PIMAGE_EXPORT_DIRECTORY - 内存访问错误

时间:2014-10-28 18:58:11

标签: c++ windows portable-executable

我正在尝试在kernel32.dll中找到rib for loadlibrary。我已经阅读了几个解析PE Headers的文档,但我似乎无法找出为什么我的指向导出目录的指针似乎无效。

hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        err = GetLastError();
        return err;
    }

    hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (hFileMapping == 0)
    {
        err = GetLastError();
        CloseHandle(fileName);
        return err;
    }

    lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
    if (lpFileBase == 0)
    {
        err = GetLastError();
        CloseHandle(fileName);
        CloseHandle(hFileMapping);
        return err;
    }

    dosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
    pNTHeader = (PIMAGE_NT_HEADERS)((BYTE*)dosHeader + dosHeader->e_lfanew);
    base = (DWORD64)dosHeader;

这里我打开文件,一切都很好,当我在这里运行调试器时。

    exportsStartRVA = pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
    exportsEndRVA = exportsStartRVA + pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;

这里我成功访问DataDirectory以获取导出目录的VirtualAddress和大小。

PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(pNTHeader);
unsigned i;
for (i = 0; i < pNTHeader->FileHeader.NumberOfSections; i++, section++)
{
    // Is the RVA within this section?
    if ((exportsStartRVA >= section->VirtualAddress) &&
        (exportsStartRVA < (section->VirtualAddress + section->Misc.VirtualSize)))
        break;
}

我查看了所有部分,直到我得到一个包含exportsStartRVA的节头。现在“section”指向导出目录的Section Header。

exportDir = (PIMAGE_EXPORT_DIRECTORY)((PBYTE)base + exportsStartRVA + section->PointerToRawData - section->VirtualAddress);

这里我得到一个指向导出目录的指针。

PDWORD pfunctions = (PDWORD)((PBYTE)base + (DWORD64)exportDir->AddressOfFunctions + header->PointerToRawData - header->VirtualAddress);
PDWORD ordinals = (PDWORD)((PBYTE)base + (DWORD64)exportDir->AddressOfNameOrdinals + header->PointerToRawData - header->VirtualAddress);
PSTR* name = (PSTR*)((PBYTE)base + (DWORD64)exportDir->AddressOfNames + header->PointerToRawData - header->VirtualAddress);
PSTR funcName;

for (unsigned i = 0; i < (DWORD64)exportDir->NumberOfNames; i++)
{
    funcName = name[i];
}

编辑:问题在于我的解除引用我认为,funcName实际上并没有给我任何内存访问错误。

1 个答案:

答案 0 :(得分:1)

AddressOfNames是一个RVA到一个RVA列表,其中包含字符串名称而不是RVA到字符串列表。