/*
 * tenkana, a spider that jumps from the checkpoints of your TeX document.
 * Copyright © 2026 निरंजन (Niranjan)
 *
 * tenkana is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * tenkana is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with tenkana.  If not, see <https://www.gnu.org/licenses/>.
 *
 * tenkana was written by Claude, a large language model (LLM) made by
 * Anthropic.  Its maintainer designs tenkana and tests what it does, but does
 * not understand its code; as far as he knows, no human has reviewed it.
 * Courts are divided on whether material generated by an LLM can be protected
 * by copyright.  Should it be found that the copyright claimant cannot hold
 * copyright in any part of tenkana, that part is in the public domain.
 * Wherever copyright does hold, tenkana is distributed under the terms of the
 * GNU General Public License, version 3 or (at your option) any later version,
 * as stated above.
 */

/*
 * tenkanasnap -- fork-based snapshots for an unmodified TeX engine, no root
 * needed.
 *
 * Loaded into the engine with LD_PRELOAD.  It wraps fopen() and a few other C
 * library calls (see below).  When the engine opens the file
 * $TENKANA_CTL/tenkanapause  (tenkana makes TeX do that with \openin just
 * before \begin{document} and before every \include):
 *
 *   1. remember the offset of every open regular file;
 *   2. fork().  The child becomes a *holder*: a frozen copy of the engine at
 *      this exact point.  It waits for commands on the FIFO
 *      $TENKANA_CTL/cmd<k>.
 *   3. the original reports "pause k <pid> <holder pid>" on $TENKANA_CTL/ev
 *      and waits for a line on $TENKANA_CTL/go (tenkana copies the output
 *      files meanwhile), then carries on typesetting.
 *
 * Holder commands
 *   resume [path]
 *           fork again; the new child restores the remembered file offsets,
 *           the engine's signal handlers and its terminal input (path, e.g.
 *           /proc/<pid>/fd/0 of the tenkana run; /dev/null without one), and
 *           continues typesetting from the pause point.  The holder waits for
 *           it and reports "exit <pid> <code>" on ev.  The holder stays frozen
 *           and can be resumed any number of times.
 *   quit    exit.
 * Holders also exit after $TENKANA_TTL seconds (default 8 h) without a build
 * of the document (tenkana touches $TENKANA_CTL/used each time) or when
 * $TENKANA_CTL disappears.
 *
 * Memory: fork() is copy-on-write, so a holder only costs the pages the live
 * engine changes after the snapshot.
 */
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>

/* tenkana carries this library ready-made, so it must load with any glibc
   since 2.17, not only the one it was built with: glibc 2.34 moved dlsym and
   dladdr into libc under a new version, so ask for the old one. */
#if defined(__GLIBC__) && defined(__x86_64__)
__asm__(".symver dlsym,dlsym@GLIBC_2.2.5");
__asm__(".symver dladdr,dladdr@GLIBC_2.2.5");
#endif
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <sys/syscall.h>
#include <unistd.h>

#define RESTORED 0x5E5E
static int save_image(const char *path, long limit, int level);

/* Portable helpers: avoid fstat/stat/strtol symbols that only exist in new
   glibc versions, so one prebuilt library works on old and new systems. */
static int raw_fstat(int fd, struct stat *st) {
    return (int)syscall(SYS_fstat, fd, st);
}
static int dir_exists(const char *p) {
    return access(p, F_OK) == 0;
}
static long to_long(const char *s) {
    long v = 0;
    while (*s >= '0' && *s <= '9')
        v = v * 10 + (*s++ - '0');
    return v;
}

/* Link against the oldest dlsym so one binary runs on old and new glibc. */
__asm__(".symver dlsym,dlsym@GLIBC_2.2.5");
__asm__(".symver dlopen,dlopen@GLIBC_2.2.5");
__asm__(".symver memcpy,memcpy@GLIBC_2.2.5");
__asm__(".symver clock_gettime,clock_gettime@GLIBC_2.2.5");

typedef FILE *(*fopen_t)(const char *, const char *);
static fopen_t real_fopen, real_fopen64;
typedef int (*unlink_t)(const char *);
typedef int (*unlinkat_t)(int, const char *, int);
static unlink_t real_unlink, real_remove;
static unlinkat_t real_unlinkat;
static int pause_no = 0;

/* The main .tex file.  When the engine opens it, we hand it $TENKANA_MAIN_SUB
   instead: the same text with tenkana's pause hooks prepended to line 1.  TeX
   still prints and records the real name, so logs, errors and SyncTeX point
   to the user's file.  We keep the FILE* to re-position it on resume. */
static FILE *main_fp = NULL;
static long main_pos = -1;
typedef int (*fclose_t)(FILE *);
static fclose_t real_fclose;

static int same_file(const char *a, const char *b) {
    struct stat sa, sb;
    if (!a || !b) return 0;
    if (syscall(SYS_stat, a, &sa) != 0 || syscall(SYS_stat, b, &sb) != 0)
        return 0;
    return sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino;
}

#define MAXFD 512
static int saved_fd[MAXFD];
static off_t saved_off[MAXFD];
static int nsaved = 0;

/* tenkana's settings for this engine, read once when the library is loaded
   (see aint_init at the end).  They are then removed from the environment,
   with the library itself, so that programs the engine starts -- \write18,
   a TikZ externalisation run, kpsewhich -- run as without tenkana. */
static char g_ctl[4096], g_main[4096], g_sub[4096];

static const char *ctl(void) {
    return g_ctl[0] ? g_ctl : NULL;
}

static void ctl_path(char *buf, size_t n, const char *name) {
    snprintf(buf, n, "%s/%s", ctl(), name);
}

static void send_event(const char *fmt, ...) {
    char line[256], p[4096];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(line, sizeof line, fmt, ap);
    va_end(ap);
    ctl_path(p, sizeof p, "ev");
    int fd = open(p, O_WRONLY | O_NONBLOCK | O_CLOEXEC);
    if (fd >= 0) {
        ssize_t r = write(fd, line, strlen(line)); /* < PIPE_BUF: atomic */
        (void)r;
        close(fd);
    }
}

/* Read one line (without the newline) from fd; -1 on EOF/error. */
static int read_line(int fd, char *buf, size_t n) {
    size_t i = 0;
    for (;;) {
        char c;
        ssize_t r = read(fd, &c, 1);
        if (r < 0 && errno == EINTR) continue;
        if (r <= 0) return -1;
        if (c == '\n') break;
        if (i + 1 < n) buf[i++] = c;
    }
    buf[i] = 0;
    return (int)i;
}

static int is_magic(const char *path) {
    if (!path || !ctl()) return 0;
    size_t n = strlen(path), m = strlen("tenkanapause");
    return n >= m && strcmp(path + n - m, "tenkanapause") == 0 &&
           (n == m || path[n - m - 1] == '/');
}

static void record_offsets(void) {
    nsaved = 0;
    DIR *d = opendir("/proc/self/fd");
    if (!d) return;
    int dfd = dirfd(d);
    struct dirent *e;
    while ((e = readdir(d)) && nsaved < MAXFD) {
        if (e->d_name[0] < '0' || e->d_name[0] > '9') continue;
        int fd = (int)to_long(e->d_name);
        struct stat st;
        if (fd == dfd || raw_fstat(fd, &st) != 0 || !S_ISREG(st.st_mode))
            continue;
        off_t off = lseek(fd, 0, SEEK_CUR);
        if (off < 0) continue;
        saved_fd[nsaved] = fd;
        saved_off[nsaved] = off;
        nsaved++;
    }
    closedir(d);
}

static void restore_offsets(void) {
    for (int i = 0; i < nsaved; i++)
        lseek(saved_fd[i], saved_off[i], SEEK_SET);
}

static const char *name_buf(int k) {
    static char n[32];
    snprintf(n, sizeof n, "tenkana-snap-%d", k);
    return n;
}

/* The engine's own handlers (TeX catches SIGINT to show its
   "Interruption" prompt): ignored while frozen, given back on resume. */
static const int held_sig[] = {SIGHUP, SIGINT, SIGPIPE, SIGCHLD};
#define NHELD (int)(sizeof held_sig / sizeof held_sig[0])
static struct sigaction engine_sa[NHELD];

