почему краш при запуске EXE из памяти

У меня функция для загрузки PE из памяти, NTHeaders валиден, видит что x64, но при самом вызове entryPointFunc() выдаёт SIGSEGV, Segmentation fault

#include <windows.h>
#include <stdio.h>

void ExecuteEXEFromMemory(const char *filePath) {
    HANDLE hFile = CreateFileA(filePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) return;

    DWORD fileSize = GetFileSize(hFile, NULL);
    BYTE* buffer = (BYTE*)VirtualAlloc(NULL, fileSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if (buffer == NULL) {
        CloseHandle(hFile);
        return;
    }

    DWORD bytesRead;
    if (!ReadFile(hFile, buffer, fileSize, &bytesRead, NULL) || bytesRead != fileSize) {
        VirtualFree(buffer, 0, MEM_RELEASE);
        CloseHandle(hFile);
        return;
    }
    CloseHandle(hFile);
    
    IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)buffer;
    IMAGE_NT_HEADERS64* ntHeaders = (IMAGE_NT_HEADERS64*)(buffer + dosHeader->e_lfanew);
    
    if (ntHeaders->Signature != IMAGE_NT_SIGNATURE) {
        VirtualFree(buffer, 0, MEM_RELEASE);
        return; // Not a valid PE file
    }

    // Get the entry point address
    DWORD_PTR entryPoint = (DWORD_PTR)buffer + ntHeaders->OptionalHeader.AddressOfEntryPoint;

    printf("Calling...\n");
    if (ntHeaders->OptionalHeader.ImageBase == 0x140000000) {
        // Ensure the entry point is within the allocated buffer
        if (entryPoint >= (DWORD_PTR)buffer && entryPoint < (DWORD_PTR)(buffer + fileSize)) {
            // Call the entry point
            void (*entryPointFunc)() = (void(*)())(entryPoint);
            entryPointFunc(); // Call the entry point
        } else {
            // Handle invalid entry point
            printf("Invalid entry point address\n");
        }
    } else {
        printf("Unknown architecture program\n");
    }

    VirtualFree(buffer, 0, MEM_RELEASE);
}

Ответы (0 шт):