Update the modemn status bit that indicates whether the RLSD line is
[wine.git] / loader / pe_image.c
blob5c282f4b7c72ba23795aec6bcf6583df31c73353
1 /*
2 * Copyright 1994 Eric Youndale & Erik Bos
3 * Copyright 1995 Martin von Löwis
4 * Copyright 1996-98 Marcus Meissner
6 * based on Eric Youndale's pe-test and:
8 * ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
9 * make that:
10 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
12 /* Notes:
13 * Before you start changing something in this file be aware of the following:
15 * - There are several functions called recursively. In a very subtle and
16 * obscure way. DLLs can reference each other recursively etc.
17 * - If you want to enhance, speed up or clean up something in here, think
18 * twice WHY it is implemented in that strange way. There is usually a reason.
19 * Though sometimes it might just be lazyness ;)
20 * - In PE_MapImage, right before fixup_imports() all external and internal
21 * state MUST be correct since this function can be called with the SAME image
22 * AGAIN. (Thats recursion for you.) That means MODREF.module and
23 * NE_MODULE.module32.
24 * - No, you (usually) cannot use Linux mmap() to mmap() the images directly.
26 * The problem is, that there is not direct 1:1 mapping from a diskimage and
27 * a memoryimage. The headers at the start are mapped linear, but the sections
28 * are not. For x86 the sections are 512 byte aligned in file and 4096 byte
29 * aligned in memory. Linux likes them 4096 byte aligned in memory (due to
30 * x86 pagesize, this cannot be fixed without a rather large kernel rewrite)
31 * and 'blocksize' file-aligned (offsets). Since we have 512/1024/2048 (CDROM)
32 * and other byte blocksizes, we can't do this. However, this could be less
33 * difficult to support... (See mm/filemap.c).
34 * - All those function map things into a new addresspace. From the wrong
35 * process and the wrong thread. So calling other API functions will mess
36 * things up badly sometimes.
39 #include <errno.h>
40 #include <assert.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/mman.h>
47 #include "windows.h"
48 #include "winbase.h"
49 #include "callback.h"
50 #include "file.h"
51 #include "heap.h"
52 #include "neexe.h"
53 #include "peexe.h"
54 #include "process.h"
55 #include "thread.h"
56 #include "pe_image.h"
57 #include "module.h"
58 #include "global.h"
59 #include "task.h"
60 #include "snoop.h"
61 #include "debug.h"
63 static void PE_InitDLL(WINE_MODREF *wm, DWORD type, LPVOID lpReserved);
65 /* convert PE image VirtualAddress to Real Address */
66 #define RVA(x) ((unsigned int)load_addr+(unsigned int)(x))
68 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
70 void dump_exports( HMODULE32 hModule )
72 char *Module;
73 int i, j;
74 u_short *ordinal;
75 u_long *function,*functions;
76 u_char **name;
77 unsigned int load_addr = hModule;
79 DWORD rva_start = PE_HEADER(hModule)->OptionalHeader
80 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
81 DWORD rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
82 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
83 IMAGE_EXPORT_DIRECTORY *pe_exports = (IMAGE_EXPORT_DIRECTORY*)RVA(rva_start);
85 Module = (char*)RVA(pe_exports->Name);
86 TRACE(win32,"*******EXPORT DATA*******\n");
87 TRACE(win32,"Module name is %s, %ld functions, %ld names\n",
88 Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
90 ordinal=(u_short*) RVA(pe_exports->AddressOfNameOrdinals);
91 functions=function=(u_long*) RVA(pe_exports->AddressOfFunctions);
92 name=(u_char**) RVA(pe_exports->AddressOfNames);
94 TRACE(win32," Ord RVA Addr Name\n" );
95 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
97 if (!*function) continue; /* No such function */
98 if (TRACE_ON(win32)){
99 dbg_decl_str(win32, 1024);
101 dsprintf(win32,"%4ld %08lx %08x",
102 i + pe_exports->Base, *function, RVA(*function) );
103 /* Check if we have a name for it */
104 for (j = 0; j < pe_exports->NumberOfNames; j++)
105 if (ordinal[j] == i)
106 dsprintf(win32, " %s", (char*)RVA(name[j]) );
107 if ((*function >= rva_start) && (*function <= rva_end))
108 dsprintf(win32, " (forwarded -> %s)", (char *)RVA(*function));
109 TRACE(win32,"%s\n", dbg_str(win32));
114 /* Look up the specified function or ordinal in the exportlist:
115 * If it is a string:
116 * - look up the name in the Name list.
117 * - look up the ordinal with that index.
118 * - use the ordinal as offset into the functionlist
119 * If it is a ordinal:
120 * - use ordinal-pe_export->Base as offset into the functionlist
122 FARPROC32 PE_FindExportedFunction(
123 PDB32 *process, /* [in] process context */
124 WINE_MODREF *wm, /* [in] WINE modreference */
125 LPCSTR funcName ) /* [in] function name */
127 u_short * ordinal;
128 u_long * function;
129 u_char ** name, *ename;
130 int i;
131 PE_MODREF *pem = &(wm->binfmt.pe);
132 IMAGE_EXPORT_DIRECTORY *exports = pem->pe_export;
133 unsigned int load_addr = wm->module;
134 u_long rva_start, rva_end, addr;
135 char * forward;
137 if (HIWORD(funcName))
138 TRACE(win32,"(%s)\n",funcName);
139 else
140 TRACE(win32,"(%d)\n",(int)funcName);
141 if (!exports) {
142 /* Not a fatal problem, some apps do
143 * GetProcAddress(0,"RegisterPenApp") which triggers this
144 * case.
146 WARN(win32,"Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,pem);
147 return NULL;
149 ordinal = (u_short*) RVA(exports->AddressOfNameOrdinals);
150 function= (u_long*) RVA(exports->AddressOfFunctions);
151 name = (u_char **) RVA(exports->AddressOfNames);
152 forward = NULL;
153 rva_start = PE_HEADER(wm->module)->OptionalHeader
154 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
155 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
156 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
158 if (HIWORD(funcName)) {
159 for(i=0; i<exports->NumberOfNames; i++) {
160 ename=(char*)RVA(*name);
161 if(!strcmp(ename,funcName))
163 addr = function[*ordinal];
164 if (!addr) return NULL;
165 if ((addr < rva_start) || (addr >= rva_end))
166 return SNOOP_GetProcAddress32(wm->module,ename,*ordinal,(FARPROC32)RVA(addr));
167 forward = (char *)RVA(addr);
168 break;
170 ordinal++;
171 name++;
173 } else {
174 int i;
175 if (LOWORD(funcName)-exports->Base > exports->NumberOfFunctions) {
176 TRACE(win32," ordinal %d out of range!\n",
177 LOWORD(funcName));
178 return NULL;
180 addr = function[(int)funcName-exports->Base];
181 if (!addr) return NULL;
182 ename = "";
183 if (name) {
184 for (i=0;i<exports->NumberOfNames;i++) {
185 ename = (char*)RVA(*name);
186 if (*ordinal == LOWORD(funcName)-exports->Base)
187 break;
188 ordinal++;
189 name++;
191 if (i==exports->NumberOfNames)
192 ename = "";
194 if ((addr < rva_start) || (addr >= rva_end))
195 return SNOOP_GetProcAddress32(wm->module,ename,(DWORD)funcName-exports->Base,(FARPROC32)RVA(addr));
196 forward = (char *)RVA(addr);
198 if (forward)
200 HMODULE32 hMod;
201 char module[256];
202 char *end = strchr(forward, '.');
204 if (!end) return NULL;
205 assert(end-forward<256);
206 strncpy(module, forward, (end - forward));
207 module[end-forward] = 0;
208 hMod = MODULE_FindModule32(process,module);
209 assert(hMod);
210 return MODULE_GetProcAddress32( process, hMod, end + 1);
212 return NULL;
215 DWORD fixup_imports (PDB32 *process,WINE_MODREF *wm)
217 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
218 WINE_MODREF *xwm;
219 PE_MODREF *pem;
220 unsigned int load_addr = wm->module;
221 int i;
222 char *modname;
224 assert(wm->type==MODULE32_PE);
225 pem = &(wm->binfmt.pe);
226 if (pem->pe_export)
227 modname = (char*) RVA(pem->pe_export->Name);
228 else
229 modname = "<unknown>";
231 /* OK, now dump the import list */
232 TRACE(win32, "Dumping imports list\n");
234 /* first, count the number of imported non-internal modules */
235 pe_imp = pem->pe_import;
236 if (!pe_imp)
237 ERR(win32, "no import directory????\n");
239 /* FIXME: should terminate on 0 Characteristics */
240 for (i = 0; pe_imp->Name; pe_imp++)
241 i++;
243 /* load the imported modules. They are automatically
244 * added to the modref list of the process.
247 /* FIXME: should terminate on 0 Characteristics */
248 for (i = 0, pe_imp = pem->pe_import; pe_imp->Name; pe_imp++) {
249 HMODULE32 hImpModule;
250 WINE_MODREF **ywm;
251 IMAGE_IMPORT_BY_NAME *pe_name;
252 LPIMAGE_THUNK_DATA import_list,thunk_list;
253 char *name = (char *) RVA(pe_imp->Name);
255 /* don't use MODULE_Load, Win32 creates new task differently */
256 hImpModule = MODULE_LoadLibraryEx32A( name, process, 0, 0 );
257 if (!hImpModule) {
258 char *p,buffer[2000];
260 /* GetModuleFileName would use the wrong process, so don't use it */
261 strcpy(buffer,wm->shortname);
262 if (!(p = strrchr (buffer, '\\')))
263 p = buffer;
264 strcpy (p + 1, name);
265 hImpModule = MODULE_LoadLibraryEx32A( buffer, process, 0, 0 );
267 if (!hImpModule) {
268 ERR (module, "Module %s not found\n", name);
269 return 1;
271 xwm = wm->next;
272 while (xwm) {
273 if (xwm->module == hImpModule)
274 break;
275 xwm = xwm->next;
277 if (xwm) {
278 /* It has been loaded *BEFORE* us, so we have to initialize
279 * it before us. We cannot just link in the xwm before wm,
280 * since xwm might reference more dlls which would be in the
281 * wrong order after that.
282 * Instead we link in wm right AFTER xwm, which should keep
283 * the correct order. (I am not 100% sure about that.)
285 /* unlink wm from chain */
286 ywm = &(process->modref_list);
287 while (*ywm) {
288 if ((*ywm)==wm)
289 break;
290 ywm = &((*ywm)->next);
292 *ywm = wm->next;
294 /* link wm directly AFTER xwm */
295 wm->next = xwm->next;
296 xwm->next = wm;
299 i++;
301 /* FIXME: forwarder entries ... */
303 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
304 TRACE(win32, "Microsoft style imports used\n");
305 import_list =(LPIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
306 thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
308 while (import_list->u1.Ordinal) {
309 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
310 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
312 TRACE(win32, "--- Ordinal %s,%d\n", name, ordinal);
313 thunk_list->u1.Function=MODULE_GetProcAddress32(
314 process, hImpModule, (LPCSTR)ordinal
316 if (!thunk_list->u1.Function) {
317 ERR(win32,"No implementation for %s.%d, setting to 0xdeadbeef\n",
318 name, ordinal);
319 thunk_list->u1.Function = (FARPROC32)0xdeadbeef;
321 } else { /* import by name */
322 pe_name = (LPIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
323 TRACE(win32, "--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
324 thunk_list->u1.Function=MODULE_GetProcAddress32(
325 process, hImpModule, pe_name->Name
327 if (!thunk_list->u1.Function) {
328 ERR(win32,"No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
329 name,pe_name->Hint,pe_name->Name);
330 thunk_list->u1.Function = (FARPROC32)0xdeadbeef;
333 import_list++;
334 thunk_list++;
336 } else { /* Borland style */
337 TRACE(win32, "Borland style imports used\n");
338 thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
339 while (thunk_list->u1.Ordinal) {
340 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
341 /* not sure about this branch, but it seems to work */
342 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
344 TRACE(win32,"--- Ordinal %s.%d\n",name,ordinal);
345 thunk_list->u1.Function=MODULE_GetProcAddress32(
346 process, hImpModule, (LPCSTR) ordinal
348 if (!thunk_list->u1.Function) {
349 ERR(win32, "No implementation for %s.%d, setting to 0xdeadbeef\n",
350 name,ordinal);
351 thunk_list->u1.Function = (FARPROC32)0xdeadbeef;
353 } else {
354 pe_name=(LPIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
355 TRACE(win32,"--- %s %s.%d\n",
356 pe_name->Name,name,pe_name->Hint);
357 thunk_list->u1.Function=MODULE_GetProcAddress32(
358 process, hImpModule, pe_name->Name
360 if (!thunk_list->u1.Function) {
361 ERR(win32, "No implementation for %s.%d, setting to 0xdeadbeef\n",
362 name, pe_name->Hint);
363 thunk_list->u1.Function = (FARPROC32)0xdeadbeef;
366 thunk_list++;
370 return 0;
373 static int calc_vma_size( HMODULE32 hModule )
375 int i,vma_size = 0;
376 IMAGE_SECTION_HEADER *pe_seg = PE_SECTIONS(hModule);
378 TRACE(win32, "Dump of segment table\n");
379 TRACE(win32, " Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
380 for (i = 0; i< PE_HEADER(hModule)->FileHeader.NumberOfSections; i++)
382 TRACE(win32, "%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
383 pe_seg->Name,
384 pe_seg->Misc.VirtualSize,
385 pe_seg->VirtualAddress,
386 pe_seg->SizeOfRawData,
387 pe_seg->PointerToRawData,
388 pe_seg->PointerToRelocations,
389 pe_seg->PointerToLinenumbers,
390 pe_seg->NumberOfRelocations,
391 pe_seg->NumberOfLinenumbers,
392 pe_seg->Characteristics);
393 vma_size = MAX(vma_size, pe_seg->VirtualAddress+pe_seg->SizeOfRawData);
394 pe_seg++;
396 return vma_size;
399 static void do_relocations(WINE_MODREF *wm)
401 PE_MODREF *pem = &(wm->binfmt.pe);
402 int delta = wm->module - PE_HEADER(wm->module)->OptionalHeader.ImageBase;
403 unsigned int load_addr= wm->module;
405 IMAGE_BASE_RELOCATION *r = pem->pe_reloc;
406 int hdelta = (delta >> 16) & 0xFFFF;
407 int ldelta = delta & 0xFFFF;
409 /* int reloc_size = */
411 if(delta == 0)
412 /* Nothing to do */
413 return;
414 while(r->VirtualAddress)
416 char *page = (char*) RVA(r->VirtualAddress);
417 int count = (r->SizeOfBlock - 8)/2;
418 int i;
419 TRACE(fixup, "%x relocations for page %lx\n",
420 count, r->VirtualAddress);
421 /* patching in reverse order */
422 for(i=0;i<count;i++)
424 int offset = r->TypeOffset[i] & 0xFFF;
425 int type = r->TypeOffset[i] >> 12;
426 TRACE(fixup,"patching %x type %x\n", offset, type);
427 switch(type)
429 case IMAGE_REL_BASED_ABSOLUTE: break;
430 case IMAGE_REL_BASED_HIGH:
431 *(short*)(page+offset) += hdelta;
432 break;
433 case IMAGE_REL_BASED_LOW:
434 *(short*)(page+offset) += ldelta;
435 break;
436 case IMAGE_REL_BASED_HIGHLOW:
437 #if 1
438 *(int*)(page+offset) += delta;
439 #else
440 { int h=*(unsigned short*)(page+offset);
441 int l=r->TypeOffset[++i];
442 *(unsigned int*)(page + offset) = (h<<16) + l + delta;
444 #endif
445 break;
446 case IMAGE_REL_BASED_HIGHADJ:
447 WARN(win32, "Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
448 break;
449 case IMAGE_REL_BASED_MIPS_JMPADDR:
450 WARN(win32, "Is this a MIPS machine ???\n");
451 break;
452 default:
453 WARN(win32, "Unknown fixup type\n");
454 break;
457 r = (IMAGE_BASE_RELOCATION*)((char*)r + r->SizeOfBlock);
465 /**********************************************************************
466 * PE_LoadImage
467 * Load one PE format DLL/EXE into memory
469 * Unluckily we can't just mmap the sections where we want them, for
470 * (at least) Linux does only support offsets which are page-aligned.
472 * BUT we have to map the whole image anyway, for Win32 programs sometimes
473 * want to access them. (HMODULE32 point to the start of it)
475 static HMODULE32 PE_LoadImage( HFILE32 hFile )
477 HMODULE32 hModule;
478 HANDLE32 mapping;
479 int i,rawsize = 0;
480 IMAGE_SECTION_HEADER *pe_sec;
481 BY_HANDLE_FILE_INFORMATION bhfi;
484 /* map the PE file somewhere */
485 mapping = CreateFileMapping32A( hFile, NULL, PAGE_READONLY | SEC_COMMIT,
486 0, 0, NULL );
487 if (!mapping)
489 WARN( win32, "CreateFileMapping error %ld\n",
490 GetLastError() );
491 return 0;
493 hModule = (HMODULE32)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
494 CloseHandle( mapping );
495 if (!hModule)
497 WARN( win32, "PE_LoadImage: MapViewOfFile error %ld\n",
498 GetLastError() );
499 return 0;
502 if (PE_HEADER(hModule)->Signature != IMAGE_NT_SIGNATURE)
504 WARN(win32,"image doesn't have PE signature, but 0x%08lx\n",
505 PE_HEADER(hModule)->Signature );
506 goto error;
509 if (PE_HEADER(hModule)->FileHeader.Machine != IMAGE_FILE_MACHINE_I386)
511 MSG("Trying to load PE image for unsupported architecture (");
512 switch (PE_HEADER(hModule)->FileHeader.Machine)
514 case IMAGE_FILE_MACHINE_UNKNOWN: MSG("Unknown\n"); break;
515 case IMAGE_FILE_MACHINE_I860: MSG("I860\n"); break;
516 case IMAGE_FILE_MACHINE_R3000: MSG("R3000\n"); break;
517 case IMAGE_FILE_MACHINE_R4000: MSG("R4000\n"); break;
518 case IMAGE_FILE_MACHINE_R10000: MSG("R10000\n"); break;
519 case IMAGE_FILE_MACHINE_ALPHA: MSG("Alpha\n"); break;
520 case IMAGE_FILE_MACHINE_POWERPC: MSG("PowerPC\n"); break;
521 default: MSG("Unknown-%04x\n",
522 PE_HEADER(hModule)->FileHeader.Machine); break;
524 goto error;
526 /* find out how large this executeable should be */
527 pe_sec = PE_SECTIONS(hModule);
528 for (i=0;i<PE_HEADER(hModule)->FileHeader.NumberOfSections;i++) {
529 if (pe_sec[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
530 continue;
531 if (pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData > rawsize)
532 rawsize = pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData;
534 if (GetFileInformationByHandle(hFile,&bhfi)) {
535 /* FIXME: 64 bit */
536 if (bhfi.nFileSizeLow < rawsize) {
537 ERR(win32,"PE module is too small (header: %d, filesize: %d), probably truncated download?\n",rawsize,bhfi.nFileSizeLow);
538 goto error;
541 /* Else ... Hmm, we have opened it, so we should be able to get info?
542 * Anyway, don't care in this case
544 return hModule;
546 error:
547 UnmapViewOfFile( (LPVOID)hModule );
548 return 0;
551 /**********************************************************************
552 * This maps a loaded PE dll into the address space of the specified process.
554 static BOOL32 PE_MapImage( PDB32 *process,WINE_MODREF *wm, OFSTRUCT *ofs, DWORD flags )
556 PE_MODREF *pem;
557 int i, result;
558 DWORD load_addr;
559 IMAGE_DATA_DIRECTORY dir;
560 char *modname;
561 int vma_size;
562 HMODULE32 hModule = wm->module;
564 IMAGE_SECTION_HEADER *pe_seg;
565 IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)hModule;
566 IMAGE_NT_HEADERS *nt_header = PE_HEADER(hModule);
568 pem = &(wm->binfmt.pe);
570 result = GetLongPathName32A(ofs->szPathName,NULL,0);
571 wm->longname = (char*)HeapAlloc(process->heap,0,result+1);
572 GetLongPathName32A(ofs->szPathName,wm->longname,result+1);
574 wm->shortname = HEAP_strdupA(process->heap,0,ofs->szPathName);
576 if (!(nt_header->FileHeader.Characteristics & IMAGE_FILE_DLL))
578 if (process->exe_modref)
579 FIXME(win32,"overwriting old exe_modref... arrgh\n");
580 process->exe_modref = wm;
583 load_addr = nt_header->OptionalHeader.ImageBase;
584 vma_size = calc_vma_size( hModule );
585 TRACE(win32, "Load addr is %lx\n",load_addr);
586 load_addr = (DWORD)VirtualAlloc( (void*)load_addr, vma_size,
587 MEM_RESERVE | MEM_COMMIT,
588 PAGE_EXECUTE_READWRITE );
589 if (load_addr == 0) {
590 load_addr = (DWORD)VirtualAlloc( NULL, vma_size,
591 MEM_RESERVE | MEM_COMMIT,
592 PAGE_EXECUTE_READWRITE );
594 /* NOTE: this changes a value in the process modref chain, which can
595 * be accessed independently from this function
597 wm->module = (HMODULE32)load_addr;
599 TRACE(win32, "Load addr is really %lx, range %x\n",
600 load_addr, vma_size);
602 TRACE(segment, "Loading %s at %lx, range %x\n",
603 ofs->szPathName, load_addr, vma_size );
605 /* Store the NT header at the load addr
606 * (FIXME: should really use mmap)
608 *(IMAGE_DOS_HEADER *)load_addr = *dos_header;
609 *(IMAGE_NT_HEADERS *)(load_addr + dos_header->e_lfanew) = *nt_header;
610 memcpy(PE_SECTIONS(load_addr),PE_SECTIONS(hModule),sizeof(IMAGE_SECTION_HEADER)*nt_header->FileHeader.NumberOfSections);
612 pe_seg = PE_SECTIONS(hModule);
613 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++, pe_seg++)
615 /* memcpy only non-BSS segments */
616 /* FIXME: this should be done by mmap(..MAP_PRIVATE|MAP_FIXED..)
617 * but it is not possible for (at least) Linux needs
618 * a page-aligned offset.
620 if(!(pe_seg->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
621 memcpy((char*)RVA(pe_seg->VirtualAddress),
622 (char*)(hModule + pe_seg->PointerToRawData),
623 pe_seg->SizeOfRawData
626 result = RVA (pe_seg->VirtualAddress);
627 #if 1
628 /* not needed, memory is zero */
629 if(strcmp(pe_seg->Name, ".bss") == 0)
630 memset((void *)result, 0,
631 pe_seg->Misc.VirtualSize ?
632 pe_seg->Misc.VirtualSize :
633 pe_seg->SizeOfRawData);
634 #endif
636 if(strcmp(pe_seg->Name, ".idata") == 0)
637 pem->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) result;
639 if(strcmp(pe_seg->Name, ".edata") == 0)
640 pem->pe_export = (LPIMAGE_EXPORT_DIRECTORY) result;
642 if(strcmp(pe_seg->Name, ".rsrc") == 0)
643 pem->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) result;
645 if(strcmp(pe_seg->Name, ".reloc") == 0)
646 pem->pe_reloc = (LPIMAGE_BASE_RELOCATION) result;
649 /* There is word that the actual loader does not care about the
650 section names, and only goes for the DataDirectory */
651 dir=nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
652 if(dir.Size)
654 if(pem->pe_export && (int)pem->pe_export!=RVA(dir.VirtualAddress))
655 WARN(win32,"wrong export directory??\n");
656 /* always trust the directory */
657 pem->pe_export = (LPIMAGE_EXPORT_DIRECTORY) RVA(dir.VirtualAddress);
660 dir=nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
661 if(dir.Size)
664 if(pem->pe_import && (int)pem->pe_import!=RVA(dir.VirtualAddress))
665 WARN(win32,"wrong import directory??\n");
667 pem->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) RVA(dir.VirtualAddress);
670 dir=nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
671 if(dir.Size)
673 if(pem->pe_resource && (int)pem->pe_resource!=RVA(dir.VirtualAddress))
674 WARN(win32,"wrong resource directory??\n");
675 pem->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) RVA(dir.VirtualAddress);
678 if(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size)
679 FIXME(win32,"Exception directory ignored\n");
681 if(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size)
682 FIXME(win32,"Security directory ignored\n");
686 dir=nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
687 if(dir.Size)
689 if(pem->pe_reloc && (int)pem->pe_reloc!= RVA(dir.VirtualAddress))
690 WARN(win32,"wrong relocation list??\n");
691 pem->pe_reloc = (void *) RVA(dir.VirtualAddress);
694 if(nt_header->OptionalHeader.DataDirectory
695 [IMAGE_DIRECTORY_ENTRY_COPYRIGHT].Size)
696 FIXME(win32,"Copyright string ignored\n");
698 if(nt_header->OptionalHeader.DataDirectory
699 [IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size)
700 FIXME(win32,"Global Pointer (MIPS) ignored\n");
702 if(nt_header->OptionalHeader.DataDirectory
703 [IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size)
704 FIXME(win32,"Load Configuration directory ignored\n");
706 if(nt_header->OptionalHeader.DataDirectory
707 [IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size)
708 TRACE(win32,"Bound Import directory ignored\n");
710 if(nt_header->OptionalHeader.DataDirectory
711 [IMAGE_DIRECTORY_ENTRY_IAT].Size)
712 TRACE(win32,"Import Address Table directory ignored\n");
713 if(nt_header->OptionalHeader.DataDirectory[13].Size)
714 FIXME(win32,"Unknown directory 13 ignored\n");
715 if(nt_header->OptionalHeader.DataDirectory[14].Size)
716 FIXME(win32,"Unknown directory 14 ignored\n");
717 if(nt_header->OptionalHeader.DataDirectory[15].Size)
718 FIXME(win32,"Unknown directory 15 ignored\n");
720 if(pem->pe_reloc) do_relocations(wm);
721 if(pem->pe_export) {
722 dump_exports(wm->module);
724 wm->modname = HEAP_strdupA(process->heap,0,(char*)RVA(pem->pe_export->Name));
725 } else {
726 /* try to find out the name from the OFSTRUCT */
727 char *s;
728 modname = s = ofs->szPathName;
729 while ((s=strchr(modname,'\\')))
730 modname = s+1;
731 wm->modname = HEAP_strdupA(process->heap,0,modname);
733 if(pem->pe_import) {
734 if (fixup_imports(process,wm)) {
735 WINE_MODREF **xwm;
737 /* remove entry from modref chain */
738 xwm = &(process->modref_list);
739 while (*xwm) {
740 if (*xwm==wm) {
741 *xwm = wm->next;
742 break;
744 xwm = &((*xwm)->next);
746 /* FIXME: there are several more dangling references
747 * left. Including dlls loaded by this dll before the
748 * failed one. Unrolling is rather difficult with the
749 * current structure and we can leave it them lying
750 * around with no problems, so we don't care
752 return 0;
756 /* Now that we got everything at the right address,
757 * we can unmap the previous module */
758 UnmapViewOfFile( (LPVOID)hModule );
759 return 1;
762 /******************************************************************************
763 * The PE Library Loader frontend.
764 * FIXME: handle the flags.
765 * internal module handling should be made better here (and in builtin.c)
767 HMODULE32 PE_LoadLibraryEx32A (LPCSTR name, PDB32 *process,
768 HFILE32 hFile, DWORD flags)
770 OFSTRUCT ofs;
771 HMODULE32 hModule;
772 NE_MODULE *pModule;
773 WINE_MODREF *wm;
775 if ((hModule = MODULE_FindModule32( process, name ))) {
776 for (wm= process->modref_list;wm;wm=wm->next)
777 if (wm->module == hModule)
778 return hModule;
779 /* Since MODULE_FindModule32 uses the modref chain too, the
780 * module MUST have been found above. If not, something has gone
781 * terribly wrong.
783 assert(0);
785 /* try to load builtin, enabled modules first */
786 if ((hModule = BUILTIN32_LoadModule( name, FALSE, process )))
787 return hModule;
789 /* try to load the specified dll/exe */
790 if (HFILE_ERROR32==(hFile=OpenFile32(name,&ofs,OF_READ))) {
791 /* Now try the built-in even if disabled */
792 if ((hModule = BUILTIN32_LoadModule( name, TRUE, process ))) {
793 WARN( module, "Could not load external DLL '%s', using built-in module.\n", name );
794 return hModule;
796 return 0;
798 /* will go away ... */
799 if ((hModule = MODULE_CreateDummyModule( &ofs )) < 32) {
800 _lclose32(hFile);
801 return hModule;
803 pModule = (NE_MODULE *)GlobalLock16( hModule );
804 pModule->flags = NE_FFLAGS_WIN32;
805 /* .. */
807 wm=(WINE_MODREF*)HeapAlloc(process->heap,HEAP_ZERO_MEMORY,sizeof(*wm));
808 wm->type = MODULE32_PE;
809 /* NOTE: fixup_imports takes care of the correct order */
810 wm->next = process->modref_list;
811 process->modref_list = wm;
813 wm->module = pModule->module32 = PE_LoadImage( hFile );
815 CloseHandle( hFile );
816 if (wm->module < 32)
818 process->modref_list = wm->next;
819 FreeLibrary16( hModule);
820 HeapFree(process->heap,0,wm);
821 ERR(win32,"can't load %s\n",ofs.szPathName);
822 return 0;
825 /* (possible) recursion */
826 if (!PE_MapImage(process,wm,&ofs,flags)) {
827 /* ERROR cleanup ... */
828 WINE_MODREF **xwm;
830 ERR(win32,"couldn't load %s\n",ofs.szPathName);
831 /* unlink from process modref chain */
832 for ( xwm=&(process->modref_list);
833 *xwm && (*xwm!=wm);
834 xwm=&((*xwm)->next)
835 ) /* EMPTY */;
836 if (*xwm)
837 *xwm=(*xwm)->next;
839 return 0;
841 pModule->module32 = wm->module;
842 if (wm->binfmt.pe.pe_export)
843 SNOOP_RegisterDLL(wm->module,wm->modname,wm->binfmt.pe.pe_export->NumberOfFunctions);
844 return wm->module;
847 /*****************************************************************************
848 * Load the PE main .EXE. All other loading is done by PE_LoadLibraryEx32A
849 * FIXME: this function should use PE_LoadLibraryEx32A, but currently can't
850 * due to the PROCESS_Create stuff.
852 HINSTANCE16 PE_CreateProcess( LPCSTR name, LPCSTR cmd_line,
853 LPCSTR env, LPSTARTUPINFO32A startup,
854 LPPROCESS_INFORMATION info )
856 HMODULE16 hModule16;
857 HMODULE32 hModule32;
858 HINSTANCE16 hInstance;
859 NE_MODULE *pModule;
860 HFILE32 hFile;
861 OFSTRUCT ofs;
862 PDB32 *process;
863 TDB *pTask;
864 WINE_MODREF *wm;
866 if ((hFile = OpenFile32( name, &ofs, OF_READ )) == HFILE_ERROR32)
867 return 2; /* File not found */
869 if ((hModule16 = MODULE_CreateDummyModule( &ofs )) < 32) return hModule16;
870 pModule = (NE_MODULE *)GlobalLock16( hModule16 );
871 pModule->flags = NE_FFLAGS_WIN32;
873 pModule->module32 = hModule32 = PE_LoadImage( hFile );
874 if (hModule32 < 32) return 21;
876 if (PE_HEADER(hModule32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
877 return 11;
879 hInstance = NE_CreateInstance( pModule, NULL, FALSE );
880 process = PROCESS_Create( pModule, cmd_line, env,
881 hInstance, 0, startup, info );
882 pTask = (TDB *)GlobalLock16( process->task );
884 wm=(WINE_MODREF*)HeapAlloc(process->heap,HEAP_ZERO_MEMORY,sizeof(*wm));
885 wm->type = MODULE32_PE;
886 /* NOTE: fixup_imports takes care of the correct order */
887 wm->next = process->modref_list;
888 wm->module = hModule32;
889 process->modref_list = wm;
890 if (!PE_MapImage( process, wm, &ofs, 0 ))
892 /* FIXME: should destroy the task created and free referenced stuff */
893 return 0;
895 pModule->module32 = wm->module;
897 /* FIXME: Yuck. Is there no other good place to do that? */
898 PE_InitTls( pTask->thdb );
900 return hInstance;
903 /*********************************************************************
904 * PE_UnloadImage [internal]
906 int PE_UnloadImage( HMODULE32 hModule )
908 FIXME(win32,"stub.\n");
909 /* free resources, image, unmap */
910 return 1;
913 /* Called if the library is loaded or freed.
914 * NOTE: if a thread attaches a DLL, the current thread will only do
915 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
916 * (SDK)
918 static void PE_InitDLL(WINE_MODREF *wm, DWORD type,LPVOID lpReserved)
920 if (wm->type!=MODULE32_PE)
921 return;
922 if (type==DLL_PROCESS_ATTACH)
923 wm->binfmt.pe.flags |= PE_MODREF_PROCESS_ATTACHED;
925 /* DLL_ATTACH_PROCESS:
926 * lpreserved is NULL for dynamic loads, not-NULL for static loads
927 * DLL_DETACH_PROCESS:
928 * lpreserved is NULL if called by FreeLibrary, not-NULL otherwise
929 * the SDK doesn't mention anything for DLL_THREAD_*
932 /* Is this a library? And has it got an entrypoint? */
933 if ((PE_HEADER(wm->module)->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
934 (PE_HEADER(wm->module)->OptionalHeader.AddressOfEntryPoint)
936 DLLENTRYPROC32 entry = (void*)RVA_PTR( wm->module,OptionalHeader.AddressOfEntryPoint );
937 TRACE(relay, "CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
938 entry, wm->module, type, lpReserved );
939 entry( wm->module, type, lpReserved );
943 /* Call the DLLentry function of all dlls used by that process.
944 * (NOTE: this may recursively call this function (if a library calls
945 * LoadLibrary) ... but it won't matter)
947 void PE_InitializeDLLs(PDB32 *process,DWORD type,LPVOID lpReserved) {
948 WINE_MODREF *wm;
950 for (wm = process->modref_list;wm;wm=wm->next) {
951 PE_MODREF *pem = NULL;
952 if (wm->type!=MODULE32_PE)
953 continue;
954 pem = &(wm->binfmt.pe);
955 if (pem->flags & PE_MODREF_NO_DLL_CALLS)
956 continue;
957 if (type==DLL_PROCESS_ATTACH) {
958 if (pem->flags & PE_MODREF_PROCESS_ATTACHED)
959 continue;
961 PE_InitDLL( wm, type, lpReserved );
965 void PE_InitTls(THDB *thdb)
967 WINE_MODREF *wm;
968 PE_MODREF *pem;
969 IMAGE_NT_HEADERS *peh;
970 DWORD size,datasize;
971 LPVOID mem;
972 LPIMAGE_TLS_DIRECTORY pdir;
973 PDB32 *pdb = thdb->process;
974 int delta;
976 for (wm = pdb->modref_list;wm;wm=wm->next) {
977 if (wm->type!=MODULE32_PE)
978 continue;
979 pem = &(wm->binfmt.pe);
980 peh = PE_HEADER(wm->module);
981 delta = wm->module - peh->OptionalHeader.ImageBase;
982 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
983 continue;
984 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
985 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
988 if (!(pem->flags & PE_MODREF_TLS_ALLOCED)) {
989 pem->tlsindex = THREAD_TlsAlloc(thdb);
990 *(LPDWORD)AdjustPtr(pdir->AddressOfIndex,delta)
991 =pem->tlsindex;
993 pem->flags |= PE_MODREF_TLS_ALLOCED;
994 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
995 size = datasize + pdir->SizeOfZeroFill;
996 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
997 memcpy(mem,
998 AdjustPtr(pdir->StartAddressOfRawData,delta),
999 datasize);
1001 /* don't use TlsSetValue, we are in the wrong thread */
1002 if (pdir->AddressOfCallBacks) {
1003 LPIMAGE_TLS_CALLBACK *cbs =
1004 (LPIMAGE_TLS_CALLBACK *)
1005 AdjustPtr(pdir->AddressOfCallBacks, delta);
1007 if (*cbs) {
1008 FIXME(win32, "TLS Callbacks aren't going to be called\n");
1011 thdb->tls_array[pem->tlsindex] = mem;
1015 /****************************************************************************
1016 * DisableThreadLibraryCalls (KERNEL32.74)
1017 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
1019 BOOL32 WINAPI DisableThreadLibraryCalls(HMODULE32 hModule)
1021 WINE_MODREF *wm;
1023 for (wm=PROCESS_Current()->modref_list;wm;wm=wm->next)
1024 if ((wm->module == hModule) && (wm->type==MODULE32_PE))
1025 wm->binfmt.pe.flags|=PE_MODREF_NO_DLL_CALLS;
1026 return TRUE;