/* A resumed engine reads from the terminal of the tenkana run that resumed it
   (path from the resume command, e.g. /proc/<pid>/fd/0), so TeX can ask
   and the user can answer, as without tenkana. */
static void take_terminal(const char *path) {
    int t = path && *path ? open(path, O_RDONLY | O_CLOEXEC) : -1;
    if (t < 0) t = open("/dev/null", O_RDONLY | O_CLOEXEC);
    if (t >= 0 && t != 0) {
        dup2(t, 0);
        close(t);
    }
    clearerr(stdin);
}

/* The frozen copy.  Returns only in a resumed child. */
static void holder(int k) {
    struct sigaction ign;
    memset(&ign, 0, sizeof ign);
    ign.sa_handler = SIG_IGN;
    for (int i = 0; i < NHELD; i++)
        sigaction(held_sig[i], held_sig[i] == SIGCHLD ? NULL : &ign,
                  &engine_sa[i]);
    signal(SIGCHLD, SIG_DFL);
    take_terminal(NULL); /* frozen: keep no terminal open */

    char p[4096], name[32];
    /* the engine's own name and out-of-memory score, for a resumed copy */
    char engine_name[32] = "", engine_oom[16] = "";
    prctl(PR_GET_NAME, engine_name, 0, 0, 0);
    {
        int oom = open("/proc/self/oom_score_adj", O_RDONLY | O_CLOEXEC);
        if (oom >= 0) {
            ssize_t r = read(oom, engine_oom, sizeof engine_oom - 1);
            engine_oom[r > 0 ? r : 0] = 0;
            close(oom);
        }
    }
    prctl(PR_SET_NAME, name_buf(k), 0, 0, 0); /* shows in ps/top */
    { /* If RAM runs out, the kernel should kill snapshots first, never the
         user's other programs.  Raising one's own score needs no root. */
        int oom = open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
        if (oom >= 0) {
            ssize_t r = write(oom, "1000", 4);
            (void)r;
            close(oom);
        }
    }
    snprintf(name, sizeof name, "cmd%d", k);
    ctl_path(p, sizeof p, name);
    unlink(p);
    if (mkfifo(p, 0600) != 0) _exit(1);
    int fd = open(p, O_RDWR | O_CLOEXEC); /* RDWR: never sees EOF */
    if (fd < 0) _exit(1);

    /* seconds; anything but a whole number means the default */
    const char *t = getenv("TENKANA_TTL");
    long ttl = 8 * 3600;
    if (t && *t && t[strspn(t, "0123456789")] == 0) ttl = to_long(t);
    time_t last = time(NULL);
    char dir[4096], used[4200];
    snprintf(dir, sizeof dir, "%s", ctl());
    snprintf(used, sizeof used, "%s/used", dir); /* touched by every build */

    for (;;) {
        struct pollfd pfd = {fd, POLLIN, 0};
        int r = poll(&pfd, 1, 30000);
        if (r < 0 && errno == EINTR) continue;
        while (waitpid(-1, NULL, WNOHANG) > 0)
            ; /* finished savers */
        if (r == 0) {
            /* ends after $TENKANA_TTL without a build of the document */
            struct stat us;
            if (syscall(SYS_stat, used, &us) == 0 && us.st_mtime > last)
                last = us.st_mtime;
            if (!dir_exists(dir) || time(NULL) - last > ttl) _exit(0);
            continue;
        }
        char cmd[2048];
        if (read_line(fd, cmd, sizeof cmd) < 0) _exit(0);
        last = time(NULL);
        if (strcmp(cmd, "quit") == 0) _exit(0);
        if (strncmp(cmd, "save ", 5) == 0) {
            /* "save <limit-bytes> <level> <path>": write this snapshot to
               disk.  Done by a copy of this holder, so the holder stays free
               to serve "resume" meanwhile. */
            char *q = cmd + 5;
            long limit = to_long(q);
            while (*q && *q != ' ')
                q++;
            if (*q) q++;
            int level = (int)to_long(q);
            while (*q && *q != ' ')
                q++;
            if (*q) q++;
            pid_t sv = fork();
            if (sv == 0) {
                int r = save_image(q, limit, level);
                if (r != RESTORED) _exit(r == 0 ? 0 : 1);
                /* A new process, restored from disk: carry on as holder k. */
                prctl(PR_SET_NAME, name_buf(k), 0, 0, 0);
                {
                    int oom =
                        open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
                    if (oom >= 0) {
                        ssize_t w = write(oom, "1000", 4);
                        (void)w;
                        close(oom);
                    }
                }
                last = time(NULL);
                send_event("held %d %d\n", k, (int)getpid());
                continue;
            }
            /* reap the saver later; it never touches our state */
            continue;
        }
        if (strcmp(cmd, "resume") != 0 && strncmp(cmd, "resume ", 7) != 0)
            continue;

        pid_t c = fork();
        if (c == 0) { /* resumed engine: an ordinary TeX run again */
            close(fd);
            prctl(PR_SET_NAME, engine_name, 0, 0, 0);
            if (engine_oom[0]) {
                int oom =
                    open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
                if (oom >= 0) {
                    ssize_t w = write(oom, engine_oom, strlen(engine_oom));
                    (void)w;
                    close(oom);
                }
            }
            for (int i = 0; i < NHELD; i++)
                sigaction(held_sig[i], &engine_sa[i], NULL);
            take_terminal(cmd[6] == ' ' ? cmd + 7 : NULL);
            restore_offsets();
            /* Drop text stdio had read ahead and continue right after the
               pause point, so an edited body is read fresh. */
            if (main_fp && main_pos >= 0) {
                /* fflush() discards a read stream's buffer (glibc would
                   otherwise "seek" inside the stale buffer), then fseek()
                   really re-reads from the file. */
                fflush(main_fp);
                fseek(main_fp, main_pos, SEEK_SET);
            }
            return;
        }
        if (c < 0) {
            send_event("exit -1 1\n");
            continue;
        }
        send_event("resumed %d %d\n", k, (int)c);
        int st;
        while (waitpid(c, &st, 0) < 0 && errno == EINTR)
            ;
        int code = WIFEXITED(st) ? WEXITSTATUS(st) : 128 + WTERMSIG(st);
        send_event("exit %d %d\n", (int)c, code);
    }
}

static void wait_go(void) {
    char p[4096], line[64];
    ctl_path(p, sizeof p, "go");
    int fd = open(p, O_RDONLY | O_CLOEXEC);
    if (fd < 0) return;
    read_line(fd, line, sizeof line);
    close(fd);
}

static FILE *pause_point(fopen_t real) {
    int k = pause_no++;
    record_offsets();
    /* logical read position in the main file (stdio may have read ahead) */
    main_pos = main_fp ? ftell(main_fp) : -1;
    pid_t s = fork();
    if (s == 0) {
        holder(k); /* returns only in a resumed child */
    } else if (s > 0) {
        send_event("pause %d %d %d\n", k, (int)getpid(), (int)s);
        wait_go();
    }
    return real("/dev/null", "r");
}

static FILE *open_main(fopen_t real, const char *path, const char *mode) {
    const char *sub = g_sub;
    if (!sub[0] || !g_main[0] || !mode || mode[0] != 'r' ||
        !same_file(path, g_main))
        return NULL;
    FILE *f = real(sub, mode);
    if (f) main_fp = f;
    return f;
}

/* SyncTeX.  The engine writes <job>.synctex(busy) during the run and renames
   it to <job>.synctex(.gz) at the end.  A snapshot holds the busy file open,
   so after that rename it could never be resumed.  So the busy file lives in
   $TENKANA_CTL instead (snapshots keep it, tenkana saves and restores it like
   any output file), and the rename becomes a copy to the real name. */
static int is_busy(const char *path) {
    if (!path || !ctl()) return 0;
    size_t n = strlen(path), m = strlen(".synctex(busy)");
    return n > m && strcmp(path + n - m, ".synctex(busy)") == 0;
}

static const char *busy_path(const char *path) {
    static char p[4096];
    const char *base = strrchr(path, '/');
    ctl_path(p, sizeof p, base ? base + 1 : path);
    return p;
}

/* The busy file is opened through zlib's gzopen() (or fopen() when not
   compressed).  Engines built with their own copy of zlib inside -- TeX
   Live's own binaries are -- call the C library's open() for it directly,
   so open() is wrapped too: whatever the route, the file ends up in
   $TENKANA_CTL. */
