#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include <array>
#include <cstdint>
#include <cstdio>

namespace {

constexpr int kFirstGateExit = 10;
constexpr int kSecondGateExit = 20;
constexpr int kSecondGateErrorExit = 21;
constexpr int kStageErrorExit = 30;

using StageFunction = int (*)();

// The unencoded bytes are: B8 2A 00 00 00 C3 (mov eax, 42; ret).
constexpr std::array<std::uint8_t, 6> kEncodedStage = {
    0x1d, 0x8f, 0xa5, 0xa5, 0xa5, 0x66
};
constexpr std::uint8_t kXorKey = 0xa5;

}  // namespace

extern "C" __declspec(noinline) bool FirstGate() {
    const BOOL debugged = IsDebuggerPresent();
    return debugged == FALSE;
}

extern "C" __declspec(noinline) int SecondGate() {
    BOOL debugged = FALSE;
    const BOOL ok = CheckRemoteDebuggerPresent(GetCurrentProcess(), &debugged);
    if (ok == FALSE) {
        std::printf("second_gate=api_error:%lu\n", GetLastError());
        return kSecondGateErrorExit;
    }

    return debugged == FALSE ? 0 : kSecondGateExit;
}

extern "C" __declspec(noinline) int InvokeStage(StageFunction function) {
    return function();
}

extern "C" __declspec(noinline) int RunStage() {
    void* code = VirtualAlloc(nullptr, kEncodedStage.size(),
                              MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    if (code == nullptr) {
        std::printf("stage=VirtualAlloc_failed:%lu\n", GetLastError());
        return kStageErrorExit;
    }

    auto* bytes = static_cast<std::uint8_t*>(code);
    for (std::size_t i = 0; i < kEncodedStage.size(); ++i) {
        bytes[i] = kEncodedStage[i] ^ kXorKey;
    }

    DWORD oldProtection = 0;
    if (VirtualProtect(code, kEncodedStage.size(), PAGE_EXECUTE_READ,
                       &oldProtection) == FALSE) {
        std::printf("stage=VirtualProtect_failed:%lu\n", GetLastError());
        VirtualFree(code, 0, MEM_RELEASE);
        return kStageErrorExit;
    }

    if (FlushInstructionCache(GetCurrentProcess(), code,
                              kEncodedStage.size()) == FALSE) {
        std::printf("stage=FlushInstructionCache_failed:%lu\n", GetLastError());
        VirtualFree(code, 0, MEM_RELEASE);
        return kStageErrorExit;
    }

    const int result = InvokeStage(reinterpret_cast<StageFunction>(code));
    std::printf("stage_result=%d\n", result);
    if (VirtualFree(code, 0, MEM_RELEASE) == FALSE) {
        std::printf("stage=VirtualFree_failed:%lu\n", GetLastError());
        return kStageErrorExit;
    }
    return result == 42 ? 0 : kStageErrorExit;
}

int main() {
    if (!FirstGate()) {
        return kFirstGateExit;
    }

    const int secondGate = SecondGate();
    if (secondGate != 0) {
        return secondGate;
    }

    return RunStage();
}
