Files
DroidDeck/tools/tests/test_zram_spill_preload.py
T

276 lines
9.2 KiB
Python

import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#define THREADS 4
struct shared {
volatile long progress;
volatile long errors;
volatile int stop;
volatile int quiet; // readers leave the blocks alone (a page-out they would undo is being measured)
volatile int quieted; // readers that have stopped reading
};
static const char *ctl;
static size_t size;
static int block_urg;
static struct shared *shared;
static unsigned char *blocks[THREADS];
static void fill(unsigned char *p, size_t n, unsigned seed) {
for (size_t i = 0; i < n; i++) p[i] = (unsigned char)((i * 2654435761u + seed) >> 7);
}
static int same(const unsigned char *p, size_t n, unsigned seed) {
for (size_t i = 0; i < n; i += 61)
if (p[i] != (unsigned char)((i * 2654435761u + seed) >> 7)) return 0;
return 1;
}
static void *work(void *arg) {
long id = (long)arg;
if (block_urg && id == 0) {
sigset_t set;
sigfillset(&set);
pthread_sigmask(SIG_BLOCK, &set, NULL);
}
unsigned seed = (unsigned)id * 77u + 1u;
int idle = 0;
while (!shared->stop) {
if (shared->quiet) {
if (!idle) {
idle = 1;
__atomic_add_fetch(&shared->quieted, 1, __ATOMIC_RELEASE);
}
continue;
}
if (idle) {
idle = 0;
__atomic_sub_fetch(&shared->quieted, 1, __ATOMIC_RELEASE);
}
if (!same(blocks[id], size, seed)) __atomic_add_fetch(&shared->errors, 1, __ATOMIC_RELAXED);
__atomic_add_fetch(&shared->progress, 1, __ATOMIC_RELAXED);
}
return NULL;
}
static void put(const char *suffix, const char *text) {
char path[512];
snprintf(path, sizeof(path), "%s%s", ctl, suffix);
FILE *f = fopen(path, "w");
if (!f) exit(20);
fputs(text, f);
fclose(f);
}
static long get(const char *suffix, pid_t pid) {
char path[512], text[32] = {0};
snprintf(path, sizeof(path), "%s%s%d", ctl, suffix, pid);
FILE *f = fopen(path, "r");
if (!f) return -2;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
return n == 0 ? -1 : atol(text);
}
static long rss_kb(pid_t pid) {
char path[64], line[256];
long kb = -1;
snprintf(path, sizeof(path), "/proc/%d/status", pid);
FILE *f = fopen(path, "r");
while (f && fgets(line, sizeof(line), f))
if (!strncmp(line, "VmRSS:", 6)) kb = atol(line + 6);
if (f) fclose(f);
return kb;
}
static void nap(long ms) {
struct timespec t = {ms / 1000, ms % 1000 * 1000000};
nanosleep(&t, NULL);
}
static long wait_for(const char *suffix, pid_t pid, long ms) {
for (long waited = 0; waited < ms; waited += 20) {
long v = get(suffix, pid);
if (v >= 0) return v;
nap(20);
}
return -3;
}
int main(int argc, char **argv) {
if (argc > 1 && !strcmp(argv[1], "probe")) {
// whether a child may seize its parent, as the spill helper does (Yama's ptrace_scope 1 refuses)
pid_t parent = getpid(), probe = fork();
if (probe == 0) _exit(ptrace(PTRACE_SEIZE, parent, 0, 0) == 0 ? 0 : 1);
int status = 0;
waitpid(probe, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
}
if (argc > 1 && !strcmp(argv[1], "pageout")) {
// whether this host pages anonymous memory out at all (swap, and a kernel that is not emulated)
size_t n = 64u << 20;
unsigned char *p = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) return 1;
fill(p, n, 3);
long before = rss_kb(getpid());
madvise(p, n, 21 /* MADV_PAGEOUT */);
return rss_kb(getpid()) < before - 32 * 1024 ? 0 : 1;
}
ctl = argv[1];
size = (size_t)atol(argv[2]) << 20;
block_urg = argc > 3 && !strcmp(argv[3], "block");
int undumpable = argc > 3 && !strcmp(argv[3], "undumpable");
if (undumpable) prctl(PR_SET_DUMPABLE, 0);
shared = mmap(NULL, sizeof(*shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (shared == MAP_FAILED) return 2;
char resume[512];
snprintf(resume, sizeof(resume), "%s.resume", ctl);
unlink(resume);
put(".hold", "");
pid_t child = fork();
if (child == 0) {
// the blocks are the child's alone: a page-out skips pages another process still maps
for (int i = 0; i < THREADS; i++) {
blocks[i] = i % 2 ? malloc(size) : mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (!blocks[i] || blocks[i] == MAP_FAILED) _exit(3);
fill(blocks[i], size, (unsigned)i * 77u + 1u);
}
if (mprotect(blocks[2], size, PROT_READ) != 0) _exit(4);
pthread_t t[THREADS];
for (long i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, work, (void *)i);
for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
_exit(0);
}
while (shared->progress < 50) nap(10);
long before = rss_kb(child);
if (undumpable) {
shared->quiet = 1;
for (int waited = 0; __atomic_load_n(&shared->quieted, __ATOMIC_ACQUIRE) < THREADS && waited < 5000; waited += 1) nap(1);
if (__atomic_load_n(&shared->quieted, __ATOMIC_ACQUIRE) < THREADS) {
// a reader still scanning would fault pages back in before the resident set is measured
shared->stop = 1;
kill(child, SIGKILL);
waitpid(child, NULL, 0);
return 5;
}
}
put(".hold", "4 0");
kill(child, SIGURG);
long spilled = wait_for(".ack.", child, 20000);
long after = rss_kb(child);
shared->quiet = 0;
long frozen_at = shared->progress;
nap(500);
long frozen_now = shared->progress;
put(".resume", "1");
long restored = spilled > 0 ? wait_for(".restored.", child, 20000) : 0;
for (int waited = 0; shared->progress == frozen_now && waited < 10000; waited += 10) nap(10);
long resumed = shared->progress;
long back = rss_kb(child);
shared->stop = 1;
int status = 0;
waitpid(child, &status, 0);
printf("before=%ld after=%ld back=%ld spilled=%ld restored=%ld frozen=%ld resumed=%ld errors=%ld exit=%d\n",
before, after, back, spilled, restored, frozen_now - frozen_at, resumed - frozen_now, shared->errors,
WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status));
return 0;
}
"""
def _fields(text):
return {k: int(v) for k, v in (part.split("=") for part in text.split())}
@unittest.skipUnless(platform.machine() == "aarch64" and shutil.which("cc"), "the spill runs only on arm64")
class ZramSpillPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
cls.ctl = cls.dir / "ctl"
lib = cls.dir / "libzram.so"
prog = cls.dir / "spill"
(cls.dir / "spill.c").write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-shared", "-fPIC", f'-DZR_CTL="{cls.ctl}"', "-o", str(lib),
str(PRELOAD / "zram.c")], check=True)
subprocess.run(["cc", "-O2", "-pthread", "-o", str(prog), str(cls.dir / "spill.c")], check=True)
cls.lib, cls.prog = lib, prog
cls.can_trace = subprocess.run([str(prog), "probe"]).returncode == 0
cls.can_page_out = subprocess.run([str(prog), "pageout"]).returncode == 0
def need_tracing(self):
if not self.can_trace:
self.skipTest("this host does not let a child seize its parent (Yama ptrace_scope)")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, ignore_errors=True)
def run_spill(self, *extra):
self.ctl.write_text("0")
env = dict(os.environ, LD_PRELOAD=str(self.lib))
env.pop("DDNATV_ROOT", None)
out = subprocess.run([str(self.prog), str(self.ctl), "64", *extra], env=env, check=True,
capture_output=True, text=True, timeout=90).stdout
return _fields(out)
def test_spills_to_disk_holds_every_thread_and_restores_intact(self):
self.need_tracing()
r = self.run_spill()
self.assertEqual(r["exit"], 0)
self.assertGreater(r["spilled"], 200 * 1024)
self.assertLess(r["after"], r["before"] - 200 * 1024)
self.assertEqual(r["frozen"], 0)
self.assertGreaterEqual(r["restored"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_a_thread_that_blocks_every_signal_is_held_too(self):
self.need_tracing()
r = self.run_spill("block")
self.assertEqual(r["exit"], 0)
self.assertGreater(r["spilled"], 200 * 1024)
self.assertEqual(r["frozen"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_a_process_that_cannot_be_traced_falls_back_to_zram(self):
r = self.run_spill("undumpable")
self.assertEqual(r["exit"], 0)
self.assertEqual(r["spilled"], 0)
# the fallback pages out to zram before it answers: where the host can page out, the resident set
# has shrunk by then
if self.can_page_out:
self.assertLess(r["after"], r["before"] - 64 * 1024)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
if __name__ == "__main__":
unittest.main()