typedef int (*open_t)(const char *, int, ...);
typedef int (*openat_t)(int, const char *, int, ...);
typedef int (*open2_t)(const char *, int);
static open_t real_open, real_open64;
static openat_t real_openat, real_openat64;
static open2_t real_open_2, real_open64_2;

static mode_t open_mode(int flags, va_list ap) {
    return (flags & O_CREAT) || (flags & O_TMPFILE) == O_TMPFILE
               ? (mode_t)va_arg(ap, int)
               : 0;
}

int open(const char *path, int flags, ...) {
    if (!real_open) real_open = (open_t)dlsym(RTLD_NEXT, "open");
    va_list ap;
    va_start(ap, flags);
    mode_t m = open_mode(flags, ap);
    va_end(ap);
    return real_open(is_busy(path) ? busy_path(path) : path, flags, m);
}

int open64(const char *path, int flags, ...) {
    if (!real_open64) real_open64 = (open_t)dlsym(RTLD_NEXT, "open64");
    va_list ap;
    va_start(ap, flags);
    mode_t m = open_mode(flags, ap);
    va_end(ap);
    return real_open64(is_busy(path) ? busy_path(path) : path, flags, m);
}

int openat(int dirfd, const char *path, int flags, ...) {
    if (!real_openat) real_openat = (openat_t)dlsym(RTLD_NEXT, "openat");
    va_list ap;
    va_start(ap, flags);
    mode_t m = open_mode(flags, ap);
    va_end(ap);
    return real_openat(dirfd, is_busy(path) ? busy_path(path) : path, flags,
                       m);
}

int openat64(int dirfd, const char *path, int flags, ...) {
    if (!real_openat64)
        real_openat64 = (openat_t)dlsym(RTLD_NEXT, "openat64");
    va_list ap;
    va_start(ap, flags);
    mode_t m = open_mode(flags, ap);
    va_end(ap);
    return real_openat64(dirfd, is_busy(path) ? busy_path(path) : path,
                         flags, m);
}

/* what open() becomes in programs built with _FORTIFY_SOURCE */
int __open_2(const char *path, int flags) {
    if (!real_open_2) real_open_2 = (open2_t)dlsym(RTLD_NEXT, "__open_2");
    return real_open_2(is_busy(path) ? busy_path(path) : path, flags);
}

int __open64_2(const char *path, int flags) {
    if (!real_open64_2)
        real_open64_2 = (open2_t)dlsym(RTLD_NEXT, "__open64_2");
    return real_open64_2(is_busy(path) ? busy_path(path) : path, flags);
}

typedef void *(*gzopen_t)(const char *, const char *);
static gzopen_t real_gzopen, real_gzopen64;

void *gzopen(const char *path, const char *mode) {
    if (!real_gzopen) real_gzopen = (gzopen_t)dlsym(RTLD_NEXT, "gzopen");
    return real_gzopen(is_busy(path) ? busy_path(path) : path, mode);
}

void *gzopen64(const char *path, const char *mode) {
    if (!real_gzopen64) real_gzopen64 = (gzopen_t)dlsym(RTLD_NEXT, "gzopen64");
    return real_gzopen64(is_busy(path) ? busy_path(path) : path, mode);
}

typedef int (*rename_t)(const char *, const char *);
static rename_t real_rename;

int rename(const char *from, const char *to) {
    if (!real_rename) real_rename = (rename_t)dlsym(RTLD_NEXT, "rename");
    if (!is_busy(from)) return real_rename(from, to);
    /* copy to <to>.tenkana, then rename that into place */
    char tmp[4200];
    snprintf(tmp, sizeof tmp, "%s.tenkana", to);
    int in = open(busy_path(from), O_RDONLY | O_CLOEXEC);
    int out = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0666);
    int ok = in >= 0 && out >= 0;
    char buf[65536];
    ssize_t n;
    while (ok && (n = read(in, buf, sizeof buf)) > 0)
        if (write(out, buf, (size_t)n) != n) ok = 0;
    if (in >= 0) close(in);
    if (out >= 0 && close(out) != 0) ok = 0;
    if (!ok) {
        unlink(tmp);
        errno = EIO;
        return -1;
    }
    return real_rename(tmp, to);
}

FILE *fopen(const char *path, const char *mode) {
    if (!real_fopen) real_fopen = (fopen_t)dlsym(RTLD_NEXT, "fopen");
    if (is_magic(path)) return pause_point(real_fopen);
    if (is_busy(path)) path = busy_path(path);
    FILE *m = open_main(real_fopen, path, mode);
    return m ? m : real_fopen(path, mode);
}

FILE *fopen64(const char *path, const char *mode) {
    if (!real_fopen64) real_fopen64 = (fopen_t)dlsym(RTLD_NEXT, "fopen64");
    if (is_magic(path)) return pause_point(real_fopen64);
    if (is_busy(path)) path = busy_path(path);
    FILE *m = open_main(real_fopen64, path, mode);
    return m ? m : real_fopen64(path, mode);
}

int fclose(FILE *f) {
    if (!real_fclose) real_fclose = (fclose_t)dlsym(RTLD_NEXT, "fclose");
    if (f == main_fp) main_fp = NULL;
    return real_fclose(f);
}

/*
 * Snapshots keep the engine's output files open (the PDF, .aux, .log ...).  If
 * the live engine deletes one -- LuaTeX removes the PDF after a fatal error --
 * every snapshot would be left writing to a deleted file.  So instead of
 * deleting a regular file in the document's folder, move it to
 * $TENKANA_CTL/trash/<inode>; tenkana moves it back when it resumes a
 * snapshot.
 */
/* path is in the document's folder (TeX's working directory) or below */
static int in_cwd(const char *path) {
    if (path[0] != '/') return strncmp(path, "../", 3) != 0;
    char cwd[4096];
    if (!getcwd(cwd, sizeof cwd)) return 0;
    size_t n = strlen(cwd);
    return strncmp(path, cwd, n) == 0 && path[n] == '/';
}

static int protect(const char *path) {
    if (!ctl() || !path || !in_cwd(path)) return 0;
    { /* tenkana's own files are not TeX's (its cache folder can be below the
         document's folder: a document in the home folder) */
        const char *c = ctl(), *slash = strrchr(c, '/');
        size_t n = slash ? (size_t)(slash - c) : strlen(c);
        if (path[0] == '/' && strncmp(path, c, n) == 0 && path[n] == '/')
            return 0;
    }
    struct stat st;
    if (syscall(SYS_stat, path, &st) != 0 || !S_ISREG(st.st_mode)) return 0;
    char dir[4096], dst[4200];
    snprintf(dir, sizeof dir, "%s/trash", ctl());
    mkdir(dir, 0700);
    snprintf(dst, sizeof dst, "%s/%lu", dir, (unsigned long)st.st_ino);
    return rename(path, dst) == 0;
}

int unlink(const char *path) {
    if (!real_unlink) real_unlink = (unlink_t)dlsym(RTLD_NEXT, "unlink");
    if (is_busy(path)) return real_unlink(busy_path(path));
    if (protect(path)) return 0;
    return real_unlink(path);
}

int remove(const char *path) {
    if (!real_remove) real_remove = (unlink_t)dlsym(RTLD_NEXT, "remove");
    if (is_busy(path)) return real_remove(busy_path(path));
    if (protect(path)) return 0;
    return real_remove(path);
}

int unlinkat(int dirfd, const char *path, int flags) {
    if (!real_unlinkat)
        real_unlinkat = (unlinkat_t)dlsym(RTLD_NEXT, "unlinkat");
    if (!(flags & AT_REMOVEDIR) && (dirfd == AT_FDCWD || path[0] == '/') &&
        protect(path))
        return 0;
    return real_unlinkat(dirfd, path, flags);
}

/*
 * Files TeX looks for but doesn't find.  kpathsea tests a file's existence
 * with access() and stat() before opening it, so a failure in the document's
 * folder means "TeX wanted this file and it wasn't there" -- e.g. a .bbl
 * before biber has run, a chapter not written yet, a missing image.  Each is
 * appended to $TENKANA_CTL/missing as "<part>\t<path>", where <part> is the
 * pause count at that moment (0: preamble, 1: body, k+1: chapter k).  If such
 * a file appears later, tenkana rebuilds from that part.
 */
