3 * Copyright 1994 Eric Youndale & Erik Bos
4 * Copyright 1995 Martin von Löwis
6 * based on Eric Youndale's pe-test and:
8 * ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
10 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
18 #include <sys/types.h>
30 #include "registers.h"
35 void my_wcstombs(char * result, u_short * source, int len)
38 /* this used to be isascii, but see isascii implementation in Linux'
40 if(*source<255) *result++ = *source++;
42 printf("Unable to handle unicode right now\n");
49 char * xmmap(char * vaddr, unsigned int v_size, unsigned int r_size,
50 int prot, int flags, int fd, unsigned int file_offset)
53 /* .bss has no associated storage in the PE file */
57 #if defined(__svr4__) || defined(_SCO_DS)
58 fprintf(stderr,"xmmap: %s line %d doesn't support MAP_ANON\n",__FILE__, __LINE__);
62 result = mmap(vaddr, v_size, prot, flags, fd, file_offset);
63 if((unsigned int) result != 0xffffffff) return result;
65 /* Sigh. Alignment must be wrong for mmap. Do this the hard way. */
66 if(!(flags & MAP_FIXED)) {
67 vaddr = (char *)0x40000000;
71 mmap(vaddr, v_size, prot, MAP_ANONYMOUS | flags, 0, 0);
72 lseek(fd, file_offset, SEEK_SET);
73 read(fd, vaddr, v_size);
78 void dump_exports(struct PE_Export_Directory * pe_exports, unsigned int load_addr)
84 u_char ** name, *ename;
86 Module = ((char *) load_addr) + pe_exports->Name;
87 dprintf_win32(stddeb,"\n*******EXPORT DATA*******\nModule name is %s, %ld functions, %ld names\n",
89 pe_exports->Number_Of_Functions,
90 pe_exports->Number_Of_Names);
92 ordinal = (u_short *) (((char *) load_addr) + (int) pe_exports->Address_Of_Name_Ordinals);
93 function = (u_long *) (((char *) load_addr) + (int) pe_exports->AddressOfFunctions);
94 name = (u_char **) (((char *) load_addr) + (int) pe_exports->AddressOfNames);
96 dprintf_win32(stddeb,"%-32s Ordinal Virt Addr\n", "Function Name");
97 for(i=0; i< pe_exports->Number_Of_Functions; i++)
99 ename = (char *) (((char *) load_addr) + (int) *name++);
100 dprintf_win32(stddeb,"%-32s %4d %8.8lx\n", ename, *ordinal++, *function++);
104 static DWORD PE_FindExportedFunction(struct pe_data *pe, char* funcName)
106 struct PE_Export_Directory * exports = pe->pe_export;
107 unsigned load_addr = pe->load_addr;
110 u_char ** name, *ename;
112 if(!exports)return 0;
113 ordinal = (u_short *) (((char *) load_addr) + (int) exports->Address_Of_Name_Ordinals);
114 function = (u_long *) (((char *) load_addr) + (int) exports->AddressOfFunctions);
115 name = (u_char **) (((char *) load_addr) + (int) exports->AddressOfNames);
116 for(i=0; i<exports->Number_Of_Functions; i++)
120 ename = (char *) (((char *) load_addr) + (int) *name);
121 if(strcmp(ename,funcName)==0)
122 return load_addr+*function;
124 if(funcName == (int)*ordinal + exports->Base)
125 return load_addr+*function;
134 DWORD PE_GetProcAddress(HMODULE hModule, char* function)
138 if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
139 if (!(pModule->flags & NE_FFLAGS_WIN32) || !pModule->pe_module) return 0;
140 if (pModule->flags & NE_FFLAGS_BUILTIN)
141 return BUILTIN_GetProcAddress32( pModule, function );
142 return PE_FindExportedFunction( pModule->pe_module, function );
145 void fixup_imports(struct pe_data *pe, HMODULE hModule)
147 struct PE_Import_Directory * pe_imp;
149 unsigned int load_addr = pe->load_addr;
154 /* OK, now dump the import list */
155 dprintf_win32(stddeb, "\nDumping imports list\n");
157 /* first, count the number of imported non-internal modules */
158 pe_imp = pe->pe_import;
159 for(i=0;pe_imp->ModuleName;pe_imp++)
162 /* Now, allocate memory for dlls_to_init */
163 ne_mod = GlobalLock16(hModule);
164 ne_mod->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,(i+1) * sizeof(HMODULE),
165 hModule, FALSE, FALSE, FALSE );
166 mod_ptr = GlobalLock16(ne_mod->dlls_to_init);
167 /* load the modules and put their handles into the list */
168 for(i=0,pe_imp = pe->pe_import;pe_imp->ModuleName;pe_imp++)
170 char *name = (char*)load_addr+pe_imp->ModuleName;
171 mod_ptr[i] = LoadModule(name,(LPVOID)-1);
172 if(mod_ptr[i]<=(HMODULE)32)
174 char *p, buffer[256];
176 /* Try with prepending the path of the current module */
177 GetModuleFileName( hModule, buffer, sizeof(buffer) );
178 if (!(p = strrchr( buffer, '\\' ))) p = buffer;
179 strcpy( p + 1, name );
180 mod_ptr[i] = LoadModule( buffer, (LPVOID)-1 );
182 if(mod_ptr[i]<=(HMODULE)32)
184 fprintf(stderr,"Module %s not found\n",name);
189 pe_imp = pe->pe_import;
190 while (pe_imp->ModuleName)
193 struct pe_import_name * pe_name;
194 unsigned int * import_list, *thunk_list;
196 Module = ((char *) load_addr) + pe_imp->ModuleName;
197 dprintf_win32(stddeb, "%s\n", Module);
199 if(pe_imp->Import_List != 0) { /* original microsoft style */
200 dprintf_win32(stddeb, "Microsoft style imports used\n");
201 import_list = (unsigned int *)
202 (((unsigned int) load_addr) + pe_imp->Import_List);
203 thunk_list = (unsigned int *)
204 (((unsigned int) load_addr) + pe_imp->Thunk_List);
209 pe_name = (struct pe_import_name *) ((int) load_addr + ((unsigned)*import_list & ~0x80000000));
210 if((unsigned)*import_list & 0x80000000)
212 int ordinal=*import_list & (0x80000000-1);
213 dprintf_win32(stddeb,"--- Ordinal %s,%d\n", Module, ordinal);
214 *thunk_list = WIN32_GetProcAddress(MODULE_FindModule(Module),
218 fprintf(stderr,"No implementation for %s.%d\n",Module,
222 }else{ /* import by name */
223 dprintf_win32(stddeb, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
224 #ifndef WINELIB /* FIXME: JBP: Should this happen in libwine.a? */
225 *thunk_list = WIN32_GetProcAddress(MODULE_FindModule(Module),
229 fprintf(stderr,"No implementation for %s.%d(%s)\n",Module,
230 pe_name->Hint, pe_name->Name);
235 fprintf(stderr,"JBP: Call to RELAY32_GetEntryPoint being ignored.\n");
242 } else { /* Borland style */
243 dprintf_win32(stddeb, "Borland style imports used\n");
244 thunk_list = (unsigned int *)
245 (((unsigned int) load_addr) + pe_imp->Thunk_List);
247 pe_name = (struct pe_import_name *) ((int) load_addr + *thunk_list);
248 if((unsigned)pe_name & 0x80000000) {
249 fprintf(stderr,"Import by ordinal not supported\n");
252 dprintf_win32(stddeb, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
253 #ifndef WINELIB /* FIXME: JBP: Should this happen in libwine.a? */
254 /* FIXME: Both calls should be unified into GetProcAddress */
255 *thunk_list = WIN32_GetProcAddress(MODULE_FindModule(Module),
258 fprintf(stderr,"JBP: Call to RELAY32_GetEntryPoint being ignored.\n");
261 fprintf(stderr,"No implementation for %s.%d\n",Module, pe_name->Hint);
269 if(fixup_failed)exit(1);
272 static void calc_vma_size(struct pe_data *pe)
276 dprintf_win32(stddeb, "Dump of segment table\n");
277 dprintf_win32(stddeb, " Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
278 for(i=0; i< pe->pe_header->coff.NumberOfSections; i++)
280 dprintf_win32(stddeb, "%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
282 pe->pe_seg[i].Virtual_Size,
283 pe->pe_seg[i].Virtual_Address,
284 pe->pe_seg[i].Size_Of_Raw_Data,
285 pe->pe_seg[i].PointerToRawData,
286 pe->pe_seg[i].PointerToRelocations,
287 pe->pe_seg[i].PointerToLinenumbers,
288 pe->pe_seg[i].NumberOfRelocations,
289 pe->pe_seg[i].NumberOfLinenumbers,
290 pe->pe_seg[i].Characteristics);
291 pe->vma_size = MAX(pe->vma_size,
292 pe->pe_seg[i].Virtual_Address +
293 pe->pe_seg[i].Size_Of_Raw_Data);
297 static void do_relocations(struct pe_data *pe)
299 int delta = pe->load_addr - pe->base_addr;
300 struct PE_Reloc_Block *r = pe->pe_reloc;
301 int hdelta = (delta >> 16) & 0xFFFF;
302 int ldelta = delta & 0xFFFF;
303 /* int reloc_size = */
309 char *page = (char*)pe->load_addr + r->PageRVA;
310 int count = (r->BlockSize - 8)/2;
312 dprintf_fixup(stddeb, "%x relocations for page %lx\n",
314 /* patching in reverse order */
317 int offset = r->Relocations[i] & 0xFFF;
318 int type = r->Relocations[i] >> 12;
319 dprintf_fixup(stddeb,"patching %x type %x\n", offset, type);
322 case IMAGE_REL_BASED_ABSOLUTE: break;
323 case IMAGE_REL_BASED_HIGH:
324 *(short*)(page+offset) += hdelta;
326 case IMAGE_REL_BASED_LOW:
327 *(short*)(page+offset) += ldelta;
329 case IMAGE_REL_BASED_HIGHLOW:
331 *(int*)(page+offset) += delta;
333 { int h=*(unsigned short*)(page+offset);
334 int l=r->Relocations[++i];
335 *(unsigned int*)(page + offset) = (h<<16) + l + delta;
339 case IMAGE_REL_BASED_HIGHADJ:
340 fprintf(stderr, "Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
342 case IMAGE_REL_BASED_MIPS_JMPADDR:
343 fprintf(stderr, "Is this a MIPS machine ???\n");
346 fprintf(stderr, "Unknown fixup type\n");
350 r = (struct PE_Reloc_Block*)((char*)r + r->BlockSize);
358 /**********************************************************************
360 * Load one PE format executable into memory
362 static struct pe_data *PE_LoadImage( int fd, HMODULE hModule, WORD offset )
366 unsigned int load_addr;
367 struct Directory dir;
369 pe = xmalloc(sizeof(struct pe_data));
370 memset(pe,0,sizeof(struct pe_data));
371 pe->pe_header = xmalloc(sizeof(struct pe_header_s));
374 lseek( fd, offset, SEEK_SET);
375 read( fd, pe->pe_header, sizeof(struct pe_header_s));
378 pe->pe_seg = xmalloc(sizeof(struct pe_segment_table) *
379 pe->pe_header->coff.NumberOfSections);
380 read( fd, pe->pe_seg, sizeof(struct pe_segment_table) *
381 pe->pe_header->coff.NumberOfSections);
383 load_addr = pe->pe_header->opt_coff.BaseOfImage;
384 pe->base_addr=load_addr;
386 dprintf_win32(stddeb, "Load addr is %x\n",load_addr);
389 /* We use malloc here, while a huge part of that address space does
390 not be supported by actual memory. It has to be contiguous, though.
391 I don't know if mmap("/dev/null"); would do any better.
392 What I'd really like to do is a Win32 style VirtualAlloc/MapViewOfFile
394 load_addr = pe->load_addr = malloc(pe->vma_size);
395 dprintf_win32(stddeb, "Load addr is really %x, range %x\n",
396 pe->load_addr, pe->vma_size);
399 for(i=0; i < pe->pe_header->coff.NumberOfSections; i++)
401 /* load only non-BSS segments */
402 if(pe->pe_seg[i].Characteristics &
403 ~ IMAGE_SCN_TYPE_CNT_UNINITIALIZED_DATA)
404 if(lseek(fd,pe->pe_seg[i].PointerToRawData,SEEK_SET) == -1
405 || read(fd,load_addr + pe->pe_seg[i].Virtual_Address,
406 pe->pe_seg[i].Size_Of_Raw_Data)
407 != pe->pe_seg[i].Size_Of_Raw_Data)
409 fprintf(stderr,"Failed to load section %x\n", i);
412 result = load_addr + pe->pe_seg[i].Virtual_Address;
416 result = (int)xmmap((char *)0, pe->pe_seg[i].Virtual_Size,
417 pe->pe_seg[i].Size_Of_Raw_Data, 7,
418 MAP_PRIVATE, fd, pe->pe_seg[i].PointerToRawData);
419 load_addr = (unsigned int) result - pe->pe_seg[i].Virtual_Address;
421 result = (int)xmmap((char *) load_addr + pe->pe_seg[i].Virtual_Address,
422 pe->pe_seg[i].Virtual_Size,
423 pe->pe_seg[i].Size_Of_Raw_Data, 7, MAP_PRIVATE | MAP_FIXED,
424 fd, pe->pe_seg[i].PointerToRawData);
427 fprintf(stderr,"Could not load section %x to desired address %lx\n",
428 i, load_addr+pe->pe_seg[i].Virtual_Address);
429 fprintf(stderr,"Need to implement relocations now\n");
434 if(strcmp(pe->pe_seg[i].Name, ".bss") == 0)
435 memset((void *)result, 0,
436 pe->pe_seg[i].Virtual_Size ?
437 pe->pe_seg[i].Virtual_Size :
438 pe->pe_seg[i].Size_Of_Raw_Data);
440 if(strcmp(pe->pe_seg[i].Name, ".idata") == 0)
441 pe->pe_import = (struct PE_Import_Directory *) result;
443 if(strcmp(pe->pe_seg[i].Name, ".edata") == 0)
444 pe->pe_export = (struct PE_Export_Directory *) result;
446 if(strcmp(pe->pe_seg[i].Name, ".rsrc") == 0) {
447 pe->pe_resource = (struct PE_Resource_Directory *) result;
449 /* FIXME pe->resource_offset should be deleted from structure if this
450 ifdef doesn't break anything */
451 /* save offset for PE_FindResource */
452 pe->resource_offset = pe->pe_seg[i].Virtual_Address -
453 pe->pe_seg[i].PointerToRawData;
456 if(strcmp(pe->pe_seg[i].Name, ".reloc") == 0)
457 pe->pe_reloc = (struct PE_Reloc_Block *) result;
461 /* There is word that the actual loader does not care about the
462 section names, and only goes for the DataDirectory */
463 dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
467 pe->pe_export!=load_addr+dir.Virtual_address)
468 fprintf(stderr,"wrong export directory??\n");
469 /* always trust the directory */
470 pe->pe_export = load_addr+dir.Virtual_address;
473 dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
477 pe->pe_import!=load_addr+dir.Virtual_address)
478 fprintf(stderr,"wrong import directory??\n");
479 pe->pe_import = load_addr+dir.Virtual_address;
482 dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
485 if(pe->pe_resource &&
486 pe->pe_resource!=load_addr+dir.Virtual_address)
487 fprintf(stderr,"wrong resource directory??\n");
488 pe->pe_resource = load_addr+dir.Virtual_address;
491 dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_BASE_RELOCATION_TABLE];
495 pe->pe_reloc!=load_addr+dir.Virtual_address)
496 fprintf(stderr,"wrong relocation list??\n");
497 pe->pe_reloc = load_addr+dir.Virtual_address;
500 if(pe->pe_header->opt_coff.DataDirectory
501 [IMAGE_FILE_EXCEPTION_DIRECTORY].Size)
502 dprintf_win32(stdnimp,"Exception directory ignored\n");
504 if(pe->pe_header->opt_coff.DataDirectory
505 [IMAGE_FILE_SECURITY_DIRECTORY].Size)
506 dprintf_win32(stdnimp,"Security directory ignored\n");
508 if(pe->pe_header->opt_coff.DataDirectory
509 [IMAGE_FILE_DEBUG_DIRECTORY].Size)
510 dprintf_win32(stdnimp,"Debug directory ignored\n");
512 if(pe->pe_header->opt_coff.DataDirectory
513 [IMAGE_FILE_DESCRIPTION_STRING].Size)
514 dprintf_win32(stdnimp,"Description string ignored\n");
516 if(pe->pe_header->opt_coff.DataDirectory
517 [IMAGE_FILE_MACHINE_VALUE].Size)
518 dprintf_win32(stdnimp,"Machine Value ignored\n");
520 if(pe->pe_header->opt_coff.DataDirectory
521 [IMAGE_FILE_THREAD_LOCAL_STORAGE].Size)
522 dprintf_win32(stdnimp,"Thread local storage ignored\n");
524 if(pe->pe_header->opt_coff.DataDirectory
525 [IMAGE_FILE_CALLBACK_DIRECTORY].Size)
526 dprintf_win32(stdnimp,"Callback directory ignored\n");
529 if(pe->pe_import) fixup_imports(pe, hModule);
530 if(pe->pe_export) dump_exports(pe->pe_export,load_addr);
531 if(pe->pe_reloc) do_relocations(pe);
535 HINSTANCE MODULE_CreateInstance(HMODULE hModule,LOADPARAMS *params);
536 void InitTask(SIGCONTEXT context);
538 HINSTANCE PE_LoadModule( int fd, OFSTRUCT *ofs, LOADPARAMS* params )
543 SEGTABLEENTRY *pSegment;
548 struct mz_header_s mz_header;
550 lseek(fd,0,SEEK_SET);
551 read( fd, &mz_header, sizeof(mz_header) );
553 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
554 + strlen(ofs->szPathName) + 1;
555 size = sizeof(NE_MODULE) +
556 /* loaded file info */
558 /* segment table: DS,CS */
559 2 * sizeof(SEGTABLEENTRY) +
562 /* several empty tables */
565 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
566 if (!hModule) return (HINSTANCE)11; /* invalid exe */
568 FarSetOwner( hModule, hModule );
570 pModule = (NE_MODULE*)GlobalLock16(hModule);
572 /* Set all used entries */
573 pModule->magic=NE_SIGNATURE;
576 pModule->flags=NE_FFLAGS_WIN32;
580 /* Who wants to LocalAlloc for a PE Module? */
581 pModule->heap_size=0x1000;
582 pModule->stack_size=0xF000;
583 pModule->seg_count=1;
584 pModule->modref_count=0;
585 pModule->nrname_size=0;
586 pModule->fileinfo=sizeof(NE_MODULE);
587 pModule->os_flags=NE_OSFLAGS_WINDOWS;
588 pModule->expected_version=0x30A;
589 pModule->self = hModule;
591 /* Set loaded file information */
592 memcpy( pModule + 1, ofs, of_size );
593 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
595 pSegment=(SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
596 pModule->seg_table=pModule->dgroup_entry=(int)pSegment-(int)pModule;
598 pSegment->flags=NE_SEGFLAGS_DATA;
599 pSegment->minsize=0x1000;
602 cts=(DWORD)MODULE_GetWndProcEntry16("Win32CallToStart");
604 pSegment->selector=(void*)cts;
607 pSegment->selector=cts>>16; /* FIXME!! */
608 pModule->ip=cts & 0xFFFF;
612 pStr=(char*)pSegment;
613 pModule->name_table=(int)pStr-(int)pModule;
614 strcpy(pStr,"\x08W32SXXXX");
617 /* All tables zero terminated */
618 pModule->res_table=pModule->import_table=pModule->entry_table=
619 (int)pStr-(int)pModule;
621 MODULE_RegisterModule( pModule );
623 pe = PE_LoadImage( fd, hModule, mz_header.ne_offset );
625 pModule->pe_module = pe;
626 pModule->heap_size=0x1000;
627 pModule->stack_size=0xE000;
629 /* CreateInstance allocates now 64KB */
630 hInstance=MODULE_CreateInstance(hModule,NULL /* FIX: NULL? really? */);
632 /* FIXME: Is this really the correct place to initialise the DLL? */
633 if ((pe->pe_header->coff.Characteristics & IMAGE_FILE_DLL)) {
634 /* PE_InitDLL(hModule); */
636 TASK_CreateTask(hModule,hInstance,0,
637 params->hEnvironment,(LPSTR)PTR_SEG_TO_LIN(params->cmdLine),
638 *((WORD*)PTR_SEG_TO_LIN(params->showCmd)+1));
639 PE_InitializeDLLs(hModule);
644 int USER_InitApp(HINSTANCE hInstance);
645 void PE_InitTEB(int hTEB);
647 void PE_Win32CallToStart(SIGCONTEXT context)
653 dprintf_win32(stddeb,"Going to start Win32 program\n");
655 hModule = GetExePtr( GetCurrentTask() );
656 pModule = MODULE_GetPtr( hModule );
657 USER_InitApp( hModule );
658 fs=(int)GlobalAlloc16(GHND,0x10000);
660 __asm__ __volatile__("movw %w0,%%fs"::"r" (fs));
661 CallTaskStart32( (FARPROC)(pModule->pe_module->load_addr +
662 pModule->pe_module->pe_header->opt_coff.AddressOfEntryPoint) );
665 int PE_UnloadImage( HMODULE hModule )
667 printf("PEunloadImage() called!\n");
668 /* free resources, image, unmap */
672 static void PE_InitDLL(HMODULE hModule)
677 hModule = GetExePtr(hModule);
678 if (!(pModule = MODULE_GetPtr(hModule))) return;
679 if (!(pModule->flags & NE_FFLAGS_WIN32) || !(pe = pModule->pe_module))
682 /* FIXME: What are the correct values for parameters 2 and 3? */
684 /* Is this a library? */
685 if (pe->pe_header->coff.Characteristics & IMAGE_FILE_DLL)
687 printf("InitPEDLL() called!\n");
688 CallDLLEntryProc32( (FARPROC)(pe->load_addr +
689 pe->pe_header->opt_coff.AddressOfEntryPoint),
695 /* FIXME: This stuff is all on a "well it works" basis. An implementation
696 based on some kind of documentation would be greatly appreciated :-) */
703 struct TEB *TEBDSAlias;
708 void PE_InitTEB(int hTEB)
713 pTask = (TDB *)(GlobalLock16(GetCurrentTask() & 0xffff));
714 pTEB = (TEB *)(PTR_SEG_OFF_TO_LIN(hTEB, 0));
715 pTEB->stack = (void *)(GlobalLock16(pTask->hStack32));
716 pTEB->Except = (void *)(-1);
717 pTEB->TEBDSAlias = pTEB;
718 pTEB->taskid = getpid();
721 void PE_InitializeDLLs(HMODULE hModule)
725 pModule = MODULE_GetPtr( GetExePtr(hModule) );
726 if (pModule->dlls_to_init)
728 HANDLE to_init = pModule->dlls_to_init;
729 pModule->dlls_to_init = 0;
730 for (pDLL = (HMODULE *)GlobalLock16( to_init ); *pDLL; pDLL++)
732 PE_InitializeDLLs( *pDLL );
735 GlobalFree16( to_init );
737 PE_InitDLL( hModule );