【发布时间】:2020-05-12 07:32:45
【问题描述】:
我正在尝试在 windows 上打开一个文件并检查魔术字节是否与 windows PE32 匹配。如果我运行下面的代码并在函数problemFunction 中的ReadFile 调用之前返回,则代码工作正常,并在主函数末尾打印5a4d。但是,如果我在 problemFunction 中的 ReadFile 调用之后返回,那么我会在 dos->e_magic != PIMAGE_DOS_HEADER 检查中退出。
#include <Windows.h>
#include <winternl.h>
void problemFunction(HANDLE *fh) {
DWORD fileSize = GetFileSize(fh, NULL);
if (!fileSize) { CloseHandle(fh); exit(1); }
BYTE* pByte = new BYTE[fileSize];
DWORD dw;
ReadFile(*fh, pByte, fileSize, &dw, NULL);
// could be wrong but i think i need to run SetFilePointer here but not sure on what to do.
return;
}
int main() {
const char* filepath = "C:\\windows\\file\\path\\to\\exe";
HANDLE fh = CreateFileA(filepath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(fh == INVALID_HANDLE_VALUE) { CloseHandle(fh); exit(1); }
problemFunction(&fh);
DWORD fileSize = GetFileSize(fh, NULL);
if (!fileSize) { CloseHandle(fh); exit(1); }
BYTE* pByte = new BYTE[fileSize];
DWORD dw;
ReadFile(fh, pByte, fileSize, &dw, NULL);
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)pByte;
if (dos->e_magic != IMAGE_DOS_SIGNATURE) { CloseHandle(fh); exit(1); }
// dos->e_magic should be 5a4d for MZ, windows PE
}
我假设我需要在problemFunction 读取调用之后重置文件指针,例如
LONG reset = -sizeof(DWORD);
SetFilePointer(*fh, reset, NULL, FILE_END);
但我无法让它工作。
谢谢
【问题讨论】:
-
FILE_END 相对于文件末尾查找,您想从当前位置 (FILE_CURRENT) 向后查找,或者只是查找到开头(偏移量为 0 的 FILE_BEGIN)。
-
@JonathanPotter 感谢偏移量为 0 的 FILE_BEGIN 工作
-
你的解释有些漏洞。 首先: “如果我[做某件事]代码可以正常工作”——那不是你的解决方案吗?代码工作正常。问题解决了! (如果您的意思是部分代码工作正常,请更准确。) 第二:您的示例代码从不调用@987654330 @,所以我看不出
problemFunction中的任何内容会如何影响您的结果。 -
@JaMiT 显然在
main()中对test()的调用本来是要调用problemFunction() -
@RemyLebeau 当我假设某事“显而易见”时,我至少在 90% 的情况下都是错误的。