typedef int (*stat_t)(const char *, void *);
typedef int (*xstat_t)(int, const char *, void *);
static stat_t real_stat, real_stat64;
static xstat_t real_xstat, real_xstat64;
static int noting = 0;

static void note_missing(const char *path) {
    if (noting || !ctl() || !path || !*path || errno != ENOENT) return;
    if (path[0] == '/' && !in_cwd(path)) return; /* the document's folder */
    noting = 1;
    int saved = errno;
    char p[4096], line[4200];
    ctl_path(p, sizeof p, "missing");
    int fd = open(p, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0600);
    if (fd >= 0) {
        int len = snprintf(line, sizeof line, "%d\t%s\n", pause_no, path);
        if (len > 0 && len < (int)sizeof line) {
            ssize_t r = write(fd, line, len);
            (void)r;
        }
        close(fd);
    }
    errno = saved;
    noting = 0;
}

int stat(const char *path, struct stat *buf) {
    if (!real_stat) real_stat = (stat_t)dlsym(RTLD_NEXT, "stat");
    int r =
        real_stat ? real_stat(path, buf) : (int)syscall(SYS_stat, path, buf);
    if (r != 0) note_missing(path);
    return r;
}

int stat64(const char *path, struct stat64 *buf) {
    if (!real_stat64) real_stat64 = (stat_t)dlsym(RTLD_NEXT, "stat64");
    int r = real_stat64 ? real_stat64(path, buf)
                        : (int)syscall(SYS_stat, path, buf);
    if (r != 0) note_missing(path);
    return r;
}

/* older glibc (official TeX Live binaries are built against it) */
int __xstat(int ver, const char *path, void *buf) {
    if (!real_xstat) real_xstat = (xstat_t)dlsym(RTLD_NEXT, "__xstat");
    int r = real_xstat ? real_xstat(ver, path, buf)
                       : (int)syscall(SYS_stat, path, buf);
    if (r != 0) note_missing(path);
    return r;
}

int __xstat64(int ver, const char *path, void *buf) {
    if (!real_xstat64) real_xstat64 = (xstat_t)dlsym(RTLD_NEXT, "__xstat64");
    int r = real_xstat64 ? real_xstat64(ver, path, buf)
                         : (int)syscall(SYS_stat, path, buf);
    if (r != 0) note_missing(path);
    return r;
}

typedef int (*access_t)(const char *, int);
static access_t real_access;

int access(const char *path, int mode) {
    if (!real_access) real_access = (access_t)dlsym(RTLD_NEXT, "access");
    int r = real_access(path, mode);
    if (r != 0) note_missing(path);
    return r;
}

/* ======================================================================
 * Disk snapshots: save a holder to a compressed file, and restore it into
 * a freshly started engine -- without root.
 *
 * Requirements, all ensured by tenkana: the engine runs with address-space
 * randomisation off (personality ADDR_NO_RANDOMIZE, allowed for anyone),
 * with exactly the same command line and environment as the original run
 * (so the binary, libraries, stack and vdso land at the same addresses),
 * and on the same kernel with the same files.
 *
 * Saving (in a copy S of a holder):
 *   1. record open files, signal handlers, mask, cwd, umask, brk, fs base;
 *   2. capture the CPU registers (ctx_capture) -- the restore point;
 *   3. fork a pristine child C and read C's memory through /proc/C/mem
 *      (a parent may read its child's memory, also under Yama ptrace
 *      scope 1), so the saver's own work never pollutes the image;
 *   4. store, per memory region, only the pages that differ from the
 *      backing file (for file mappings) or are non-zero (anonymous);
 *   5. compress with zstd (or zlib) and write <path> atomically.
 *
 * Restoring (in the constructor below, before the engine's main()):
 *   phase 1 (C library available): check the image, decompress it into a
 *     work area that collides with nothing, switch to a stack inside it;
 *   phase 2 (raw system calls only): unmap the fresh process's memory,
 *     re-create every saved region at its address, copy the saved pages,
 *     reopen the files, restore signals, cwd and fs base, and jump to the
 *     restore point -- where the code carries on as holder k.
 * ====================================================================== */
#include <stdint.h>
#include <sys/mman.h>
#include <sys/personality.h>
#include <sys/utsname.h>
#include <asm/prctl.h>

#define PG 4096UL
#define IMG_MAGIC "ANTIMG03"
#define WORK_HEAD (4UL << 20) /* plan + stack at the work area start */

struct snap_ctx {
    uint64_t rbx, rbp, r12, r13, r14, r15, rsp, rip;
};
static struct snap_ctx g_ctx;

/* Returns 0 when capturing; returns 1 again when restored from an image. */
__attribute__((naked, noinline, used, returns_twice)) static int
ctx_capture(struct snap_ctx *c) {
    (void)c;
    __asm__ volatile("movq %rbx, 0(%rdi)\n\t"
                     "movq %rbp, 8(%rdi)\n\t"
                     "movq %r12, 16(%rdi)\n\t"
                     "movq %r13, 24(%rdi)\n\t"
                     "movq %r14, 32(%rdi)\n\t"
                     "movq %r15, 40(%rdi)\n\t"
                     "leaq 8(%rsp), %rdx\n\t"
                     "movq %rdx, 48(%rdi)\n\t"
                     "movq (%rsp), %rdx\n\t"
                     "movq %rdx, 56(%rdi)\n\t"
                     "xorl %eax, %eax\n\t"
                     "ret\n\t");
}

__attribute__((naked, noreturn, noinline, used)) static void
ctx_jump(struct snap_ctx *c) {
    (void)c;
    __asm__ volatile("movq 0(%rdi), %rbx\n\t"
                     "movq 8(%rdi), %rbp\n\t"
                     "movq 16(%rdi), %r12\n\t"
                     "movq 24(%rdi), %r13\n\t"
                     "movq 32(%rdi), %r14\n\t"
                     "movq 40(%rdi), %r15\n\t"
                     "movq 48(%rdi), %rsp\n\t"
                     "movl $1, %eax\n\t"
                     "jmpq *56(%rdi)\n\t");
}

static inline long rsys(long n, long a, long b, long c, long d, long e,
                        long f) {
    register long r10 __asm__("r10") = d;
    register long r8 __asm__("r8") = e;
    register long r9 __asm__("r9") = f;
    long ret;
    __asm__ volatile("syscall"
                     : "=a"(ret)
                     : "a"(n), "D"(a), "S"(b), "d"(c), "r"(r10), "r"(r8),
                       "r"(r9)
                     : "rcx", "r11", "memory");
    return ret;
}

enum { R_ANON = 0, R_FILE = 1, R_HEAP = 2, R_STACK = 3, R_SPECIAL = 4 };

struct img_head {
    char magic[8];
    uint32_t comp, nreg; /* comp: 1 zstd, 2 zlib */
    uint64_t raw_len, comp_len;
    char kernel[256]; /* uname release + version */
};

struct img_reg {
    uint64_t start, end, offset;
    uint32_t prot, kind, npages, pad;
    uint32_t shared, pad2; /* read-only MAP_SHARED file mapping */
    uint64_t ino, fsize;
    int64_t mtime_ns;
    char path[512];
};

struct ksa {
    uint64_t handler, flags, restorer, mask;
};

struct img_fd {
    int32_t fd;
    uint32_t flags;
    int64_t pos;
    uint32_t type; /* 0 regular, 1 fifo, 2 char device */
    char path[1020];
};

#define MAXFDS 256
struct img_state {
    struct snap_ctx ctx;
    uint64_t fsbase, brk_end, sigmask;
    struct ksa sa[65];
    uint32_t umask, nfd;
    char cwd[4096];
    struct img_fd fds[MAXFDS];
};

/* payload = struct img_state, then records {u32 region, u32 page, 4096 bytes}
 */
struct page_rec {
    uint32_t reg, page;
};

/* ---- small helpers (saving side, C library allowed) -------------------- */
struct buf {
    char *p;
    size_t len, cap;
};

