可重用函數:類比windows裝載器載入PE檔案

來源:互聯網
上載者:User
/**描述:     類比windows轉載器載入PE檔案,能更方便的對PE檔案進行處理參數:    szFileName:           PE檔案的路徑返回:    成功則返回PE檔案鏡像在記憶體的首地址,失敗則返回0*/ULONG MapPeFile(TCHAR* szFileName){HANDLE hFile;ULONG numR;IMAGE_DOS_HEADER dosHeader = {0};IMAGE_NT_HEADERS ntHeader;ULONG dwImageSize;    ULONG dwNumOfSections;ULONG dwHeadSize;PIMAGE_SECTION_HEADER pSection;    char* pBase;ULONG nIndex;        hFile = CreateFile(szFileName,    GENERIC_READ | GENERIC_WRITE,   FILE_SHARE_READ | FILE_SHARE_WRITE,                       NULL,   OPEN_EXISTING,   FILE_ATTRIBUTE_NORMAL,   NULL               );if (hFile == INVALID_HANDLE_VALUE){OutputDebugString(_T("開啟檔案失敗!"));return 0;}    ReadFile(hFile,     &dosHeader, sizeof(IMAGE_DOS_HEADER),             &numR, NULL );SetFilePointer(hFile,           dosHeader.e_lfanew,   NULL,   FILE_BEGIN            );ReadFile(hFile,     &ntHeader, sizeof(IMAGE_NT_HEADERS),             &numR, NULL );    dwImageSize = ntHeader.OptionalHeader.SizeOfImage;    dwNumOfSections = ntHeader.FileHeader.NumberOfSections;    dwHeadSize = ntHeader.OptionalHeader.SizeOfHeaders;   pBase =(char*)malloc(dwImageSize);    memset(pBase , 0 , dwImageSize);    SetFilePointer(hFile , 0 , NULL , FILE_BEGIN);ReadFile(hFile, pBase , dwHeadSize ,&numR , NULL);    pSection = (PIMAGE_SECTION_HEADER)(dosHeader.e_lfanew          + sizeof(ntHeader.Signature)        + sizeof(IMAGE_FILE_HEADER)+ ntHeader.FileHeader.SizeOfOptionalHeader+ (ULONG)pBase);    for (nIndex = 0 , pSection ; nIndex < dwNumOfSections ; nIndex++ ,pSection++){   SetFilePointer(hFile , pSection ->PointerToRawData , NULL , FILE_BEGIN);       ReadFile(hFile , &pBase[pSection->VirtualAddress] , pSection->SizeOfRawData ,&numR ,NULL);}CloseHandle(hFile);    return (ULONG)pBase;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.