#include "DisAsm.h" //----< outputs string in Heading format >---- void Title ( const std::string & str, char ch ) { for ( int i = 0 ; i < ( int ) str.length() ; i ++ ) std::cout << ch ; std::cout << "\n" << str << "\n" ; for ( int i = 0 ; i < ( int ) str.length() ; i ++ ) std::cout << ch ; std::cout << "\n\n" ; } //----< Hex Dump of a section table >---- void DisplayInHex ( DWORD dwOffset, DWORD dwImageBase, DWORD dwDataSize ) { DWORD diff = ((dwOffset + dwImageBase) % 16) ; unsigned char * pAddress = ( diff == 0 ) ? (unsigned char *) (dwOffset + dwImageBase) : (unsigned char *) (dwOffset + dwImageBase - diff) ; bool flag = true ; unsigned char Buffer [16] ; SIZE_T nSize = 16 ; SIZE_T BytesRead ; int iterations = 0 ; while ( ( flag ) && ( iterations < dwDataSize / 16 ) ) { if ( ReadProcessMemory ( GetCurrentProcess(), /* view of the PE is mapped into current process */ pAddress, /* pointer to the base address to read from */ Buffer, /* pointer to a buffer that receives the contents */ nSize, /* number of bytes to be read */ & BytesRead /* actual number of bytes transferred */ ) ) { /* offset display */ //////////////////// cout << setw(15) << left << hex << showbase << (DWORD) ((DWORD)pAddress - dwImageBase) << noshowbase ; /* the actual code section dump */ ////////////////////////////////// for ( int index = 0 ; index < (int) nSize ; ++index ) { if ( Buffer[index] < 0xA ) cout << "0" << setw(2) << left << hex << (unsigned int) Buffer[index] ; else cout << setw(3) << left << hex << (unsigned int) Buffer[index] ; if ( index == nSize/2 - 1 ) /* a padding after every 8 bytes */ cout << setw(2) << left << " " ; } /* increments for next iteration */ /////////////////////////////////// pAddress = (unsigned char *) (pAddress + 0x10) ; ++ iterations ; cout << "\n" ; } else { flag = false ; if ( iterations == 0 ) cout << "Error : Unable to display code section dump !\n\n" ; } } } //----< searches for, displays the code section >---- void CodeSectionDisplay ( IMAGE_SECTION_HEADER * pImageSectionHeader, const DWORD & dwTotalSections, IMAGE_DOS_HEADER * pDosHeader ) { for ( DWORD idx = 0 ; idx < dwTotalSections ; ++idx ) /* iterate till we find code sections */ { if ( pImageSectionHeader[idx].PointerToRawData == 0 ) continue ; char cNameStr [IMAGE_SIZEOF_SHORT_NAME+1] ; memcpy ( cNameStr ,pImageSectionHeader[idx].Name, IMAGE_SIZEOF_SHORT_NAME ) ; cNameStr [IMAGE_SIZEOF_SHORT_NAME] = '\0' ; /* make it a null terminated string */ if ( //(strcmp (cNameStr, ".textbss") == 0) || (strcmp (cNameStr, ".text") == 0 ) ) { /* display */ ///////////// cout << "\n" ; Title ( "Code Section Dump", '*' ) ; cout << setw(30) << left << " section name" << " : " << cNameStr << "\n" << setw(30) << left << " size (bytes)" << " : 0x" << hex << pImageSectionHeader[idx].SizeOfRawData << "\n" << setw(30) << left << " offset in file" << " : 0x" << hex << pImageSectionHeader[idx].PointerToRawData << "\n" << setw(30) << left << " location in memory" << " : 0x" << hex << (DWORD) ((DWORD)pImageSectionHeader[idx].PointerToRawData + pDosHeader) << "\n\n" ; cout << setw(15) << left << "Offsets" << setw(50) << left << "Contents in Hex" << "\n" << setw(15) << left << "-------" << setw(50) << left << "-------------------------------------------------" << "\n\n" ; DisplayInHex ( (DWORD) pImageSectionHeader[idx].PointerToRawData, (DWORD) pDosHeader, pImageSectionHeader[idx].SizeOfRawData ) ; cout << "\n\n" ; } } } //----< convert RVA to pointer within an enclosing Section Header >---- void * RvaToPtr ( const DWORD & dwRVA, IMAGE_NT_HEADERS * pNtHeaders, IMAGE_DOS_HEADER * pDosHeader ) { /* get the correct section header */ //////////////////////////////////// IMAGE_SECTION_HEADER * pSectionHeader = IMAGE_FIRST_SECTION ( pNtHeaders ) ; IMAGE_SECTION_HEADER * pSecHeader = 0 ; for ( int i = 0 ; i < pNtHeaders->FileHeader.NumberOfSections ; ++i ) { /* does RVA fall within bounds of this section ? */ /* use pointer-index notation. no other way out. */ /////////////////////////////////////////////////// if ( ( dwRVA >= pSectionHeader[i].VirtualAddress ) && ( dwRVA <= ( pSectionHeader[i].VirtualAddress + pSectionHeader[i].Misc.VirtualSize ) ) ) { pSecHeader = & pSectionHeader[i] ; break ; } } /* assertion check */ ///////////////////// if ( pSecHeader == 0 ) return 0 ; return (void *) ( /* base of image */ (unsigned long) pDosHeader /* RVA */ + dwRVA /* subtract from offsets to account for relocation */ - pSecHeader->VirtualAddress /* File ptr to section's first page within COFF */ + pSecHeader->PointerToRawData ) ; } //----< show the characteristics of the section table >---- void DisplaySectionTableCharacteristics ( const DWORD & dwChr ) { /* may be more than one characteristic */ ///////////////////////////////////////// cout << setw(PE_SEC_ALN) << left << " Section Characteristics -" << "\n" ; if (( dwChr & IMAGE_SCN_CNT_CODE ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section contains code\n" ; if (( dwChr & IMAGE_SCN_CNT_INITIALIZED_DATA ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section contains initialized data\n" ; if (( dwChr & IMAGE_SCN_CNT_UNINITIALIZED_DATA ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section contains uninitialized data\n" ; if (( dwChr & IMAGE_SCN_LNK_INFO ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section contains comments or some other type of information\n" ; if (( dwChr & IMAGE_SCN_LNK_REMOVE ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section contents will not become part of image\n" ; if (( dwChr & IMAGE_SCN_LNK_COMDAT ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section contains COMDAT data\n" ; if (( dwChr & IMAGE_SCN_NO_DEFER_SPEC_EXC ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Speculative exceptions handling bits in the TLB entries for this section are reset\n" ; if (( dwChr & IMAGE_SCN_GPREL ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section content can be accessed relative to GP\n" ; if (( dwChr & IMAGE_SCN_LNK_NRELOC_OVFL ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section contains extended relocations\n" ; if (( dwChr & IMAGE_SCN_MEM_DISCARDABLE ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section can be discarded\n" ; if (( dwChr & IMAGE_SCN_MEM_NOT_CACHED ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section is not cachable\n" ; if (( dwChr & IMAGE_SCN_MEM_NOT_PAGED ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section is not pageable\n" ; if (( dwChr & IMAGE_SCN_MEM_SHARED ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section is shareable\n" ; if (( dwChr & IMAGE_SCN_MEM_EXECUTE ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section is executable\n" ; if (( dwChr & IMAGE_SCN_MEM_READ ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section is readable\n" ; if (( dwChr & IMAGE_SCN_MEM_WRITE ) != 0 ) cout << setw(PE_SEC_ALN) << left << " " << " - Section is writeable\n" ; } //----< retrieve the data directory name in a string format >----- char * GetDataDirectoryNameString ( const int & index ) { switch ( index ) { case IMAGE_DIRECTORY_ENTRY_EXPORT : return "Export Directory" ; case IMAGE_DIRECTORY_ENTRY_IMPORT : return "Import Directory" ; case IMAGE_DIRECTORY_ENTRY_RESOURCE : return "Resource Directory" ; case IMAGE_DIRECTORY_ENTRY_EXCEPTION : return "Exception Directory" ; case IMAGE_DIRECTORY_ENTRY_SECURITY : return "Security Directory" ; case IMAGE_DIRECTORY_ENTRY_BASERELOC : return "Base Relocation Table" ; case IMAGE_DIRECTORY_ENTRY_DEBUG : return "Debug Directory" ; case IMAGE_DIRECTORY_ENTRY_ARCHITECTURE : return "Architecture Specific Data" ; case IMAGE_DIRECTORY_ENTRY_GLOBALPTR : return "RVA of Global Pointer" ; case IMAGE_DIRECTORY_ENTRY_TLS : return "TLS Directory" ; case IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG : return "Load Configuration Directory" ; case IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT : return "Bound Import Directory" ; case IMAGE_DIRECTORY_ENTRY_IAT : return "Import Address Table" ; case IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT : return "Delay Load Import Descriptors" ; case IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR : return "COM Runtime descriptor" ; default : return "unknown !" ; } } //----< gets DLL characteristics in string format >---- void DisplayDllCharacteristics ( const WORD & wDllChr ) { /* dll may have more than one characteristic */ ///////////////////////////////////////////////// cout << setw(PE_OPT_ALN) << left << " DLL Characteristics -" << "\n" ; if ((wDllChr & IMAGE_DLLCHARACTERISTICS_NO_BIND) != 0) cout << setw(PE_OPT_ALN) << left << " " << " - cannot bind image\n" ; if ((wDllChr & IMAGE_DLLCHARACTERISTICS_WDM_DRIVER) != 0) cout << setw(PE_OPT_ALN) << left << " " << " - driver is a WDM driver\n" ; if ((wDllChr & IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE) != 0) cout << setw(PE_OPT_ALN) << left << " " << " - image is terminal-server aware\n" ; else cout << setw(PE_OPT_ALN) << left << " " << " - none detected\n" ; } //----< determines sub-system required to run specified image file >---- char * GetSubsystemString ( const WORD & wSubSys ) { switch ( wSubSys ) { case IMAGE_SUBSYSTEM_UNKNOWN : return "Unknown subsystem" ; case IMAGE_SUBSYSTEM_NATIVE : return "No subsystem required" ; case IMAGE_SUBSYSTEM_WINDOWS_GUI : return "Windows character-mode user interface (CUI) subsystem" ; case IMAGE_SUBSYSTEM_WINDOWS_CUI : return "Windows graphical user interface (GUI) subsystem" ; case IMAGE_SUBSYSTEM_OS2_CUI : return "OS/2 character-mode user interface (CUI) subsystem" ; case IMAGE_SUBSYSTEM_POSIX_CUI : return "POSIX character-mode user interface (CUI) subsystem" ; case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI : return "Windows CE system" ; case IMAGE_SUBSYSTEM_XBOX : return "Xbox system" ; case IMAGE_SUBSYSTEM_EFI_APPLICATION : return "system with EFI application support " ; case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER : return "system with EFI driver (boot services) support" ; case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER : return "system with EFI driver (runtime services) support" ; default : return "Unknown subsystem" ; } } //----< returns the optional header magic string >---- char * GetOptionalHeaderMagicString ( const WORD & wMagic ) { switch ( wMagic ) { case IMAGE_NT_OPTIONAL_HDR_MAGIC : return "file is an executable image" ; case IMAGE_ROM_OPTIONAL_HDR_MAGIC : return "file is a ROM image" ; default : return "could not be determined !" ; } } //----< returns the image characteristic in string format >---- void DisplayImageCharacteristics ( const WORD & wChr ) { /* image may have more than one characteristic */ ///////////////////////////////////////////////// cout << setw(30) << left << " Image Characteristics -" << "\n" ; if (( wChr & IMAGE_FILE_RELOCS_STRIPPED ) != 0 ) cout << setw(30) << left << " " << " - relocation info stripped from file\n" ; if (( wChr & IMAGE_FILE_EXECUTABLE_IMAGE ) != 0 ) cout << setw(30) << left << " " << " - executable with no unresolved external references\n" ; if (( wChr & IMAGE_FILE_LINE_NUMS_STRIPPED ) != 0 ) cout << setw(30) << left << " " << " - COFF line numbers stripped from file\n" ; if (( wChr & IMAGE_FILE_LOCAL_SYMS_STRIPPED ) != 0 ) cout << setw(30) << left << " " << " - local symbols stripped from file\n" ; if (( wChr & IMAGE_FILE_AGGRESIVE_WS_TRIM ) != 0 ) cout << setw(30) << left << " " << " - aggressively trim working set\n" ; if (( wChr & IMAGE_FILE_LARGE_ADDRESS_AWARE ) != 0 ) cout << setw(30) << left << " " << " - application can handle addresses > 2 GB\n" ; if (( wChr & IMAGE_FILE_BYTES_REVERSED_LO ) != 0 ) cout << setw(30) << left << " " << " - little endian format\n" ; if (( wChr & IMAGE_FILE_32BIT_MACHINE ) != 0 ) cout << setw(30) << left << " " << " - machine based on 32-bit word architecture\n" ; if (( wChr & IMAGE_FILE_DEBUG_STRIPPED ) != 0 ) cout << setw(30) << left << " " << " - debug symbols available in separate file\n" ; if (( wChr & IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP ) != 0 ) cout << setw(30) << left << " " << " - application copied & run from swap file, if on removable media\n" ; if (( wChr & IMAGE_FILE_NET_RUN_FROM_SWAP ) != 0 ) cout << setw(30) << left << " " << " - application copied & run from swap file, if on network\n" ; if (( wChr & IMAGE_FILE_SYSTEM ) != 0 ) cout << setw(30) << left << " " << " - system file, not a user program\n" ; if (( wChr & IMAGE_FILE_DLL ) != 0 ) cout << setw(30) << left << " " << " - DLL file\n" ; if (( wChr & IMAGE_FILE_UP_SYSTEM_ONLY ) != 0 ) cout << setw(30) << left << " " << " - File should be run only on a uniprocessor computer\n" ; if (( wChr & IMAGE_FILE_BYTES_REVERSED_HI ) != 0 ) cout << setw(30) << left << " " << " - big endian format\n" ; else cout << setw(30) << left << " " << " - none detected\n" ; // FIX THIS !!!! } //----< returns the correct machine type in string format >---- char * GetMachineArchString ( const WORD & wMachine ) { switch ( wMachine ) { case IMAGE_FILE_MACHINE_UNKNOWN : return "unknown architecture !" ; case IMAGE_FILE_MACHINE_ALPHA : return "Alpha AXP processor" ; case IMAGE_FILE_MACHINE_ARM : return "ARM processor" ; case IMAGE_FILE_MACHINE_ALPHA64 : return "Alpha AXP processor (64 Bit)" ; case IMAGE_FILE_MACHINE_I386 : return "Intel i386 compatible process (32 bit)" ; case IMAGE_FILE_MACHINE_IA64 : return "Intel IA64 processor" ; case IMAGE_FILE_MACHINE_MIPS16 : return "MIPS processor" ; case IMAGE_FILE_MACHINE_MIPSFPU : return "MIPS processor with FPU" ; case IMAGE_FILE_MACHINE_MIPSFPU16 : return "MIPS16 processor with FPU" ; case IMAGE_FILE_MACHINE_POWERPC : return "PowerPC (Little Endian Format)" ; case IMAGE_FILE_MACHINE_R3000 : return "MIPS processor (Little Endian Format)" ; case IMAGE_FILE_MACHINE_R4000 : return "MIPS processor (Little Endian Format)" ; case IMAGE_FILE_MACHINE_R10000 : return "MIPS processor (Little Endian Format)" ; case IMAGE_FILE_MACHINE_SH3 : return "Hitachi SH3 processor" ; case IMAGE_FILE_MACHINE_SH4 : return "Hitachi SH4 processor" ; default : return "unknown architecture !" ; } } //-----< displays the PE headers >----- void HeaderDisplay ( const IMAGE_FILE_HEADER & ImageFileHeader ) { cout << "\n" ; Title ( "PE Header Display", '*' ) ; /* display all members */ ///////////////////////// cout << setw(30) << left << " Target Machine Architecture" << " : " << GetMachineArchString ( ImageFileHeader.Machine ) << "\n" << setw(30) << left << " Total Number of Sections" << " : " << ImageFileHeader.NumberOfSections << "\n" << setw(30) << left << " Date-Time Stamp" << " : " << ctime ( (const time_t *) & ImageFileHeader.TimeDateStamp ) << setw(30) << left << " Total symbols in symbol-table" << " : " << ImageFileHeader.NumberOfSymbols << "\n" << setw(30) << left << " Offset to the symbol table" << " : " ; if ( ImageFileHeader.PointerToSymbolTable == 0 ) cout << "symbol table does not exist\n\n" ; else cout << ImageFileHeader.PointerToSymbolTable << "\n\n" ; /* image may have multiple characteristics. show all of them */ //////////////////////////////////////////////////////////////// DisplayImageCharacteristics ( ImageFileHeader.Characteristics ) ; cout << "\n\n" ; } //-----< displays the 'optional' (!) PE headers >----- void OptionalHeaderDisplay ( const IMAGE_OPTIONAL_HEADER & ImageOptHeader ) { cout << "\n" ; Title ( "PE Optional Header Display", '*' ) ; cout << setw(PE_OPT_ALN) << left << " State of the image file" << " : " << GetOptionalHeaderMagicString ( ImageOptHeader.Magic ) << "\n" << setw(PE_OPT_ALN) << left << " Major Linker Version" << " : " << dec << (unsigned long) ImageOptHeader.MajorLinkerVersion << "\n" << setw(PE_OPT_ALN) << left << " Minor Linker Version" << " : " << dec << (unsigned long) ImageOptHeader.MinorLinkerVersion << "\n" << setw(PE_OPT_ALN) << left << " Size of all code (.text) sections" << " : " << dec << ImageOptHeader.SizeOfCode << " bytes\n" << setw(PE_OPT_ALN) << left << " Size of all initialized data sections" << " : " << dec << ImageOptHeader.SizeOfInitializedData << " bytes\n" << setw(PE_OPT_ALN) << left << " Size of all uninitialized data (.bss) sections" << " : " << dec << ImageOptHeader.SizeOfUninitializedData << " bytes\n" << setw(PE_OPT_ALN) << left << " Entry Point Function Address (RVA)" << " : 0x" << hex << ImageOptHeader.AddressOfEntryPoint << "\n" << setw(PE_OPT_ALN) << left << " Begining Of Code Section (RVA)" << " : 0x" << hex << ImageOptHeader.BaseOfCode << "\n" << setw(PE_OPT_ALN) << left << " Begining Of Data Section (RVA)" << " : 0x" << hex << ImageOptHeader.BaseOfData << "\n" << setw(PE_OPT_ALN) << left << " Preferred Load Address (VA)" << " : 0x" << hex << ImageOptHeader.ImageBase << "\n" << setw(PE_OPT_ALN) << left << " Section Alignment" << " : " << dec << ImageOptHeader.SectionAlignment << " bytes\n" << setw(PE_OPT_ALN) << left << " File Alignment" << " : " << dec << ImageOptHeader.FileAlignment << " bytes\n" << setw(PE_OPT_ALN) << left << " Major Operating System Version" << " : " << dec << ImageOptHeader.MajorOperatingSystemVersion << "\n" << setw(PE_OPT_ALN) << left << " Minor Operating System Version" << " : " << dec << ImageOptHeader.MinorOperatingSystemVersion << "\n" << setw(PE_OPT_ALN) << left << " Major Image Version" << " : " << dec << ImageOptHeader.MajorImageVersion << "\n" << setw(PE_OPT_ALN) << left << " Minor Image Version" << " : " << dec << ImageOptHeader.MinorImageVersion << "\n" << setw(PE_OPT_ALN) << left << " Major Subsystem Version" << " : " << dec << ImageOptHeader.MajorSubsystemVersion << "\n" << setw(PE_OPT_ALN) << left << " Minor Subsystem Version" << " : " << dec << ImageOptHeader.MinorSubsystemVersion << "\n" << setw(PE_OPT_ALN) << left << " Size Of Image" << " : " << dec << ImageOptHeader.SizeOfImage << " bytes\n" << setw(PE_OPT_ALN) << left << " Size Of (DOS+PE+Sections) Headers" << " : " << dec << ImageOptHeader.SizeOfHeaders << " bytes\n" << setw(PE_OPT_ALN) << left << " Image File Checksum" << " : 0x" << hex << ImageOptHeader.CheckSum << "\n" << setw(PE_OPT_ALN) << left << " Subsystem to run the image" << " : " << GetSubsystemString(ImageOptHeader.Subsystem) << "\n" << setw(PE_OPT_ALN) << left << " Size Of Stack Reserve" << " : " << dec << ImageOptHeader.SizeOfStackReserve << " bytes\n" << setw(PE_OPT_ALN) << left << " Size Of Stack Commit" << " : " << dec << ImageOptHeader.SizeOfStackCommit << " bytes\n" << setw(PE_OPT_ALN) << left << " Size Of Heap Reserve" << " : " << dec << ImageOptHeader.SizeOfHeapReserve << " bytes\n" << setw(PE_OPT_ALN) << left << " Size Of Heap Commit" << " : " << dec << ImageOptHeader.SizeOfHeapCommit << " bytes\n" << setw(PE_OPT_ALN) << left << " Data-directory entries" << " : " << dec << ImageOptHeader.NumberOfRvaAndSizes << "\n\n" ; /* iterate through the data directory */ //////////////////////////////////////// cout << setw(PE_OPT_ALN) << left << " Data Directory -" << "\n\n" << setw(6) << left << " " << setw(35) << left << "Directory Name" << setw(15) << left << "RVA" << setw(20) << left << "Table Size (bytes)" << "\n" << setw(6) << left << " " << setw(35) << left << "--------------" << setw(15) << left << "---" << setw(20) << left << "----------" << "\n" ; for ( int i = 0 ; i < ImageOptHeader.NumberOfRvaAndSizes ; ++i ) cout << setw(6) << left << " " << setw(35) << left << GetDataDirectoryNameString(i) << setw(15) << left << hex << ImageOptHeader.DataDirectory[i].VirtualAddress << setw(20) << left << dec << ImageOptHeader.DataDirectory[i].Size << "\n" ; cout << "\n" ; /* now for the dll characteristics */ ///////////////////////////////////// DisplayDllCharacteristics ( ImageOptHeader.DllCharacteristics ) ; cout << "\n\n" ; } //-----< displays the section table headers >----- /* NOTE 1 : Each row of the Section Table, in effect, is a section header. This table immediately follows the optional header, if any. NOTE 2 : The "VirtualSize" field is valid only for executable images and is set to NULL for object files. We are not handling .obj files for now. */ void SectionTableDisplay ( IMAGE_SECTION_HEADER * pImageSectionHeader, const IMAGE_FILE_HEADER & ImageFileHeader ) { cout << "\n" ; Title ( "PE Section Table Display", '*' ) ; /* iterate through each section header */ ///////////////////////////////////////// for ( int i = 0 ; i < ImageFileHeader.NumberOfSections ; ++i ) { cout << " Section Header # " << i+1 << "\n" << " -------------------\n" ; cout << setw(PE_SEC_ALN) << left << " Name" << " : " << pImageSectionHeader[i].Name << "\n" << setw(PE_SEC_ALN) << left << " Size in memory" << " : " << dec << pImageSectionHeader[i].Misc.VirtualSize << " bytes\n" << setw(PE_SEC_ALN) << left << " Virtual Address (RVA)" << " : 0x" << hex << pImageSectionHeader[i].VirtualAddress << "\n" << setw(PE_SEC_ALN) << left << " Size of initialized data on disk" << " : " << dec << pImageSectionHeader[i].SizeOfRawData << " bytes\n" << setw(PE_SEC_ALN) << left << " File ptr to section's first page within COFF file" << " : 0x" << hex << pImageSectionHeader[i].PointerToRawData << "\n" << setw(PE_SEC_ALN) << left << " File ptr to beginning of relocation entries" << " : 0x" << hex << pImageSectionHeader[i].PointerToRelocations << "\n" << setw(PE_SEC_ALN) << left << " File ptr to beginning of line-number entries" << " : 0x" << hex << pImageSectionHeader[i].PointerToLinenumbers << "\n" << setw(PE_SEC_ALN) << left << " Number of relocation entries for the section" << " : " << dec << pImageSectionHeader[i].NumberOfRelocations << "\n" << setw(PE_SEC_ALN) << left << " Number of line number entries for the section" << " : " << dec << pImageSectionHeader[i].NumberOfLinenumbers << "\n\n" ; /* Display the characteristics of the section table */ ////////////////////////////////////////////////////// DisplaySectionTableCharacteristics (pImageSectionHeader[i].Characteristics) ; cout << "\n" ; } cout << "\n\n" ; } //----< display of the entire exports section >---- void ExportsSectionDisplay ( IMAGE_NT_HEADERS * pNtHeaders, IMAGE_DOS_HEADER * pDosHeader ) { /* assertion check */ ///////////////////// assert ( pNtHeaders != NULL ) ; assert ( pDosHeader != NULL ) ; /* get the RVA and size associated with this section */ /////////////////////////////////////////////////////// DWORD dwExportRva = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress ; DWORD dwExportSize = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size ; /* get the section header to the exports section */ /////////////////////////////////////////////////// IMAGE_SECTION_HEADER * pSectionHeader = IMAGE_FIRST_SECTION ( pNtHeaders ) ; IMAGE_SECTION_HEADER * pExportSecHeader = 0 ; for ( int i = 0 ; i < pNtHeaders->FileHeader.NumberOfSections ; ++i ) { /* does RVA fall within bounds of this section ? */ /* use pointer-index notation. no other way out. */ /////////////////////////////////////////////////// if ( ( dwExportRva >= pSectionHeader[i].VirtualAddress ) && ( dwExportRva <= ( pSectionHeader[i].VirtualAddress + pSectionHeader[i].Misc.VirtualSize ) ) ) { pExportSecHeader = & pSectionHeader[i] ; break ; } } /* check n see if there is really an export section. else return */ /////////////////////////////////////////////////////////////////// if ( pExportSecHeader == 0 ) return ; /* finally the pointer to IMAGE_EXPORT_DIRECTORY */ /////////////////////////////////////////////////// IMAGE_EXPORT_DIRECTORY * pExpDirectory = (IMAGE_EXPORT_DIRECTORY *) ( /* base of image */ (unsigned long) pDosHeader /* RVA of exports */ + dwExportRva /* subtract from offsets to account for relocation */ - pExportSecHeader->VirtualAddress /* File ptr to section's first page within COFF */ + pExportSecHeader->PointerToRawData ) ; /* now resume with the display */ ///////////////////////////////// cout << "\n" ; Title ( "Exports Section", '*' ) ; // Note - at present, characteristics have not been defined for // the Exports Directory. cout << setw(PE_OPT_ALN) << left << " Name" << " : " << (char *) ( (unsigned long) pDosHeader + pExpDirectory->Name - pExportSecHeader->VirtualAddress + pExportSecHeader->PointerToRawData ) << "\n" << setw(PE_OPT_ALN) << left << " Date-Time Stamp" << " : " << ctime ( (const time_t *) & pExpDirectory->TimeDateStamp ) << setw(PE_OPT_ALN) << left << " Major Version Number of Exports" << " : " << dec << pExpDirectory->MajorVersion << "\n" << setw(PE_OPT_ALN) << left << " Minor Version Number of Exports" << " : " << dec << pExpDirectory->MinorVersion << "\n" << setw(PE_OPT_ALN) << left << " Zero-Based Index into the Export Address Table" << " : 0x" << hex << pExpDirectory->Base << "\n" << setw(PE_OPT_ALN) << left << " Number of Entries in the Export Address Table" << " : " << dec << pExpDirectory->NumberOfFunctions << "\n" << setw(PE_OPT_ALN) << left << " Number of Entries in the Export Name Table" << " : " << dec << pExpDirectory->NumberOfNames << "\n\n" ; /* now display EAT, ENT, EOT */ /////////////////////////////// DWORD * pdwEAT = (DWORD *) ( (unsigned long)pExpDirectory->AddressOfFunctions + (unsigned long) pDosHeader - pExportSecHeader->VirtualAddress + pExportSecHeader->PointerToRawData ) ; char ** pdwENT = (char **) ( (unsigned long)pExpDirectory->AddressOfNames + (unsigned long) pDosHeader - pExportSecHeader->VirtualAddress + pExportSecHeader->PointerToRawData ) ; WORD * pdwEOT = (WORD *) ( (unsigned long)pExpDirectory->AddressOfNameOrdinals + (unsigned long) pDosHeader - pExportSecHeader->VirtualAddress + pExportSecHeader->PointerToRawData ) ; /* now reversing the algo described by matt pietrek, here we go.... */ ////////////////////////////////////////////////////////////////////// for ( int i = 0 ; i < pExpDirectory->NumberOfFunctions ; ++i ) { /* go thru the EAT */ ///////////////////// DWORD dwElemEAT ; if ((dwElemEAT = pdwEAT[i]) == 0) continue ; // if 0, then skip to next EAT element /* go thru the ENT, EOT */ ////////////////////////// for ( int j = 0 ; j < pExpDirectory->NumberOfNames ; ++j ) if ( pdwEOT[j] == i ) { /* time for display */ ////////////////////// static bool HeaderDisplayed = false ; // header must be displayed only once if ( ! HeaderDisplayed ) { cout << setw(PE_OPT_ALN) << left << " Exports -" << "\n\n" << setw(6) << left << " " << setw(35) << left << "Name" << setw(15) << left << "Ordinal" << setw(20) << left << "Address (RVA)" << "\n" << setw(6) << left << " " << setw(35) << left << "----" << setw(15) << left << "-------" << setw(20) << left << "-------" << "\n" ; HeaderDisplayed = true ; } cout << setw(6) << left << " " << setw(35) << left << (char *) ( (unsigned long) pdwENT[j] + (unsigned long) pDosHeader - pExportSecHeader->VirtualAddress + pExportSecHeader->PointerToRawData ) << setw(15) << left << ( i + pExpDirectory->Base ) << setw(20) << left << hex << dwElemEAT << "\n" ; } } cout << "\n\n" ; } //----< display of the entire imports section >---- void ImportsSectionDisplay ( IMAGE_NT_HEADERS * pNtHeaders, IMAGE_DOS_HEADER * pDosHeader ) { /* assertion check */ ///////////////////// assert ( pNtHeaders != NULL ) ; assert ( pDosHeader != NULL ) ; /* get the RVA and size associated with this section */ /////////////////////////////////////////////////////// DWORD dwImportRva = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress ; DWORD dwImportSize = pNtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size ; /* get the section header to the imports section */ /////////////////////////////////////////////////// IMAGE_SECTION_HEADER * pSectionHeader = IMAGE_FIRST_SECTION ( pNtHeaders ) ; IMAGE_SECTION_HEADER * pImportSecHeader = 0 ; for ( int i = 0 ; i < pNtHeaders->FileHeader.NumberOfSections ; ++i ) { /* does RVA fall within bounds of this section ? */ /* use pointer-index notation. no other way out. */ /////////////////////////////////////////////////// if ( ( dwImportRva >= pSectionHeader[i].VirtualAddress ) && ( dwImportRva <= ( pSectionHeader[i].VirtualAddress + pSectionHeader[i].Misc.VirtualSize ) ) ) { pImportSecHeader = & pSectionHeader[i] ; break ; } } /* assertion check */ ///////////////////// assert ( pImportSecHeader != 0 ) ; if ( pImportSecHeader == 0 ) return ; /* finally the pointer to first IMAGE_IMPORT_DESCRIPTOR */ ////////////////////////////////////////////////////////// IMAGE_IMPORT_DESCRIPTOR * pImpDesc = (IMAGE_IMPORT_DESCRIPTOR *) ( /* base of image */ (unsigned long) pDosHeader /* RVA of imports */ + dwImportRva /* subtract from offsets to account for relocation */ - pImportSecHeader->VirtualAddress /* File ptr to section's first page within COFF */ + pImportSecHeader->PointerToRawData ) ; /* now the display */ ///////////////////// cout << "\n" ; Title ( "Imports Section", '*' ) ; /* we do not know the total number of import descriptors at this point */ /* so we have to iterate thru all descriptors one by one till.....???? */ bool bMoreDesc = true ; for ( int iCount = 0 ; bMoreDesc == true ; ++iCount, ++pImpDesc ) { /* empty descriptor ? */ if ( ( pImpDesc->TimeDateStamp == NULL ) && ( pImpDesc->Name == NULL ) ) break ; // bMoreDesc = false ? cout << " Imported Binary Image # " << (iCount + 1) << "\n" << " -------------------------\n" ; cout << setw(30) << left << " Name" << " : " << (char *) RvaToPtr(pImpDesc->Name, pNtHeaders, pDosHeader) << "\n" << setw(30) << left << " Date-Time Stamp" << " : " << ctime ( (const time_t *) & pImpDesc->OriginalFirstThunk ) << setw(30) << left << " Original First Thunk (RVA)" << " : 0x" << hex << pImpDesc->OriginalFirstThunk << "\n" << setw(30) << left << " First Thunk (RVA)" << " : 0x" << hex << pImpDesc->FirstThunk << "\n\n" ; /* get the thunk arrays */ ////////////////////////// IMAGE_THUNK_DATA * pINT = (IMAGE_THUNK_DATA *) RvaToPtr ( pImpDesc->OriginalFirstThunk, pNtHeaders, pDosHeader ) ; IMAGE_THUNK_DATA * pIAT = (IMAGE_THUNK_DATA *) RvaToPtr ( pImpDesc->FirstThunk, pNtHeaders, pDosHeader ) ; // NOTE : assertion check needed here ? /* lets go thunking ! */ //////////////////////// bool bMoreThunkElems = true ; for ( int iThunkCount = 0 ; bMoreThunkElems == true ; ++iThunkCount, ++pINT, ++pIAT ) { if ( pINT->u1.AddressOfData == 0 ) break ; /* display by name or ordinal ? */ ////////////////////////////////// if ( ( pINT->u1.Ordinal & IMAGE_ORDINAL_FLAG ) != 0 ) { cout << setw(10) << right << " 0x" << setw(15) << left << IMAGE_ORDINAL ( pINT->u1.Ordinal ) << "\n" ; } else { IMAGE_IMPORT_BY_NAME * pImportName = (IMAGE_IMPORT_BY_NAME *) RvaToPtr ( (DWORD)pINT->u1.AddressOfData, pNtHeaders, pDosHeader ) ; cout << setw(10) << right << " 0x" << setw(15) << left << pImportName->Hint << setw(35) << left << pImportName->Name << "\n" ; } } cout << "\n" ; } cout << "\n\n" ; } //----< identify the file format and process it >---- void ProcessFile ( LPVOID lpFileBase ) { /* some pre-condition check to prevent embarrassment later */ ///////////////////////////////////////////////////////////// assert ( lpFileBase != NULL ) ; /* although undocumented in msdn, IMAGE_DOS_HEADER is described in WinNT.h */ ///////////////////////////////////////////////////////////////////////////// IMAGE_DOS_HEADER * pDosHeader = (IMAGE_DOS_HEADER*) lpFileBase ; if ( pDosHeader->e_magic != IMAGE_DOS_SIGNATURE ) { cout << "File is not in either of these formats - .exe, .dll ! \n" ; return ; } /* file offset to NT Header is obtained from the "e_lfanew" field of dos header */ ////////////////////////////////////////////////////////////////////////////////// IMAGE_NT_HEADERS * pNtHeaders = (IMAGE_NT_HEADERS*)( (unsigned long)pDosHeader + (unsigned long)pDosHeader->e_lfanew ) ; if ( pNtHeaders->Signature != IMAGE_NT_SIGNATURE ) /* the signature is 'PE\0\0' */ { cout << "File is not a valid PE file ! \n" ; return ; } /* now that validity has been confirmed, dump each of the sections */ ///////////////////////////////////////////////////////////////////// HeaderDisplay ( pNtHeaders->FileHeader ) ; OptionalHeaderDisplay ( pNtHeaders->OptionalHeader ) ; /* "Optional Header" is a misnomer. it is always present in PE. */ SectionTableDisplay ( IMAGE_FIRST_SECTION(pNtHeaders), /* Note: Don't ever waste half a day again */ pNtHeaders->FileHeader ) ; /* trying to get offsets into Section Table. Many */ /* undocumented macros, already defined in */ /* the WinNT.h header which provide offsets. */ /* Moral of the Story : Always look first in WinNt.h */ /* header for anything even remotely connected with */ /* the PE format. */ ExportsSectionDisplay ( pNtHeaders, pDosHeader ) ; ImportsSectionDisplay ( pNtHeaders, pDosHeader ) ; CodeSectionDisplay ( IMAGE_FIRST_SECTION(pNtHeaders), /* macro in use again */ pNtHeaders->FileHeader.NumberOfSections, pDosHeader ) ; } //----< main program entry point >---- void main ( int argc, char* argv[] ) { /* a little command-line check */ ///////////////////////////////// if ( argc != 2 ) { cout << "Syntax Error ! \n" << "Usage : DisAsm \n" ; return ; } char * pszFileName = argv[1] ; /* get handle to this file */ ///////////////////////////// HANDLE hFile = CreateFile ( pszFileName, /* file name */ GENERIC_READ, /* for reading only */ FILE_SHARE_READ, /* enable subsequent read operations */ NULL, /* null */ OPEN_EXISTING, /* open the existing file only */ FILE_ATTRIBUTE_NORMAL, /* no other file attributes set */ NULL ) ; /* no extended file attributes */ if ( hFile == INVALID_HANDLE_VALUE ) { CloseHandle ( hFile ) ; cout << "File could not be opended for reading !\n" ; return ; } /* now create a mapping object for this file in memory */ ///////////////////////////////////////////////////////// HANDLE hFileMap = CreateFileMapping ( hFile, /* handle to file */ NULL, /* no security attributes */ PAGE_READONLY, /* read-only access to committed region of pages */ 0, /* maximum size of the file mapping object is */ 0, /* equal to the current size of specified file */ NULL ) ; /* no name for mapping object */ if ( hFileMap == NULL ) { CloseHandle ( hFileMap ) ; CloseHandle ( hFile ) ; cout << "Operation could not be completed !\n" ; return ; } /* map view of file mapping object into our address space */ //////////////////////////////////////////////////////////// LPVOID lpFileBase = MapViewOfFile ( hFileMap, /* handle to file mapping object */ FILE_MAP_READ, /* read-only access */ 0, 0, 0 ) ; /* bytes to be mapped to our view, extend from offset to the end of the section */ if ( lpFileBase == NULL ) { CloseHandle ( hFileMap ) ; CloseHandle ( hFile ) ; cout << "Operation could not be completed !\n" ; return; } /* let the carnage begin ! */ ///////////////////////////// ProcessFile ( lpFileBase ) ; /* Now that we are done, unmap the view of the file mapping object */ ///////////////////////////////////////////////////////////////////// UnmapViewOfFile ( lpFileBase ) ; /* close all handles */ ////////////////////// CloseHandle ( hFileMap ) ; CloseHandle ( hFile ) ; }