如何整齐地修改PE数据部分

时间:2013-03-24 15:01:54

标签: c winapi portable-executable

我正在'C / C ++ - Win32API'环境中编写一个dll。 我有一些常量变量(都是DWORD值和LPWSTR / LPSTR字符串),我必须启用用户修改。 我正在寻找的是(希望)一种能够实现SAFE二进制修改的工具,如上所述, 以更新PE的所有必要表格的方式。

1 个答案:

答案 0 :(得分:3)

您可以在单独的PE部分中创建结构:

// Create the section
#pragma section("myconst", read)

// Declare a struct to hold the constant data
typedef struct
{
    DWORD a;
    DWORD b;
    char stringa[256];
    char stringb[256];
} ConstData;

// Create an initialized instance of the struct in the new section
__declspec(allocate("myconst"))
const ConstData theData = {0xdeadbeef, 0xfeedface, "Hello", "dolly"};

编译代码。打开Visual Studio命令提示符,运行

dumpbin /all myexe.exe > dump.txt
notepad dump.txt

搜索myconst部分。你应该看到类似的东西:

SECTION HEADER #4
 myconst name
     208 virtual size
    4000 virtual address (00404000 to 00404207)
     400 size of raw data
    2000 file pointer to raw data (00002000 to 000023FF)
       0 file pointer to relocation table
       0 file pointer to line numbers
       0 number of relocations
       0 number of line numbers
40000040 flags
         Initialized Data
         Read Only

RAW DATA #4
  00404000: EF BE AD DE CE FA ED FE 48 65 6C 6C 6F 00 00 00  ï¾­ÞÎúíþHello...
  00404010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
  00404020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................

您可以看到代码中初始化的两个十六进制值和第一个字符串值。您还可以看到PE文件中此数据的偏移量 - “文件指向原始数据” - 是0x2000。

有了这些信息,很容易构建一个新的数据块,打开PE文件并在0x2000覆盖数据。

要确定代码的偏移量,需要解析PE文件头和节头。这非常简单。或者您可以在构建过程中从dumpbin输出中获取偏移量,并将其提供给编辑工具的构建。

请注意,要在发布模式下对此进行测试,您需要实际使用theData,否则链接器会将其丢弃。另请注意,该部分仅具有read属性,因此它是真正的只读属性。尝试编写它会导致访问冲突。

最后......这一切都很邋..除非你别无选择,否则我不会打扰。