static int buf_put(struct buf *b, const void *d, size_t n) {
    if (b->len + n > b->cap) {
        size_t nc = b->cap ? b->cap * 2 : (64UL << 20);
        while (nc < b->len + n)
            nc *= 2;
        void *q = b->p ? mremap(b->p, b->cap, nc, MREMAP_MAYMOVE)
                       : mmap(NULL, nc, PROT_READ | PROT_WRITE,
                              MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (q == MAP_FAILED) return -1;
        b->p = q;
        b->cap = nc;
    }
    memcpy(b->p + b->len, d, n);
    b->len += n;
    return 0;
}

static int is_zero(const char *p) {
    const uint64_t *w = (const uint64_t *)p;
    for (size_t i = 0; i < PG / 8; i++)
        if (w[i]) return 0;
    return 1;
}

static void kernel_id(char *out, size_t n) {
    struct utsname u;
    if (uname(&u) == 0)
        snprintf(out, n, "%s %s", u.release, u.version);
    else
        snprintf(out, n, "?");
}

static void write_status(const char *path, const char *fmt, ...) {
    char p[1200], tmp[1300], line[512];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(line, sizeof line, fmt, ap);
    va_end(ap);
    snprintf(p, sizeof p, "%s.status", path);
    snprintf(tmp, sizeof tmp, "%s.tmp", p);
    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
    if (fd < 0) return;
    ssize_t w = write(fd, line, strlen(line));
    (void)w;
    close(fd);
    rename(tmp, p);
}

typedef size_t (*zstd_bound_t)(size_t);
typedef size_t (*zstd_comp_t)(void *, size_t, const void *, size_t, int);
typedef size_t (*zstd_decomp_t)(void *, size_t, const void *, size_t);
typedef unsigned (*zstd_iserr_t)(size_t);
typedef unsigned long (*z_bound_t)(unsigned long);
typedef int (*z_comp2_t)(unsigned char *, unsigned long *,
                         const unsigned char *, unsigned long, int);
typedef int (*z_uncomp_t)(unsigned char *, unsigned long *,
                          const unsigned char *, unsigned long);

/* Compress src into a new mapping; returns its length (0 on failure). */
static size_t compress_blob(const char *src, size_t n, int level, char **out,
                            uint32_t *comp) {
    void *z = dlopen("libzstd.so.1", RTLD_NOW | RTLD_LOCAL);
    if (z) {
        zstd_bound_t bound = (zstd_bound_t)dlsym(z, "ZSTD_compressBound");
        zstd_comp_t cmp = (zstd_comp_t)dlsym(z, "ZSTD_compress");
        zstd_iserr_t iserr = (zstd_iserr_t)dlsym(z, "ZSTD_isError");
        if (bound && cmp && iserr) {
            size_t cap = bound(n);
            char *d = mmap(NULL, cap, PROT_READ | PROT_WRITE,
                           MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
            if (d != MAP_FAILED) {
                size_t r = cmp(d, cap, src, n, level);
                if (!iserr(r)) {
                    *out = d;
                    *comp = 1;
                    return r;
                }
                munmap(d, cap);
            }
        }
    }
    void *zl = dlopen("libz.so.1", RTLD_NOW | RTLD_LOCAL);
    if (zl) {
        z_bound_t bound = (z_bound_t)dlsym(zl, "compressBound");
        z_comp2_t cmp = (z_comp2_t)dlsym(zl, "compress2");
        if (bound && cmp) {
            unsigned long cap = bound(n);
            char *d = mmap(NULL, cap, PROT_READ | PROT_WRITE,
                           MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
            if (d != MAP_FAILED) {
                unsigned long len = cap;
                if (cmp((unsigned char *)d, &len, (const unsigned char *)src,
                        n, 6) == 0) {
                    *out = d;
                    *comp = 2;
                    return len;
                }
                munmap(d, cap);
            }
        }
    }
    return 0;
}

static int decompress_into(uint32_t comp, const char *src, size_t n, char *dst,
                           size_t want) {
    if (comp == 1) {
        void *z = dlopen("libzstd.so.1", RTLD_NOW | RTLD_LOCAL);
        if (!z) return -1;
        zstd_decomp_t dec = (zstd_decomp_t)dlsym(z, "ZSTD_decompress");
        zstd_iserr_t iserr = (zstd_iserr_t)dlsym(z, "ZSTD_isError");
        if (!dec || !iserr) return -1;
        size_t r = dec(dst, want, src, n);
        return (!iserr(r) && r == want) ? 0 : -1;
    }
    if (comp == 2) {
        void *z = dlopen("libz.so.1", RTLD_NOW | RTLD_LOCAL);
        if (!z) return -1;
        z_uncomp_t dec = (z_uncomp_t)dlsym(z, "uncompress");
        if (!dec) return -1;
        unsigned long len = want;
        return (dec((unsigned char *)dst, &len, (const unsigned char *)src,
                    n) == 0 &&
                len == want)
                   ? 0
                   : -1;
    }
    return -1;
}

/* Parse one /proc/PID/maps line. */
static int parse_map(const char *line, uint64_t *a, uint64_t *b, char perms[5],
                     uint64_t *off, char *path, size_t pathlen) {
    /* "start-end perms offset dev inode   path" (no sscanf: portability) */
    const char *q = line;
    uint64_t v[3] = {0, 0, 0};
    for (int f = 0; f < 3; f++) {
        if (f == 2) { /* perms before offset */
            for (int i = 0; i < 4; i++)
                perms[i] = q[i] ? q[i] : '-';
            perms[4] = 0;
            while (*q && *q != ' ')
                q++;
            while (*q == ' ')
                q++;
        }
        int digits = 0;
        for (;; q++) {
            char ch = *q;
            int d = ch >= '0' && ch <= '9'   ? ch - '0'
                    : ch >= 'a' && ch <= 'f' ? ch - 'a' + 10
                                             : -1;
            if (d < 0) break;
            v[f] = v[f] * 16 + (uint64_t)d;
            digits++;
        }
        if (!digits) return -1;
        q++; /* '-' or ' ' */
        while (*q == ' ')
            q++;
    }
    *a = v[0];
    *b = v[1];
    *off = v[2];
    for (int skip = 0; skip < 2; skip++) { /* dev, inode */
        while (*q && *q != ' ')
            q++;
        while (*q == ' ')
            q++;
    }
    size_t l = strcspn(q, "\n");
    if (l >= pathlen) l = pathlen - 1;
    memcpy(path, q, l);
    path[l] = 0;
    return 0;
}

static int prot_of(const char *perms) {
    return (perms[0] == 'r' ? PROT_READ : 0) |
           (perms[1] == 'w' ? PROT_WRITE : 0) |
           (perms[2] == 'x' ? PROT_EXEC : 0);
}

static int is_special(const char *path) {
    return !strcmp(path, "[vvar]") || !strcmp(path, "[vdso]") ||
           !strcmp(path, "[vsyscall]") || !strcmp(path, "[vvar_vclock]");
}

/* ---- saving ---------------------------------------------------------------
 */
static struct img_state g_state;

static int record_process_state(char *why, size_t wl) {
    memset(&g_state, 0, sizeof g_state);
    DIR *d = opendir("/proc/self/fd");
    if (!d) {
        snprintf(why, wl, "cannot list open files");
        return -1;
    }
    int dfd = dirfd(d);
    struct dirent *e;
    while ((e = readdir(d))) {
        if (e->d_name[0] < '0' || e->d_name[0] > '9') continue;
        int fd = (int)to_long(e->d_name);
        if (fd == dfd) continue;
        if (g_state.nfd >= MAXFDS) {
            closedir(d);
            snprintf(why, wl, "too many open files");
            return -1;
        }
        struct img_fd *f = &g_state.fds[g_state.nfd];
        char lp[64];
        snprintf(lp, sizeof lp, "/proc/self/fd/%d", fd);
        ssize_t n = readlink(lp, f->path, sizeof f->path - 1);
        if (n <= 0) continue;
        f->path[n] = 0;
        if (f->path[0] != '/' || strstr(f->path, " (deleted)")) {
            closedir(d);
            snprintf(why, wl, "an open file can't be saved (%s)", f->path);
            return -1;
        }
        struct stat st;
        if (raw_fstat(fd, &st) != 0) continue;
        f->type = S_ISREG(st.st_mode)    ? 0
                  : S_ISFIFO(st.st_mode) ? 1
                  : S_ISCHR(st.st_mode)  ? 2
                                         : 9;
        if (f->type == 9) {
            closedir(d);
            snprintf(why, wl, "unsupported open file %s", f->path);
            return -1;
        }
        f->fd = fd;
        f->flags = (uint32_t)fcntl(fd, F_GETFL) |
                   ((fcntl(fd, F_GETFD) & FD_CLOEXEC) ? O_CLOEXEC : 0);
        f->pos = f->type == 0 ? lseek(fd, 0, SEEK_CUR) : 0;
        g_state.nfd++;
    }
    closedir(d);
    rsys(SYS_arch_prctl, ARCH_GET_FS, (long)&g_state.fsbase, 0, 0, 0, 0);
    g_state.brk_end = (uint64_t)rsys(SYS_brk, 0, 0, 0, 0, 0, 0);
    rsys(SYS_rt_sigprocmask, SIG_BLOCK, 0, (long)&g_state.sigmask, 8, 0, 0);
    for (int s = 1; s <= 64; s++)
        rsys(SYS_rt_sigaction, s, 0, (long)&g_state.sa[s], 8, 0, 0);
    if (!getcwd(g_state.cwd, sizeof g_state.cwd)) {
        snprintf(why, wl, "no cwd");
        return -1;
    }
    mode_t m = umask(0);
    umask(m);
    g_state.umask = m;
    return 0;
}

/* Build the image of process `c` (a pristine copy of us) into buf. */
static int build_image(pid_t c, struct buf *regs, struct buf *payload,
                       uint32_t *nreg, char *why, size_t wl) {
    char p[64];
    snprintf(p, sizeof p, "/proc/%d/maps", (int)c);
    FILE *mf = real_fopen ? real_fopen(p, "r") : NULL;
    if (!mf) {
        snprintf(why, wl, "cannot read the memory map");
        return -1;
    }
    snprintf(p, sizeof p, "/proc/%d/mem", (int)c);
    int mem = open(p, O_RDONLY | O_CLOEXEC);
    if (mem < 0) {
        real_fclose(mf);
        snprintf(why, wl, "cannot read the snapshot's memory");
        return -1;
    }
    if (buf_put(payload, &g_state, sizeof g_state) < 0) goto nomem;

    char line[1024], *chunk = mmap(NULL, 1UL << 20, PROT_READ | PROT_WRITE,
                                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    char *fpage = mmap(NULL, 1UL << 20, PROT_READ | PROT_WRITE,
                       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (chunk == MAP_FAILED || fpage == MAP_FAILED) goto nomem;
    uint32_t ri = 0;
    while (fgets(line, sizeof line, mf)) {
        struct img_reg r;
        memset(&r, 0, sizeof r);
        char perms[5];
        if (parse_map(line, &r.start, &r.end, perms, &r.offset, r.path,
                      sizeof r.path) < 0)
            continue;
        r.prot = prot_of(perms);
        if (is_special(r.path))
            r.kind = R_SPECIAL;
        else if (perms[3] == 's') {
            /* read-only shared file mappings (e.g. glibc's gconv cache) are
               simply mapped again; writable shared memory can't be saved */
            if (r.path[0] != '/' || (r.prot & PROT_WRITE) ||
                strstr(r.path, " (deleted)")) {
                snprintf(why, wl, "shared memory can't be saved");
                goto fail;
            }
            r.kind = R_FILE;
            r.shared = 1;
        } else if (!strcmp(r.path, "[heap]"))
            r.kind = R_HEAP;
        else if (!strcmp(r.path, "[stack]"))
            r.kind = R_STACK;
        else if (r.path[0] == '/') {
            if (strstr(r.path, " (deleted)")) {
                snprintf(why, wl, "a mapped file was deleted");
                goto fail;
            }
            r.kind = R_FILE;
        } else
            r.kind = R_ANON;

        int ffd = -1;
        if (r.kind == R_FILE) {
            ffd = open(r.path, O_RDONLY | O_CLOEXEC);
            struct stat st;
            if (ffd < 0 || raw_fstat(ffd, &st) != 0) {
                snprintf(why, wl, "cannot open %s", r.path);
                goto fail;
            }
            r.ino = st.st_ino;
            r.fsize = st.st_size;
            r.mtime_ns =
                (int64_t)st.st_mtim.tv_sec * 1000000000LL + st.st_mtim.tv_nsec;
        }
        if (r.kind != R_SPECIAL && !r.shared) {
            for (uint64_t a = r.start; a < r.end; a += (1UL << 20)) {
                size_t n =
                    (r.end - a) < (1UL << 20) ? (r.end - a) : (1UL << 20);
                ssize_t got = pread(mem, chunk, n, (off_t)a);
                if (got != (ssize_t)n) {
                    memset(chunk, 0, n);
                    if (got > 0) {
                    }
                }
                if (ffd >= 0) {
                    off_t fo = (off_t)(r.offset + (a - r.start));
                    memset(fpage, 0, n);
                    if ((uint64_t)fo < r.fsize) {
                        ssize_t fr = pread(ffd, fpage, n, fo);
                        (void)fr;
                    }
                }
                for (size_t i = 0; i < n; i += PG) {
                    const char *pg = chunk + i;
                    int keep = ffd >= 0 ? memcmp(pg, fpage + i, PG) != 0
                                        : !is_zero(pg);
                    if (!keep) continue;
                    struct page_rec pr = {ri,
                                          (uint32_t)((a + i - r.start) / PG)};
                    if (buf_put(payload, &pr, sizeof pr) < 0 ||
                        buf_put(payload, pg, PG) < 0)
                        goto nomem;
                    r.npages++;
                }
            }
        }
        if (ffd >= 0) close(ffd);
        if (buf_put(regs, &r, sizeof r) < 0) goto nomem;
        ri++;
    }
    *nreg = ri;
    real_fclose(mf);
    close(mem);
    munmap(chunk, 1UL << 20);
    munmap(fpage, 1UL << 20);
    return 0;
nomem:
    snprintf(why, wl, "out of memory");
fail:
    real_fclose(mf);
    close(mem);
    return -1;
}

/* Returns 0 saved, 1 not saved (status explains), RESTORED in a restored
 * process. */
static int save_image(const char *path, long limit, int level) {
    char why[600] = "";
    struct timespec t0, t1;
    clock_gettime(CLOCK_MONOTONIC, &t0);
    if (!real_fopen) real_fopen = (fopen_t)dlsym(RTLD_NEXT, "fopen");
    if (!real_fclose) real_fclose = (fclose_t)dlsym(RTLD_NEXT, "fclose");
    if ((personality(0xffffffff) & ADDR_NO_RANDOMIZE) == 0) {
        write_status(path, "fail address randomisation is on\n");
        return 1;
    }
    if (record_process_state(why, sizeof why) < 0) {
        write_status(path, "fail %s\n", why);
        return 1;
    }
    if (ctx_capture(&g_ctx)) return RESTORED; /* <- the restore point */

    pid_t c = fork();
    if (c == 0) { /* pristine copy: just wait */
        prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
        for (;;)
            pause();
    }
    if (c < 0) {
        write_status(path, "fail fork\n");
        return 1;
    }

    struct buf regs = {0}, payload = {0};
    uint32_t nreg = 0;
    int ok = build_image(c, &regs, &payload, &nreg, why, sizeof why);
    kill(c, SIGKILL);
    waitpid(c, NULL, 0);
    if (ok < 0) {
        write_status(path, "fail %s\n", why);
        return 1;
    }

    struct img_head h;
    memset(&h, 0, sizeof h);
    memcpy(h.magic, IMG_MAGIC, 8);
    h.nreg = nreg;
    h.raw_len = payload.len;
    kernel_id(h.kernel, sizeof h.kernel);
    if (limit > 0 && payload.len / 20 > (size_t)limit) {
        /* can't fit even at 20:1 (real images compress 7-13:1): don't spend
           the time compressing; report an estimate */
        munmap(payload.p, payload.cap);
        write_status(path, "big %zu ~\n", payload.len / 10);
        return 1;
    }
    char *cdata = NULL;
    size_t clen =
        compress_blob(payload.p, payload.len, level, &cdata, &h.comp);
    munmap(payload.p, payload.cap);
    if (!clen) {
        write_status(path, "fail compression\n");
        return 1;
    }
    h.comp_len = clen;
    size_t total = sizeof h + regs.len + clen;
    if (limit > 0 && (long)total > limit) {
        write_status(path, "big %zu\n", total);
        return 1;
    }
    char tmp[1100];
    snprintf(tmp, sizeof tmp, "%s.tmp", path);
    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
    if (fd < 0) {
        write_status(path, "fail cannot write %s\n", tmp);
        return 1;
    }
    int bad = write(fd, &h, sizeof h) != (ssize_t)sizeof h;
    bad |= write(fd, regs.p, regs.len) != (ssize_t)regs.len;
    for (size_t o = 0; !bad && o < clen;) {
        ssize_t w = write(fd, cdata + o, clen - o);
        if (w <= 0)
            bad = 1;
        else
            o += (size_t)w;
    }
    bad |= fsync(fd) != 0;
    close(fd);
    if (bad || rename(tmp, path) != 0) {
        unlink(tmp);
        write_status(path, "fail write error\n");
        return 1;
    }
    clock_gettime(CLOCK_MONOTONIC, &t1);
    double secs = (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) / 1e9;
    write_status(path, "ok %zu %llu %.2f\n", total,
                 (unsigned long long)h.raw_len, secs);
    return 0;
}

/* ---- restoring --------------------------------------------------------- */
struct cur_map {
    uint64_t start, end;
    uint32_t keep, pad;
};

struct plan {
    struct img_head h;
    uint64_t work, work_len;
    uint32_t ncur, nreg;
    uint64_t heap_start;
    struct img_reg *regs; /* inside the work area */
    struct cur_map *cur;  /* inside the work area */
    char *payload;        /* inside the work area */
};

#define P2                                                                    \
    __attribute__((noinline, used,                                            \
                   optimize("no-tree-loop-distribute-patterns",               \
                            "no-jump-tables", "no-stack-protector")))

P2 static void p2_copy(volatile uint64_t *d, const volatile uint64_t *s,
                       uint64_t n) {
    for (uint64_t i = 0; i < n / 8; i++)
        d[i] = s[i];
}

P2 static void p2_zero(volatile uint64_t *d, uint64_t n) {
    for (uint64_t i = 0; i < n / 8; i++)
        d[i] = 0;
}

P2 static void p2_die(void) {
    rsys(SYS_exit_group, 76, 0, 0, 0, 0, 0);
    for (;;)
        ;
}

/* Phase 2: no C library from here on -- its memory is being replaced. */
P2 __attribute__((noreturn)) static void restore_phase2(struct plan *pl) {
    struct img_reg *R = pl->regs;
    struct img_state *st = (struct img_state *)pl->payload;

    /* 1. drop the fresh process's memory (except what we stand on) */
    for (uint32_t i = 0; i < pl->ncur; i++)
        if (!pl->cur[i].keep)
            rsys(SYS_munmap, (long)pl->cur[i].start,
                 (long)(pl->cur[i].end - pl->cur[i].start), 0, 0, 0, 0);

    /* 2. the brk heap, then every other region */
    for (uint32_t i = 0; i < pl->nreg; i++) {
        struct img_reg *r = &R[i];
        uint64_t len = r->end - r->start;
        if (r->kind == R_SPECIAL) continue;
        if (r->kind == R_HEAP) {
            if ((uint64_t)rsys(SYS_brk, (long)r->end, 0, 0, 0, 0, 0) != r->end)
                p2_die();
            p2_zero((volatile uint64_t *)r->start, len);
            continue;
        }
        if (r->kind == R_STACK) { /* kernel stack: write into it */
            p2_zero((volatile uint64_t *)r->start, len);
            continue;
        }
        if (r->kind == R_FILE && r->pad == 1)
            continue; /* our own code: kept */
        if (r->kind == R_FILE) {
            long fd = rsys(SYS_open, (long)r->path, O_RDONLY | O_CLOEXEC, 0, 0,
                           0, 0);
            if (fd < 0) p2_die();
            uint64_t inside =
                r->fsize > r->offset
                    ? ((r->fsize - r->offset + PG - 1) & ~(PG - 1))
                    : 0;
            if (inside > len) inside = len;
            if (inside) {
                long m =
                    r->shared
                        ? rsys(SYS_mmap, (long)r->start, (long)inside, r->prot,
                               MAP_SHARED | MAP_FIXED, fd, (long)r->offset)
                        : rsys(SYS_mmap, (long)r->start, (long)inside,
                               PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED,
                               fd, (long)r->offset);
                if (m != (long)r->start) p2_die();
            }
            rsys(SYS_close, fd, 0, 0, 0, 0, 0);
            if (inside < len) {
                long m = rsys(SYS_mmap, (long)(r->start + inside),
                              (long)(len - inside), PROT_READ | PROT_WRITE,
                              MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
                if (m != (long)(r->start + inside)) p2_die();
            }
            continue;
        }
        long m =
            rsys(SYS_mmap, (long)r->start, (long)len, PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
        if (m != (long)r->start) p2_die();
    }

    /* 3. the saved pages */
    char *q = pl->payload + sizeof(struct img_state);
    char *end = pl->payload + pl->h.raw_len;
    while (q + sizeof(struct page_rec) + PG <= end) {
        struct page_rec *pr = (struct page_rec *)q;
        struct img_reg *r = &R[pr->reg];
        p2_copy((volatile uint64_t *)(r->start + (uint64_t)pr->page * PG),
                (const volatile uint64_t *)(q + sizeof *pr), PG);
        q += sizeof *pr + PG;
    }

    /* 4. final protections */
    for (uint32_t i = 0; i < pl->nreg; i++) {
        struct img_reg *r = &R[i];
        if (r->kind == R_ANON ||
            (r->kind == R_FILE && r->pad != 1 && !r->shared))
            rsys(SYS_mprotect, (long)r->start, (long)(r->end - r->start),
                 r->prot, 0, 0, 0);
    }

    /* 5. open files, at their numbers and positions */
    for (long fd = 0; fd < 1024; fd++)
        rsys(SYS_close, fd, 0, 0, 0, 0, 0);
    for (uint32_t i = 0; i < st->nfd; i++) {
        struct img_fd *f = &st->fds[i];
        long flags =
            (long)(f->flags & ~(uint32_t)(O_CREAT | O_TRUNC | O_EXCL));
        if (f->type == 1)
            flags = (flags & ~O_ACCMODE) | O_RDWR; /* FIFO: never blocks */
        long fd = rsys(SYS_open, (long)f->path, flags, 0, 0, 0, 0);
        if (fd < 0) p2_die();
        if (fd != f->fd) {
            if (rsys(SYS_dup3, fd, f->fd, (long)(f->flags & O_CLOEXEC), 0, 0,
                     0) < 0)
                p2_die();
            rsys(SYS_close, fd, 0, 0, 0, 0, 0);
        }
        if (f->type == 0) rsys(SYS_lseek, f->fd, f->pos, SEEK_SET, 0, 0, 0);
    }

    /* 6. signals, directory, umask, thread pointer */
    for (long s = 1; s <= 64; s++) {
        if (s == SIGKILL || s == SIGSTOP) continue;
        rsys(SYS_rt_sigaction, s, (long)&st->sa[s], 0, 8, 0, 0);
    }
    rsys(SYS_rt_sigprocmask, SIG_SETMASK, (long)&st->sigmask, 0, 8, 0, 0);
    rsys(SYS_chdir, (long)st->cwd, 0, 0, 0, 0, 0);
    rsys(SYS_umask, st->umask, 0, 0, 0, 0, 0);
    rsys(SYS_arch_prctl, ARCH_SET_FS, (long)st->fsbase, 0, 0, 0, 0);

    /* 7. free the decompressed image (keep the small part we stand on) */
    rsys(SYS_munmap, (long)(pl->work + WORK_HEAD),
         (long)(pl->work_len - WORK_HEAD), 0, 0, 0, 0);

    /* 8. back into the saved holder, as if ctx_capture() returned 1 */
    ctx_jump(&g_ctx);
}

static const char *restore_image(const char *path) {
    static char why[700];
    int fd = open(path, O_RDONLY | O_CLOEXEC);
    if (fd < 0) return "the image file can't be read";
    struct img_head h;
    if (read(fd, &h, sizeof h) != (ssize_t)sizeof h ||
        memcmp(h.magic, IMG_MAGIC, 8) != 0) {
        close(fd);
        return "not a tenkana image";
    }
    char kid[256];
    kernel_id(kid, sizeof kid);
    if (strcmp(kid, h.kernel) != 0) {
        close(fd);
        return "the kernel changed";
    }
    size_t rl = (size_t)h.nreg * sizeof(struct img_reg);
    struct img_reg *regs = malloc(rl);
    char *comp = malloc(h.comp_len);
    if (!regs || !comp) {
        close(fd);
        return "out of memory";
    }
    if (read(fd, regs, rl) != (ssize_t)rl) {
        close(fd);
        return "the image file is damaged";
    }
    for (size_t o = 0; o < h.comp_len;) {
        ssize_t r = read(fd, comp + o, h.comp_len - o);
        if (r <= 0) {
            close(fd);
            return "the image file is damaged";
        }
        o += (size_t)r;
    }
    close(fd);

    /* the files behind file mappings must be the same files */
    for (uint32_t i = 0; i < h.nreg; i++) {
        struct img_reg *r = &regs[i];
        if (r->kind != R_FILE) continue;
        struct stat st;
        if (syscall(SYS_stat, r->path, &st) != 0 ||
            (uint64_t)st.st_ino != r->ino ||
            (uint64_t)st.st_size != r->fsize ||
            (int64_t)st.st_mtim.tv_sec * 1000000000LL + st.st_mtim.tv_nsec !=
                r->mtime_ns) {
            snprintf(why, sizeof why, "%s changed", r->path);
            return why;
        }
    }

    /* current memory map */
    FILE *mf = real_fopen("/proc/self/maps", "r");
    if (!mf) return "cannot read the memory map";
    struct cur_map *cur = malloc(4096 * sizeof *cur);
    char(*curpath)[512] = malloc(4096 * 512);
    uint32_t ncur = 0;
    char line[1024];
    while (ncur < 4096 && fgets(line, sizeof line, mf)) {
        char perms[5];
        uint64_t off;
        if (parse_map(line, &cur[ncur].start, &cur[ncur].end, perms, &off,
                      curpath[ncur], 512) < 0)
            continue;
        cur[ncur].keep = is_special(curpath[ncur]) ||
                         !strcmp(curpath[ncur], "[stack]") ||
                         !strcmp(curpath[ncur], "[heap]");
        ncur++;
    }
    real_fclose(mf);

    /* our own code must sit where it sat when the image was made */
    uint64_t here = (uint64_t)(uintptr_t)&restore_phase2;
    int found = 0;
    for (uint32_t i = 0; i < h.nreg; i++) {
        struct img_reg *r = &regs[i];
        r->pad = 0;
        if (r->kind == R_FILE && here >= r->start && here < r->end) {
            for (uint32_t j = 0; j < ncur; j++)
                if (cur[j].start == r->start && cur[j].end == r->end &&
                    !strcmp(curpath[j], r->path)) {
                    cur[j].keep = 1;
                    r->pad = 1;
                    found = 1;
                }
        }
        if (r->kind == R_SPECIAL || r->kind == R_STACK) {
            int same = 0;
            for (uint32_t j = 0; j < ncur; j++)
                if (!strcmp(curpath[j], r->path) && cur[j].end == r->end &&
                    (r->kind == R_STACK || cur[j].start == r->start))
                    same = 1;
            if (!same) {
                snprintf(why, sizeof why, "the memory layout differs (%s)",
                         r->path);
                return why;
            }
        }
    }
    if (!found) return "the memory layout differs (snapshot library)";

    /* a work area that collides with nothing, old or new */
    uint64_t wlen = WORK_HEAD + ((h.raw_len + PG - 1) & ~(PG - 1));
    uint64_t work = 0;
    for (uint64_t cand = 0x200000000000ULL; cand < 0x700000000000ULL && !work;
         cand += 0x10000000000ULL) {
        int clash = 0;
        for (uint32_t i = 0; i < h.nreg && !clash; i++)
            if (regs[i].start < cand + wlen && regs[i].end > cand) clash = 1;
        for (uint32_t j = 0; j < ncur && !clash; j++)
            if (cur[j].start < cand + wlen && cur[j].end > cand) clash = 1;
        if (clash) continue;
        void *m =
            mmap((void *)cand, wlen, PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
        if (m == (void *)cand)
            work = cand;
        else if (m != MAP_FAILED)
            munmap(m, wlen);
    }
    if (!work) return "no room for the work area";

    char *payload = (char *)(work + WORK_HEAD);
    if (decompress_into(h.comp, comp, h.comp_len, payload, h.raw_len) < 0)
        return "the image can't be decompressed";
    free(comp);

    struct plan *pl = (struct plan *)work;
    memset(pl, 0, sizeof *pl);
    pl->h = h;
    pl->work = work;
    pl->work_len = wlen;
    pl->nreg = h.nreg;
    pl->ncur = ncur;
    char *w = (char *)work + sizeof *pl;
    pl->regs = (struct img_reg *)w;
    memcpy(w, regs, rl);
    w += rl;
    pl->cur = (struct cur_map *)w;
    memcpy(w, cur, ncur * sizeof *cur);
    w += ncur * sizeof *cur;
    if ((uint64_t)(w - (char *)work) > WORK_HEAD / 2)
        return "the image is too complex";
    pl->payload = payload;
    /* the work area itself must survive phase 2 */
    for (uint32_t j = 0; j < ncur; j++)
        if (pl->cur[j].start >= work && pl->cur[j].end <= work + wlen)
            pl->cur[j].keep = 1;

    /* switch to a stack inside the work area and never come back */
    uint64_t top = (work + WORK_HEAD - 64) & ~15ULL;
    __asm__ volatile("movq %0, %%rsp\n\t"
                     "movq %1, %%rdi\n\t"
                     "callq *%2\n\t"
                     :
                     : "r"(top), "r"(pl), "r"(&restore_phase2)
                     : "memory");
    __builtin_unreachable();
}

/* Remove this library from $LD_PRELOAD (tenkana puts it first), in place. */
static void unpreload(void) {
    char *v = getenv("LD_PRELOAD");
    Dl_info info;
    if (!v || !dladdr((void *)&unpreload, &info) || !info.dli_fname) return;
    size_t n = strlen(info.dli_fname);
    if (strncmp(v, info.dli_fname, n) != 0 || (v[n] && v[n] != ':')) return;
    if (!v[n]) {
        unsetenv("LD_PRELOAD");
        return;
    }
    memmove(v, v + n + 1, strlen(v + n + 1) + 1);
}

static void keep(char *dst, size_t n, const char *name) {
    const char *v = getenv(name);
    snprintf(dst, n, "%s", v ? v : "");
}

/* Before the engine's main(): take tenkana's settings, and if $TENKANA_RESTORE
   names an image, become it. */
__attribute__((constructor)) static void aint_init(void) {
    keep(g_ctl, sizeof g_ctl, "TENKANA_CTL");
    keep(g_main, sizeof g_main, "TENKANA_MAIN");
    keep(g_sub, sizeof g_sub, "TENKANA_MAIN_SUB");
    char path[1024];
    keep(path, sizeof path, "TENKANA_RESTORE");
    unsetenv("TENKANA_CTL");
    unsetenv("TENKANA_MAIN");
    unsetenv("TENKANA_MAIN_SUB");
    unsetenv("TENKANA_RESTORE");
    if (g_ctl[0]) unpreload();
    if (path[0] != '/') return;
    for (size_t n = strlen(path); n && path[n - 1] == ' '; n--)
        path[n - 1] = 0;
    if (!real_fopen) real_fopen = (fopen_t)dlsym(RTLD_NEXT, "fopen");
    if (!real_fclose) real_fclose = (fclose_t)dlsym(RTLD_NEXT, "fclose");
    const char *why = restore_image(path);
    char res[1100];
    snprintf(res, sizeof res, "%s.result", path);
    int fd = open(res, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
    if (fd >= 0) {
        ssize_t w = write(fd, why, strlen(why));
        (void)w;
        close(fd);
    }
    _exit(75);
}
