Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(native): a packaged game leaves a record its player can send

yhh424e9a845f49
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index 444a98d5c..1e16cedab 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -230,6 +230,7 @@ if(ESTELLA_QUICKJS_DIR)
set(HOST_SOURCES
host/Host.cpp
host/Runtime.cpp
+ host/BootLog.cpp
host/EsnShim.cpp
host/bindings/HeapBindings.cpp
host/bindings/EcsBindings.cpp
diff --git a/native/host/BootLog.cpp b/native/host/BootLog.cpp
new file mode 100644
index 000000000..1a332bc41
--- /dev/null
+++ b/native/host/BootLog.cpp
@@ -0,0 +1,203 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+
+#include "BootLog.hpp"
+
+#include <cstdarg>
+#include <cstdio>
+#include <cstring>
+#include <ctime>
+#include <string>
+
+#include <csignal>
+#include <dlfcn.h>
+#include <unistd.h>
+#include <unwind.h>
+
+namespace eshost {
+namespace {
+
+FILE* g_file = nullptr;
+std::string g_path;
+const char* g_phase = "(none)";
+/// The same file, as a descriptor — what the signal handler is allowed to use.
+int g_fd = -1;
+
+/** Wall-clock, ISO-ish. The record is read by a person comparing it against
+ * "it broke this afternoon", so it wants the clock, not the monotonic timer. */
+std::string stamp() {
+ std::time_t t = std::time(nullptr);
+ std::tm tm{};
+#if defined(_WIN32)
+ localtime_s(&tm, &t);
+#else
+ localtime_r(&t, &tm);
+#endif
+ char buf[32];
+ std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm);
+ return buf;
+}
+
+void writeLine(const char* prefix, const char* text) {
+ if (!g_file) return;
+ std::fprintf(g_file, "%s%s\n", prefix, text);
+ // Flushed per line, not per buffer: a launch that is about to die is exactly
+ // the one whose last line matters, and a buffered line is one the crash eats.
+ std::fflush(g_file);
+}
+
+} // namespace
+
+void openBootLog(const std::string& dir) {
+ if (dir.empty()) return;
+
+ g_path = dir + "/estella-boot.log";
+ const std::string prev = dir + "/estella-boot.prev.log";
+ std::remove(prev.c_str());
+ std::rename(g_path.c_str(), prev.c_str());
+
+ g_file = std::fopen(g_path.c_str(), "w");
+ if (!g_file) { g_path.clear(); return; }
+ g_fd = fileno(g_file);
+
+ std::fprintf(g_file, "estella boot record — %s\n", stamp().c_str());
+ std::fflush(g_file);
+}
+
+void bootPhase(const char* name) {
+ g_phase = name ? name : "(none)";
+ writeLine("phase: ", g_phase);
+}
+
+void bootNote(const char* fmt, ...) {
+ char buf[1024];
+ va_list args;
+ va_start(args, fmt);
+ std::vsnprintf(buf, sizeof(buf), fmt, args);
+ va_end(args);
+ writeLine("", buf);
+}
+
+void bootReady(double ms) {
+ char buf[128];
+ std::snprintf(buf, sizeof(buf), "ready in %.0f ms", ms);
+ writeLine("", buf);
+}
+
+void bootLogLine(bool error, const char* message) {
+ if (!g_file || !message) return;
+ // Errors carry the phase they happened in: the file is read top-down by
+ // someone who wants to know where it stopped, and an error that names its own
+ // phase answers that without counting lines.
+ if (error) {
+ std::fprintf(g_file, "ERROR [%s] %s\n", g_phase, message);
+ } else {
+ std::fprintf(g_file, " %s\n", message);
+ }
+ std::fflush(g_file);
+}
+
+const std::string& bootLogPath() { return g_path; }
+
+// =============================================================================
+// The crash handler
+// =============================================================================
+
+namespace {
+
+/** write(2) a NUL-terminated string. The only output primitive a signal handler
+ * is allowed; a partial write is retried because a signal can interrupt one. */
+void rawWrite(const char* s) {
+ if (g_fd < 0 || !s) return;
+ size_t n = std::strlen(s);
+ while (n > 0) {
+ const ssize_t got = write(g_fd, s, n);
+ if (got <= 0) return;
+ s += got;
+ n -= (size_t)got;
+ }
+}
+
+/** An unsigned value in hex, without printf. */
+void rawHex(uintptr_t v) {
+ char buf[2 + sizeof(uintptr_t) * 2 + 1];
+ char* p = buf + sizeof(buf) - 1;
+ *p = '\0';
+ do { *--p = "0123456789abcdef"[v & 0xf]; v >>= 4; } while (v);
+ *--p = 'x';
+ *--p = '0';
+ rawWrite(p);
+}
+
+struct Frames {
+ static constexpr int kMax = 32;
+ void* pc[kMax];
+ int n = 0;
+};
+
+_Unwind_Reason_Code collectFrame(_Unwind_Context* ctx, void* arg) {
+ auto* f = static_cast<Frames*>(arg);
+ const uintptr_t ip = _Unwind_GetIP(ctx);
+ if (ip && f->n < Frames::kMax) f->pc[f->n++] = reinterpret_cast<void*>(ip);
+ return f->n >= Frames::kMax ? _URC_END_OF_STACK : _URC_NO_REASON;
+}
+
+const char* signalName(int sig) {
+ switch (sig) {
+ case SIGSEGV: return "SIGSEGV (bad memory access)";
+ case SIGABRT: return "SIGABRT (abort — an assert or an uncaught throw)";
+ case SIGBUS: return "SIGBUS (misaligned or unmapped access)";
+ case SIGFPE: return "SIGFPE (arithmetic)";
+ case SIGILL: return "SIGILL (illegal instruction)";
+ default: return "signal";
+ }
+}
+
+void onFatalSignal(int sig, siginfo_t*, void*) {
+ rawWrite("\nFATAL ");
+ rawWrite(signalName(sig));
+ rawWrite(" during phase: ");
+ rawWrite(g_phase);
+ rawWrite("\nbacktrace (symbolize against this version's unstripped libestella_js_host.so):\n");
+
+ Frames frames;
+ _Unwind_Backtrace(collectFrame, &frames);
+ for (int i = 0; i < frames.n; i++) {
+ rawWrite(" ");
+ rawHex(reinterpret_cast<uintptr_t>(frames.pc[i]));
+ // dladdr is not formally async-signal-safe, but it is what every Android
+ // crash reporter uses here, and a frame with a library and an offset is
+ // the difference between a number and an address someone can look up.
+ Dl_info info;
+ if (dladdr(frames.pc[i], &info) && info.dli_fname) {
+ rawWrite(" ");
+ rawWrite(info.dli_fname);
+ if (info.dli_fbase) {
+ rawWrite("+");
+ rawHex(reinterpret_cast<uintptr_t>(frames.pc[i])
+ - reinterpret_cast<uintptr_t>(info.dli_fbase));
+ }
+ if (info.dli_sname) { rawWrite(" "); rawWrite(info.dli_sname); }
+ }
+ rawWrite("\n");
+ }
+ fsync(g_fd);
+
+ // Die the way we would have: the OS still writes its tombstone, and the
+ // process still reports the same signal to whatever is watching.
+ signal(sig, SIG_DFL);
+ raise(sig);
+}
+
+} // namespace
+
+void installCrashHandler() {
+ if (g_fd < 0) return; // nowhere to write — nothing to install
+ struct sigaction sa = {};
+ sa.sa_sigaction = onFatalSignal;
+ sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
+ sigemptyset(&sa.sa_mask);
+ for (int sig : {SIGSEGV, SIGABRT, SIGBUS, SIGFPE, SIGILL}) sigaction(sig, &sa, nullptr);
+}
+
+} // namespace eshost
diff --git a/native/host/BootLog.hpp b/native/host/BootLog.hpp
new file mode 100644
index 000000000..a14ab25bf
--- /dev/null
+++ b/native/host/BootLog.hpp
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The boot record — what a packaged game leaves behind about how it started.
+//
+// Everything this host reports goes to the platform log, which means logcat,
+// which means a cable and a developer. So when a player says a game closed
+// itself, the evidence is on their phone and unreachable, and the only way to
+// learn anything is to reproduce it on a device you own — which is exactly what
+// you cannot do when the difference is their GPU, their driver, or a build they
+// installed and you did not.
+//
+// This writes the same lines to a file under Platform::logDir(), which a file
+// manager can open and a person can send. It records what a failed launch needs
+// to be diagnosed FROM THE FILE: what was running, on what, how far it got, and
+// what the last error was.
+//
+// The previous run is kept alongside. An app that dies and is opened again would
+// otherwise overwrite the only record of the death with a record of the retry.
+
+#pragma once
+
+#include <string>
+
+namespace eshost {
+
+/**
+ * Begin this launch's record in @p dir, moving the previous one aside.
+ *
+ * Takes the directory rather than the Platform that knows it: this file has no
+ * business knowing what a platform is, and a record that depends on nothing can
+ * be exercised on its own — which for a crash handler is the difference between
+ * a tested one and a hoped-for one.
+ *
+ * Safe to call before anything else works. An empty @p dir records nothing, and
+ * every other entry point stays valid.
+ */
+void openBootLog(const std::string& dir);
+
+/**
+ * Enter a named boot phase.
+ *
+ * The last phase in the file is where a launch that never finished stopped,
+ * which is the one thing a black screen cannot tell you by itself.
+ */
+void bootPhase(const char* name);
+
+/** Record a fact about this launch (printf-shaped) — a decision worth reading
+ * later, like which source the SDK bundle came from. */
+void bootNote(const char* fmt, ...);
+
+/** Mark the launch as fully up. Its absence in a file is what says the game
+ * never got there. */
+void bootReady(double ms);
+
+/** Append one already-formatted log line. Called by hostLog, so the record and
+ * the platform log never disagree about what happened. */
+void bootLogLine(bool error, const char* message);
+
+/** Where the record is being written, for the one log line that tells a
+ * developer to ask for it. Empty when there is none. */
+const std::string& bootLogPath();
+
+/**
+ * Catch the signals that end a process, and write what happened into the record
+ * before letting it die.
+ *
+ * Without this a native crash leaves a file that simply stops — the last phase
+ * is a hint, and a hint is all. The OS writes a tombstone with the real stack,
+ * but a tombstone lives in a directory a player cannot read and is gone by the
+ * time anyone asks. This puts the signal, the phase it happened in, and the
+ * return addresses next to everything else in the one file they can send; the
+ * addresses symbolize offline against the unstripped `libestella_js_host.so`
+ * for that version.
+ *
+ * The handler is written to the rules signal handlers actually have: a raw
+ * write(2) to a file descriptor opened up front, no allocation, no stdio. Then
+ * it restores the default handler and re-raises, so the OS still produces its
+ * own report and the process still dies the way it would have.
+ */
+void installCrashHandler();
+
+} // namespace eshost
diff --git a/native/host/Host.cpp b/native/host/Host.cpp
index 083dcf8a3..e735f39bd 100644
--- a/native/host/Host.cpp
+++ b/native/host/Host.cpp
@@ -18,6 +18,7 @@
* Licensed under the Apache License, Version 2.0.
*/
#include "Bindings.hpp"
+#include "BootLog.hpp"
#include "esengine/bindings/ActiveContext.hpp" // g_activeContext — the context the generated bindings act on
#include "esengine/core/Log.hpp"
@@ -67,6 +68,16 @@ void fallbackFrame(HostState& h) {
rf.end();
}
+/** One cleared frame, presented — the host's own colour, since the game's lives
+ * on a Canvas that does not exist yet. */
+void paintBootFrame(HostState& h) {
+ if (!h.gfx || !h.ctx) return;
+ auto& rf = h.ctx->require<RenderFrame>();
+ rf.begin(glm::ortho(0.0f, h.w, 0.0f, h.h), 0, RenderFrame::PassClear{true, true, kFallbackClear});
+ rf.end();
+ h.gfx->present();
+}
+
/** Ask Dawn for an adapter and a device on the platform's backend, enabling the
* block-compression families this adapter supports (a device rejects a format it
* did not opt into, even when the adapter advertises it). */
@@ -115,6 +126,26 @@ bool createDevice(HostState& h) {
return true;
}
+/**
+ * Record which GPU this is.
+ *
+ * The first question about a failure that happens on someone else's phone and
+ * not on yours, and the one a log without it cannot answer. Dawn knows it as
+ * soon as the adapter exists.
+ */
+void logAdapter(HostState& h) {
+ if (!h.adapter) return;
+ WGPUAdapterInfo info = {};
+ if (wgpuAdapterGetInfo(h.adapter, &info) != WGPUStatus_Success) return;
+ auto str = [](const WGPUStringView& v) {
+ return v.data ? std::string(v.data, v.length == WGPU_STRLEN ? strlen(v.data) : v.length)
+ : std::string();
+ };
+ bootNote("gpu: %s %s (%s) — %s", str(info.vendor).c_str(), str(info.device).c_str(),
+ str(info.architecture).c_str(), str(info.description).c_str());
+ wgpuAdapterInfoFreeMembers(info);
+}
+
} // namespace
bool bindSurface() {
@@ -156,11 +187,21 @@ bool boot(Platform& platform) {
hostLog(entry.level >= esengine::LogLevel::Error, "[engine] %s", entry.message.c_str());
});
+ // Opened before anything can fail, so a launch that dies in the GPU bring-up
+ // still leaves a file saying so. Every ESHOST_LOG from here on lands in it.
+ openBootLog(platform.logDir());
+ installCrashHandler();
+ bootNote("device: %s", platform.describe().c_str());
+ if (!bootLogPath().empty()) ESHOST_LOGI("boot record: %s", bootLogPath().c_str());
+
const double t0 = nowMs();
+ bootPhase("gpu device");
if (!createDevice(h)) return false;
+ logAdapter(h);
auto device = makeUnique<WebGPUDevice>(h.device, h.instance, h.adapter);
h.gfx = device.get();
+ bootPhase("surface");
if (!bindSurface()) return false;
static EstellaContext context;
@@ -172,6 +213,7 @@ bool boot(Platform& platform) {
g_activeContext = &context;
context.state().viewport_width = (i32)h.w;
context.state().viewport_height = (i32)h.h;
+ bootPhase("engine context");
if (!context.init(std::move(device))) { ESHOST_LOGE("context.init failed"); return false; }
static ecs::Registry registry;
@@ -179,9 +221,19 @@ bool boot(Platform& platform) {
ESHOST_LOGI("boot ms — Dawn instance/adapter/device + EstellaContext: %.0f", nowMs() - t0);
ESHOST_LOGI("audio: %s", h.audio.init() ? "native engine up (miniaudio)" : "no device — silent");
+ // Paint the surface before the slow part. Until the game's first frame the
+ // window holds whatever was there — black — which is also what a process that
+ // died leaves behind; they are the same picture for as long as boot takes, and
+ // on a first launch that has to compile the SDK bundle that is seconds. One
+ // filled frame is the difference between "starting" and "gone".
+ paintBootFrame(h);
+
+ bootPhase("js runtime");
initRuntime(h);
+ bootPhase("game script");
if (!runPackagedGame(h)) return false;
h.ready = true;
+ bootReady(nowMs() - t0);
ESHOST_LOGI("real SDK up (%dx%d) — esengine World over native Dawn", (int)h.w, (int)h.h);
return true;
}
diff --git a/native/host/Host.hpp b/native/host/Host.hpp
index 82103f74e..2582d907d 100644
--- a/native/host/Host.hpp
+++ b/native/host/Host.hpp
@@ -96,6 +96,22 @@ struct Platform {
/** Writable private directory for the SDK bytecode cache; empty disables it. */
virtual std::string cacheDir() = 0;
+ /**
+ * Writable directory a PLAYER can reach — where the boot record goes.
+ *
+ * Distinct from {@link cacheDir}, which is private to the app and reachable
+ * only over adb or a rooted phone. When a packaged game fails on someone
+ * else's device, the only evidence that can travel back is a file they can
+ * find: `Android/data/<pkg>/files` on Android, Documents on iOS. Empty turns
+ * the record off, and a platform that returns empty is choosing to make its
+ * failures unreportable.
+ */
+ virtual std::string logDir() = 0;
+
+ /** This device, in one line: model, OS version, ABI. The first thing asked
+ * about a failure that happens on someone else's phone and not on yours. */
+ virtual std::string describe() = 0;
+
/** The backend Dawn must pick: Vulkan on Android, Metal on iOS. */
virtual WGPUBackendType backend() const = 0;
diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cpp
index 8dead325c..e69a2c4d9 100644
--- a/native/host/Runtime.cpp
+++ b/native/host/Runtime.cpp
@@ -21,6 +21,7 @@
* Licensed under the Apache License, Version 2.0.
*/
#include "Bindings.hpp"
+#include "BootLog.hpp"
#include "esn_shim.hpp" // esn_register / esn_register_functions
#include "esengine_bundle.h" // the real SDK, bundled: installs globalThis.ESEngine
@@ -60,6 +61,9 @@ void hostLog(bool error, const char* fmt, ...) {
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
if (g_host && g_host->platform) g_host->platform->log(error, buf);
+ // …and into the boot record, so what a developer reads over a cable and what
+ // a player can send are the same lines.
+ bootLogLine(error, buf);
}
double nowMs() {
@@ -235,6 +239,7 @@ bool tryBytecode(HostState& h, const u8* blob, size_t size, uint64_t want,
return false;
}
ESHOST_LOGI("SDK bundle: loaded from %s", origin);
+ bootNote("bundle: %s", origin);
out = JS_EvalFunction(h.js, fn);
return true;
}
@@ -286,6 +291,10 @@ JSValue evalCachedScript(HostState& h, const char* src, size_t srcLen, const cha
}
// Parse once (slow), cache the bytecode, run.
+ // No bytecode from either source: this launch pays the parse. Said plainly,
+ // because it is seconds of black screen and the question it raises ("did it
+ // crash?") is the one the record exists to answer.
+ bootNote("bundle: NO bytecode — parsing on device, expect a slow first launch");
JSValue fn = JS_Eval(h.js, src, srcLen, filename, JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
if (JS_IsException(fn)) return fn;
if (!cachePath.empty()) {
diff --git a/native/host/platform/android.cpp b/native/host/platform/android.cpp
index 4fdb1bb10..95f2f0c84 100644
--- a/native/host/platform/android.cpp
+++ b/native/host/platform/android.cpp
@@ -15,6 +15,7 @@
*/
#include <android_native_app_glue.h>
#include <android/log.h>
+#include <sys/system_properties.h>
#include <android/input.h>
#include <android/asset_manager.h>
#include <android/font.h>
@@ -146,6 +147,7 @@ struct AndroidPlatform final : eshost::Platform {
ANativeWindow* window = nullptr;
JavaVM* vm = nullptr; // for JNI HttpURLConnection off-thread
std::string cache; // app private dir — SDK bytecode cache
+ std::string logs; // Android/data/<pkg>/files — a player can open this
// Read an APK asset (assets/<path>) fully into a buffer; empty if missing.
std::vector<u8> readAsset(const char* path) override {
@@ -164,6 +166,18 @@ struct AndroidPlatform final : eshost::Platform {
std::string cacheDir() override { return cache; }
+ std::string logDir() override { return logs; }
+
+ /** Model, Android release and ABI, from the system properties every device
+ * answers — no JNI round trip, so this works before anything else is up. */
+ std::string describe() override {
+ char model[PROP_VALUE_MAX] = {0}, release[PROP_VALUE_MAX] = {0}, abi[PROP_VALUE_MAX] = {0};
+ __system_property_get("ro.product.model", model);
+ __system_property_get("ro.build.version.release", release);
+ __system_property_get("ro.product.cpu.abi", abi);
+ return std::string(model) + ", Android " + release + ", " + abi;
+ }
+
WGPUBackendType backend() const override { return WGPUBackendType_Vulkan; }
WebGPUDevice::NativeSurface surface() override {
@@ -739,6 +753,8 @@ void android_main(android_app* app) {
// es_textEditor_* entry points are bound at all.
attachTextEditor(app->activity);
if (app->activity->internalDataPath) g_platform.cache = app->activity->internalDataPath;
+ // The boot record goes where a person can reach it without a cable.
+ if (app->activity->externalDataPath) g_platform.logs = app->activity->externalDataPath;
app->onAppCmd = onAppCmd;
app->onInputEvent = onInput;
// Chained, not replaced: the glue's handler is what wakes the frame loop on
diff --git a/native/host/platform/ios.mm b/native/host/platform/ios.mm
index 1d7e46245..4a3d1667c 100644
--- a/native/host/platform/ios.mm
+++ b/native/host/platform/ios.mm
@@ -98,6 +98,21 @@ struct IOSPlatform final : eshost::Platform {
return std::string([dirs[0] UTF8String]);
}
+ /** Documents, not Caches: the record exists to be sent, and Documents is the
+ * directory the Files app shows (with UIFileSharingEnabled) and iTunes/Finder
+ * can copy off a device that has none. */
+ std::string logDir() override {
+ NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
+ if (dirs.count == 0) return {};
+ return std::string([dirs[0] UTF8String]);
+ }
+
+ std::string describe() override {
+ UIDevice* d = [UIDevice currentDevice];
+ return std::string([[d model] UTF8String]) + ", iOS "
+ + std::string([[d systemVersion] UTF8String]) + ", arm64";
+ }
+
WGPUBackendType backend() const override { return WGPUBackendType_Metal; }
WebGPUDevice::NativeSurface surface() override {
diff --git a/native/tools/bootlog_crash_test.cpp b/native/tools/bootlog_crash_test.cpp
new file mode 100644
index 000000000..bb6a582d0
--- /dev/null
+++ b/native/tools/bootlog_crash_test.cpp
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Does the boot record survive the thing it exists for?
+//
+// A crash handler that has never handled a crash is a comment. This runs the
+// real BootLog.cpp on a real device, faults for real, and leaves the file behind
+// for the caller to read — so the claim "a player can send us the crash" is
+// something that was observed rather than intended.
+//
+// Built and run by tools/verify-bootlog-crash.mjs; not part of the host.
+//
+// bootlog_crash_test <dir> [--no-crash]
+
+#include "../host/BootLog.hpp"
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+
+int main(int argc, char** argv) {
+ if (argc < 2) {
+ std::fprintf(stderr, "usage: bootlog_crash_test <dir> [--no-crash]\n");
+ return 2;
+ }
+ const bool crash = !(argc > 2 && std::strcmp(argv[2], "--no-crash") == 0);
+
+ eshost::openBootLog(argv[1]);
+ if (eshost::bootLogPath().empty()) {
+ std::fprintf(stderr, "no record opened in %s\n", argv[1]);
+ return 3;
+ }
+ eshost::installCrashHandler();
+
+ eshost::bootPhase("gpu device");
+ eshost::bootNote("device: a test, not a phone");
+ eshost::bootPhase("engine context");
+ eshost::bootLogLine(false, "a line the host would have logged");
+ eshost::bootPhase("js runtime");
+
+ if (!crash) {
+ eshost::bootReady(1.0);
+ std::printf("%s\n", eshost::bootLogPath().c_str());
+ return 0;
+ }
+
+ // The point. Volatile so it survives the optimizer, and a null store rather
+ // than abort() because a bad pointer is what actually happens in the field.
+ std::printf("%s\n", eshost::bootLogPath().c_str());
+ std::fflush(stdout);
+ *static_cast<volatile int*>(nullptr) = 1;
+ return 0; // not reached
+}
diff --git a/tools/verify-bootlog-crash.mjs b/tools/verify-bootlog-crash.mjs
new file mode 100644
index 000000000..a19a65a2a
--- /dev/null
+++ b/tools/verify-bootlog-crash.mjs
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Prove the boot record survives a crash, on a device.
+//
+// The record exists so that a game that dies on someone else's phone leaves
+// something they can send. That claim is only worth making if the handler has
+// been watched doing it: this builds the real BootLog.cpp for arm64 with the
+// NDK, pushes it, faults on purpose, and reads the file back.
+//
+// node tools/verify-bootlog-crash.mjs (needs an adb device + NDK)
+//
+// Skips with a message when there is no device or no NDK, so it can be run
+// anywhere without pretending to have checked something it did not.
+
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, readdirSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const OUT = path.join(ROOT, 'build', 'bootlog-crash');
+const DEVICE_DIR = '/data/local/tmp/estella-bootlog';
+
+function sdkRoot() {
+ return process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT
+ || path.join(process.env.LOCALAPPDATA || process.env.HOME || '', 'Android', 'Sdk');
+}
+
+function adbPath() {
+ const exe = process.platform === 'win32' ? 'adb.exe' : 'adb';
+ const inSdk = path.join(sdkRoot(), 'platform-tools', exe);
+ return existsSync(inSdk) ? inSdk : exe;
+}
+
+function ndkClang() {
+ const ndkRoot = process.env.ANDROID_NDK_HOME
+ || (() => {
+ const dir = path.join(sdkRoot(), 'ndk');
+ if (!existsSync(dir)) return null;
+ const versions = readdirSync(dir).sort();
+ return versions.length ? path.join(dir, versions[versions.length - 1]) : null;
+ })();
+ if (!ndkRoot) return null;
+ const host = process.platform === 'win32' ? 'windows-x86_64'
+ : process.platform === 'darwin' ? 'darwin-x86_64' : 'linux-x86_64';
+ const exe = process.platform === 'win32' ? '.cmd' : '';
+ const clang = path.join(ndkRoot, 'toolchains', 'llvm', 'prebuilt', host, 'bin', `aarch64-linux-android33-clang++${exe}`);
+ return existsSync(clang) ? clang : null;
+}
+
+function device(adb) {
+ try {
+ const out = execFileSync(adb, ['devices'], { encoding: 'utf8' });
+ return out.split('\n').slice(1).some((l) => /\tdevice\s*$/.test(l.trim() + ' ') || /\tdevice/.test(l));
+ } catch {
+ return false;
+ }
+}
+
+const adb = adbPath();
+const clang = ndkClang();
+if (!clang) {
+ console.log('verify-bootlog-crash: SKIP — no Android NDK found');
+ process.exit(0);
+}
+if (!device(adb)) {
+ console.log('verify-bootlog-crash: SKIP — no adb device attached');
+ process.exit(0);
+}
+
+mkdirSync(OUT, { recursive: true });
+const bin = path.join(OUT, 'bootlog_crash_test');
+console.log('building the record + handler for arm64…');
+// `shell: true` because the NDK's Windows driver is a .cmd, which node refuses
+// to spawn directly (EINVAL) — the same reason every Windows toolchain wrapper
+// has to be invoked through a shell.
+execFileSync(clang, [
+ '-std=c++17', '-O1', '-g0', '-static-libstdc++',
+ '-o', bin,
+ path.join(ROOT, 'native', 'tools', 'bootlog_crash_test.cpp'),
+ path.join(ROOT, 'native', 'host', 'BootLog.cpp'),
+], { stdio: 'inherit', shell: process.platform === 'win32' });
+
+const sh = (cmd) => execFileSync(adb, ['shell', cmd], { encoding: 'utf8' });
+sh(`rm -rf ${DEVICE_DIR}; mkdir -p ${DEVICE_DIR}`);
+execFileSync(adb, ['push', bin, `${DEVICE_DIR}/t`], { stdio: 'ignore' });
+sh(`chmod 755 ${DEVICE_DIR}/t`);
+
+console.log('crashing it on the device…');
+let exitLine = '';
+try {
+ exitLine = sh(`${DEVICE_DIR}/t ${DEVICE_DIR}; echo EXIT=$?`);
+} catch (err) {
+ exitLine = String(err.stdout ?? '');
+}
+const record = sh(`cat ${DEVICE_DIR}/estella-boot.log`);
+
+console.log('\n--- the file a player would send ---');
+console.log(record.trimEnd());
+console.log('------------------------------------\n');
+
+const problems = [];
+if (!/FATAL SIGSEGV/.test(record)) problems.push('no FATAL SIGSEGV line');
+if (!/during phase: js runtime/.test(record)) problems.push('the phase it died in was not recorded');
+if (!/backtrace/.test(record)) problems.push('no backtrace');
+if (!/libc|bootlog_crash_test|\+0x/.test(record)) problems.push('no resolved frames in the backtrace');
+if (/EXIT=0\b/.test(exitLine)) problems.push('the process did not die — the handler swallowed the signal');
+
+sh(`rm -rf ${DEVICE_DIR}`);
+
+if (problems.length) {
+ console.error('verify-bootlog-crash: FAIL');
+ for (const p of problems) console.error(` ${p}`);
+ process.exit(1);
+}
+console.log('verify-bootlog-crash: PASS — the crash reached the file, with the phase and a backtrace');