这是一个反汇编的例子,反汇编的代码是使用Bochs 中的反汇编的代码,由于Bochs 反汇编模块做的比较独立,所以可以直接把反汇编模块包含到程序,不过为了使用这个反汇编的代码,需要自己写一小段对PE 进行简单解析的代码,下面是这个代码:
#include "stdafx.h" #include "windows.h" #include "disasm.h"
DWORD RVA2FileOffset(PIMAGE_SECTION_HEADER ntHead, int nSection , DWORD RVA);
int main(int argc, char* argv[]) { IMAGE_DOS_HEADER dos; IMAGE_NT_HEADERS fileHeader ; DWORD cbRead ; //printf("Hello World!\n"); if(argc != 2) { printf("Uage : %s PE file Name , ex : %s a.exe \r\n",argv[0],argv[0]); return 0; } disassembler obj; HANDLE hFile = CreateFile(argv[1],GENERIC_READ , FILE_SHARE_READ , NULL,OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) { printf("can not open file : %s",argv[1]); return 0; } printf("Begin Reading File ... ...\r\n"); //read the file dos header ReadFile(hFile,&dos,sizeof(IMAGE_DOS_HEADER), &cbRead, NULL ); SetFilePointer(hFile,dos.e_lfanew , NULL, FILE_BEGIN);
//read the file pe header ReadFile(hFile,&fileHeader, sizeof(IMAGE_NT_HEADERS), &cbRead, NULL ); int nEntryAddress = fileHeader.OptionalHeader.AddressOfEntryPoint ; int nSectionNumber = fileHeader.FileHeader.NumberOfSections ; PIMAGE_SECTION_HEADER pSection = new IMAGE_SECTION_HEADER [nSectionNumber]; ReadFile(hFile,pSection, sizeof(IMAGE_SECTION_HEADER ) * nSectionNumber, &cbRead, NULL); printf("The Address of Entry is : %.8x\r\n", nEntryAddress); printf("The Section number is : %d\r\n", nSectionNumber);
int nEntryAddressOffFile = RVA2FileOffset(pSection, nSectionNumber, nEntryAddress); SetFilePointer(hFile,nEntryAddressOffFile,NULL,FILE_BEGIN); unsigned char szInBuf[1024]; char szoutBuf[4096]; ReadFile(hFile,szInBuf,1024,&cbRead,NULL); unsigned char *pStart = (unsigned char *)&szInBuf[0] ; int nTotalLen = 0; for(int i = 0 ; nTotalLen < 1024 ; i ++) { int nLen = obj.disasm(TRUE, fileHeader.OptionalHeader.ImageBase, nEntryAddress, pStart, ( char *)&szoutBuf[0]); pStart += nLen ; nTotalLen += nLen ; printf(szoutBuf ); printf("\r\n"); }
CloseHandle(hFile); return 0; } DWORD RVA2FileOffset(PIMAGE_SECTION_HEADER ntHead, int nSection , DWORD RVA) { PIMAGE_SECTION_HEADER pSection = (PIMAGE_SECTION_HEADER) ntHead ; int nTotalSection = nSection; for(int i = 0 ; i < nTotalSection ; i ++) { if ((pSection->VirtualAddress <= RVA) && (pSection->VirtualAddress + pSection->Misc.VirtualSize >= RVA)) { break; } } if(i >= nTotalSection ){ return 0; } return pSection->PointerToRawData + RVA - pSection->VirtualAddress ; } 看了上面的代码,你就会知道disassembler 这个类不是我自己写的,这个类就是来自Bochs 中的反汇编模块 。 这个模块的代码可以从Bochs 的源代码中获得。

|