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.

fix(android): the V8 host boots on a phone, and compiled systems install there

yhhef00e2af0bb6
diff --git a/bench/aot-native/README.md b/bench/aot-native/README.md
index 5f1439dc7..ffb9afd65 100644
--- a/bench/aot-native/README.md
+++ b/bench/aot-native/README.md
@@ -64,6 +64,19 @@ by side (`BENCH_TEMPLATE` points at the QuickJS template; the desktop host runs
gets the 9.2x with no change; a compiled system still takes ~6x off the JIT's frame.
The QuickJS column is the iOS road (and macOS / Linux, which embed no V8 yet).
+On a phone (2026-11-04, Xiaomi 24129PN74C, Snapdragon 8 Elite, Android 16, arm64),
+the same project exported as APKs from each Android template. The bench switches are
+system properties there (`adb shell setprop debug.estella.bench_frames 300`, likewise
+`bench_warmup`, `bench_dt`), read before the app starts, and the bench line is in logcat:
+
+| body | build | QuickJS-ng host | V8 host |
+|---|---|---|---|
+| thin | interpreted | 63.68 ms | **13.97 ms** |
+| thin | compiled | 5.01 ms | **4.15 ms** |
+
+4.6x on the phone for a project that changes nothing. The V8 APK is 11.5 MB larger
+(44.4 vs 32.9 MB): `libv8android.so` is 15.5 MB, stored uncompressed.
+
## What was measured (2026-08-27, i5-14600K, Windows, QuickJS-ng in the native host)
5000 entities, each with `Transform` + `Sprite` + a script component, 200 timed frames
diff --git a/build-tools/tasks/nativeDeps.js b/build-tools/tasks/nativeDeps.js
index a60945e9b..20ba2976a 100644
--- a/build-tools/tasks/nativeDeps.js
+++ b/build-tools/tasks/nativeDeps.js
@@ -168,7 +168,10 @@ export async function fetchV8(platform, options = {}) {
const deps = options.depsDir || nativeDepsDir(rootDir);
const dir = path.join(deps, `v8-${platform}`);
const stamp = path.join(dir, '.estella-v8');
- const want = `${pin.version}\n${JSON.stringify(pin[platform])}`;
+ // The layout version: what this function lays out, beside what it fetched — a
+ // directory laid out by an older version of it is laid out again.
+ const LAYOUT = 2;
+ const want = `${pin.version}\n${JSON.stringify(pin[platform])}\nlayout ${LAYOUT}`;
if (existsSync(stamp) && (await readFile(stamp, 'utf8')) === want) {
logger.info(`V8 ${pin.version} (${platform}) already fetched`);
return dir;
@@ -198,10 +201,16 @@ export async function fetchV8(platform, options = {}) {
await mkdir(dir, { recursive: true });
await extract(aarFile, dir, 'zip');
await cp(path.join(dist, 'include'), path.join(dir, 'include'), { recursive: true });
+ // This build keeps its startup snapshot OUTSIDE the library: without it
+ // Isolate::New dies with "Failed to deserialize the V8 snapshot blob".
+ await cp(path.join(dist, 'snapshot_blob'), path.join(dir, 'snapshot'), { recursive: true });
}
if (!existsSync(path.join(dir, 'include', 'v8.h'))) {
throw new Error(`V8 (${platform}): the archive laid out no include/v8.h under ${dir}`);
}
+ if (platform === 'android' && !existsSync(path.join(dir, 'snapshot', 'arm64-v8a', 'snapshot_blob.bin'))) {
+ throw new Error(`V8 (android): the archive carried no startup snapshot under ${dir}/snapshot`);
+ }
await rm(scratch, { recursive: true, force: true });
await writeFile(stamp, want);
logger.success(`V8 ${pin.version} (${platform}): ${dir}`);
diff --git a/build-tools/utils/gradleProject.js b/build-tools/utils/gradleProject.js
index f37f74e82..2c16dd8fb 100644
--- a/build-tools/utils/gradleProject.js
+++ b/build-tools/utils/gradleProject.js
@@ -255,6 +255,10 @@ export async function emitAndroidGradleProject(contentDir, app, sources, icon) {
if (sources.bytecode && existsSync(sources.bytecode)) {
await cp(sources.bytecode, path.join(assetsDir, path.basename(sources.bytecode)));
}
+ // So does a V8 host's startup snapshot, without which the engine cannot start.
+ if (sources.v8Snapshots && existsSync(sources.v8Snapshots)) {
+ await cp(sources.v8Snapshots, path.join(assetsDir, 'v8'), { recursive: true });
+ }
await cp(sources.libs, path.join(mainDir, 'jniLibs'), { recursive: true });
// What the export built per ABI (the project's compiled systems), beside the template's.
diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.ts
index 099eb13d3..0b8454b07 100644
--- a/build-tools/utils/nativeTemplate.d.ts
+++ b/build-tools/utils/nativeTemplate.d.ts
@@ -51,6 +51,8 @@ export const BYTECODE_FILE: string;
export const V8_WINDOWS_RUNTIME: readonly string[];
/** The V8 an Android V8 host links, one per ABI beside the host library. */
export const V8_ANDROID_LIBRARY: string;
+/** Where an Android V8 host reads its startup snapshot from, inside the assets. */
+export function v8SnapshotAsset(abi: string): string;
/** The JS engine a template's host embeds, read off the files it carries. */
export function templateJsEngine(dir: string, platform: TemplatePlatform): 'v8' | 'quickjs';
export const ANDROID_ABIS: readonly string[];
@@ -139,6 +141,8 @@ export function androidTemplateSources(dir: string): {
icon: string;
/** Precompiled SDK bytecode, when the template's build machine could produce it. */
bytecode: string;
+ /** A V8 host's startup snapshots (assets/v8/<abi>/), absent from a QuickJS template. */
+ v8Snapshots: string;
};
export function desktopTemplateSources(dir: string, platform?: TemplatePlatform): {
diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.js
index 03bfb299b..6e1121393 100644
--- a/build-tools/utils/nativeTemplate.js
+++ b/build-tools/utils/nativeTemplate.js
@@ -59,6 +59,12 @@ export const V8_WINDOWS_RUNTIME = [
/** The V8 an Android V8 host links, one per ABI beside the host library. */
export const V8_ANDROID_LIBRARY = 'libv8android.so';
+/** Where an Android V8 host reads its startup snapshot from, inside the package's
+ * assets — the name native/CMakeLists.txt compiles in as ESJS_V8_SNAPSHOT_ASSET. */
+export function v8SnapshotAsset(abi) {
+ return `v8/${abi}/snapshot_blob.bin`;
+}
+
/** The JS engine a template's host embeds, read off the files it carries: 'v8'
* when the V8 runtime is there, 'quickjs' otherwise. */
export function templateJsEngine(dir, platform) {
@@ -251,6 +257,12 @@ export function templateLayout(platform, options = {}) {
rel: `lib/${abi}/${V8_ANDROID_LIBRARY}`, strip: true, abi, optional: true,
from: (ctx) => path.join(ctx.root, 'build/cmake/native', abi, V8_ANDROID_LIBRARY),
},
+ {
+ // Its startup snapshot, which this V8 keeps outside the library. An
+ // asset, read by the host before the engine starts (Runtime.cpp).
+ rel: `assets/${v8SnapshotAsset(abi)}`, abi, optional: true,
+ from: (ctx) => path.join(ctx.root, 'build/cmake/native', abi, 'v8_snapshot_blob.bin'),
+ },
]);
return [
...libs,
@@ -322,6 +334,8 @@ export function androidTemplateSources(dir) {
manifestIn: path.join(dir, 'AndroidManifest.xml.in'),
icon: path.join(dir, DEFAULT_ICON),
bytecode: path.join(dir, 'assets', BYTECODE_FILE),
+ /** A V8 host's startup snapshots, one per ABI; absent from a QuickJS template. */
+ v8Snapshots: path.join(dir, 'assets', 'v8'),
};
}
diff --git a/docs/astro/src/content/docs/publishing/android-ios.mdx b/docs/astro/src/content/docs/publishing/android-ios.mdx
index 62a869d16..f1ca8c88c 100644
--- a/docs/astro/src/content/docs/publishing/android-ios.mdx
+++ b/docs/astro/src/content/docs/publishing/android-ios.mdx
@@ -268,9 +268,10 @@ touching the source PNG. See [Assets](/docs/assets/overview/).
The engine runs native at full speed everywhere. Your game script does too on
**Android**: it runs on V8 with its JIT, the engine Chrome runs — the same script
is compiled to machine code as it would be in a browser, with nothing to change in
-the project. Measured with the same host on a desktop CPU, a frame of 5,000 scripted
-entities that took 76 ms on the interpreter takes 8 ms on V8; a phone is slower in
-both columns, by about the same factor.
+the project. On a Snapdragon 8 Elite phone, a frame of 5,000 scripted entities that
+took 64 ms on the interpreter takes 14 ms on V8 (on a desktop CPU: 76 ms → 8 ms).
+V8 adds about 11 MB to a package (`libv8android.so` per ABI, stored uncompressed as
+Android prefers for native libraries).
On **iOS** your game script is interpreted, by QuickJS: Apple's rules allow no JIT
outside its own browser. A per-entity loop written in TypeScript is the one thing
@@ -283,8 +284,8 @@ export cross-compiles every `/** @compiled */` system with the Android NDK, once
64-bit ABI the package carries (arm64-v8a, and x86_64 for the emulator), and the
APK carries each build in `lib/<abi>/`. Where the interpreter spends microseconds
per entity, the compiled system spends tens of nanoseconds — and it still takes
-about six times off what the JIT leaves of a frame (8.3 ms → 1.4 ms in the
-measurement above). The NDK must be
+a large share off what the JIT leaves of a frame (14 ms → 4.2 ms on that phone,
+8.3 ms → 1.4 ms on the desktop). The NDK must be
installed on the exporting machine (Android Studio's SDK Manager, or
`ANDROID_NDK_HOME`); the Package dialog says so when a project promises compiled
systems and it is missing. A system the host cannot bind falls back to the
diff --git a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx
index b34af3044..622abf3e8 100644
--- a/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx
+++ b/docs/astro/src/content/docs/zh-cn/publishing/android-ios.mdx
@@ -225,8 +225,9 @@ Android 的下限是 29,因为引擎的字体路径调用 `AFontMatcher_create`,
引擎在各平台都以原生全速运行。**Android** 上游戏脚本也一样:它跑在带 JIT 的 V8 上,
和 Chrome 是同一个引擎——同一份脚本会像在浏览器里那样编译成机器码,项目里什么都不用改。
-用同一个宿主在桌面 CPU 上测:5000 个脚本实体的一帧,解释器要 76 毫秒,V8 上是 8 毫秒;
-手机上两列都更慢,倍数大致相同。
+在骁龙 8 Elite 手机上:5000 个脚本实体的一帧,解释器要 64 毫秒,V8 上是 14 毫秒
+(桌面 CPU 上是 76 → 8 毫秒)。V8 让包体大约增加 11 MB(每个 ABI 一份 `libv8android.so`,
+按 Android 对原生库的偏好不压缩存放)。
**iOS** 上游戏脚本由 QuickJS 解释执行:Apple 不允许自家浏览器以外的 JIT。
用 TypeScript 写的逐实体循环,是那里比浏览器里明显更贵的那一样东西——
@@ -234,8 +235,8 @@ Android 的下限是 29,因为引擎的字体路径调用 `AFontMatcher_create`,
**在 Android 上,标记了 `@compiled` 的系统不等 JIT 就以机器码运行。** 导出时会用 Android NDK
把每个 `/** @compiled */` 系统交叉编译,包里每个 64 位 ABI 各一份(arm64-v8a,模拟器还有
-x86_64),APK 把它们放在 `lib/<abi>/`。解释器每个实体要花微秒级,编译后只要几十纳秒——在 JIT 之上它仍能把一帧再快约 6 倍
-(上面那组测量里 8.3 毫秒 → 1.4 毫秒)。导出机器
+x86_64),APK 把它们放在 `lib/<abi>/`。解释器每个实体要花微秒级,编译后只要几十纳秒——在 JIT 之上它仍能把一帧再砍掉一大截
+(那台手机上 14 毫秒 → 4.2 毫秒,桌面上 8.3 → 1.4 毫秒)。导出机器
需要装好 NDK(Android Studio 的 SDK Manager,或设置 `ANDROID_NDK_HOME`);项目承诺了编译系统
而缺少 NDK 时,打包对话框会提示。宿主绑定不了的系统会在那一帧退回解释器,所以缺模块只影响速度,
不影响正确性。iOS 目前仍全部解释执行。
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index 8a213dec5..2a480a3bd 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -341,6 +341,14 @@ if(ESTELLA_QUICKJS_DIR)
add_library(esjs_v8 SHARED IMPORTED)
set_target_properties(esjs_v8 PROPERTIES IMPORTED_LOCATION "${_v8_so}")
target_link_libraries(esjs_engine INTERFACE esjs_v8)
+ # This V8 keeps its startup snapshot outside the library; the package
+ # carries it as an asset and the host hands it over before Isolate::New.
+ set(_v8_snapshot "${ESTELLA_V8_DIR}/snapshot/${ANDROID_ABI}/snapshot_blob.bin")
+ if(NOT EXISTS "${_v8_snapshot}")
+ message(FATAL_ERROR "No V8 startup snapshot for ${ANDROID_ABI}: ${_v8_snapshot} is missing (re-run --fetch-deps).")
+ endif()
+ target_compile_definitions(esjs_engine INTERFACE
+ ESJS_V8_SNAPSHOT_ASSET="v8/${ANDROID_ABI}/snapshot_blob.bin")
elseif(WIN32)
set(_v8_lib "${ESTELLA_V8_DIR}/lib/Release")
# The Windows build carries Intl, whose data file ships beside the exe.
@@ -516,10 +524,13 @@ if(ESTELLA_QUICKJS_DIR)
# beside the host library (build-tools/utils/nativeTemplate.js).
add_custom_command(TARGET estella_js_host POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_v8_so}" $<TARGET_FILE_DIR:estella_js_host>
- COMMENT "Placing libv8android.so beside the Android host")
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_v8_snapshot}"
+ $<TARGET_FILE_DIR:estella_js_host>/v8_snapshot_blob.bin
+ COMMENT "Placing libv8android.so and its startup snapshot beside the Android host")
else()
add_custom_command(TARGET estella_js_host POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rm -f $<TARGET_FILE_DIR:estella_js_host>/libv8android.so
+ $<TARGET_FILE_DIR:estella_js_host>/v8_snapshot_blob.bin
COMMENT "Clearing a V8 a previous build left beside the host")
endif()
endif()
diff --git a/native/host/Bench.cpp b/native/host/Bench.cpp
index 47cece6d8..bff4e0545 100644
--- a/native/host/Bench.cpp
+++ b/native/host/Bench.cpp
@@ -13,6 +13,9 @@
#include "Bench.hpp"
#include <algorithm>
+#include <cctype>
+#include <cstring>
+#include <utility>
#include <chrono>
#include <cstdlib>
#include <string>
@@ -35,6 +38,10 @@
#include "Runtime.hpp" // ESHOST_LOGI
+#if defined(__ANDROID__)
+#include <sys/system_properties.h>
+#endif
+
namespace eshost {
namespace {
@@ -98,8 +105,33 @@ struct BenchState {
unsigned aotPacked = 0, aotPackedFrame = 0;
};
+/**
+ * A bench switch: the environment variable, or — on Android, where an app is
+ * started with no environment of its own — the system property it maps to:
+ * ESTELLA_BENCH_FRAMES is `debug.estella.bench_frames`, which a shell can set
+ * (`adb shell setprop debug.estella.bench_frames 300`) before the app starts.
+ * The same bench then runs on a phone without a rebuilt package.
+ */
+const char* benchEnv(const char* name) {
+ if (const char* v = std::getenv(name)) return v;
+#if defined(__ANDROID__)
+ static std::vector<std::pair<std::string, std::string>> read;
+ for (const auto& [key, value] : read) if (key == name) return value.empty() ? nullptr : value.c_str();
+ std::string prop = "debug.estella.";
+ for (const char* c = name + std::strlen("ESTELLA_"); *c; ++c) {
+ prop += static_cast<char>(std::tolower(static_cast<unsigned char>(*c)));
+ }
+ char value[PROP_VALUE_MAX] = {};
+ __system_property_get(prop.c_str(), value);
+ read.emplace_back(name, value);
+ return read.back().second.empty() ? nullptr : read.back().second.c_str();
+#else
+ return nullptr;
+#endif
+}
+
long envLong(const char* name, long fallback) {
- const char* v = std::getenv(name);
+ const char* v = benchEnv(name);
if (v == nullptr || v[0] == '\0') return fallback;
const long n = std::strtol(v, nullptr, 10);
return n >= 0 ? n : fallback;
@@ -108,16 +140,16 @@ long envLong(const char* name, long fallback) {
BenchState& state() {
static BenchState s = [] {
BenchState init;
- const char* frames = std::getenv("ESTELLA_BENCH_FRAMES");
+ const char* frames = benchEnv("ESTELLA_BENCH_FRAMES");
init.frames = envLong("ESTELLA_BENCH_FRAMES", 0);
init.asked = frames != nullptr && frames[0] != '\0' && init.frames > 0;
init.warmup = envLong("ESTELLA_BENCH_WARMUP", 120);
- if (const char* dt = std::getenv("ESTELLA_BENCH_DT")) {
+ if (const char* dt = benchEnv("ESTELLA_BENCH_DT")) {
const double v = std::strtod(dt, nullptr);
if (v > 0.0) init.dt = v;
}
- if (const char* label = std::getenv("ESTELLA_BENCH_LABEL")) init.label = label;
- if (const char* quit = std::getenv("ESTELLA_BENCH_QUIT")) init.quitAfter = quit[0] != '0';
+ if (const char* label = benchEnv("ESTELLA_BENCH_LABEL")) init.label = label;
+ if (const char* quit = benchEnv("ESTELLA_BENCH_QUIT")) init.quitAfter = quit[0] != '0';
if (init.asked) {
init.update.ms.reserve(static_cast<size_t>(init.frames));
init.pump.ms.reserve(static_cast<size_t>(init.frames));
diff --git a/native/host/Bindings.hpp b/native/host/Bindings.hpp
index 3066f770a..20093a2c9 100644
--- a/native/host/Bindings.hpp
+++ b/native/host/Bindings.hpp
@@ -60,9 +60,9 @@ void registerSteamBindings(HostState& h, esjs::Val global);
void registerNetBindings(HostState& h, esjs::Val global);
void registerDeviceBindings(HostState& h, esjs::Val global);
-/** es_aot_* — the compiled systems a shipped build loads, and the naming a
- * host does for them. Absent on the web, where the module shares the engine's
- * memory and the rows are packed in JS. */
+/** es_aot_* — the compiled systems a shipped build loads (desktop, Android), and
+ * the naming a host does for them. Absent on the web, where the module shares the
+ * engine's memory and the rows are packed in JS, and on iOS, which loads none. */
void registerAotBindings(HostState& h, esjs::Val global);
/** es_textEditor_* over the platform's soft keyboard — bound ONLY when the
diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cpp
index 52f4a8183..e78ff3ed1 100644
--- a/native/host/Runtime.cpp
+++ b/native/host/Runtime.cpp
@@ -305,6 +305,16 @@ void bindGlobal(esjs::Val global, const char* name, esjs::NativeFn fn, int argc)
void initRuntime(HostState& h) {
const double t0 = nowMs();
+#if defined(ESJS_V8_SNAPSHOT_ASSET)
+ // This V8 keeps its startup snapshot outside the library, and an isolate made
+ // without it dies on the spot ("Failed to deserialize the V8 snapshot blob").
+ const std::vector<u8> snapshot = readAsset(h, ESJS_V8_SNAPSHOT_ASSET);
+ if (snapshot.empty()) {
+ ESHOST_LOGE("JS engine: the package carries no %s — the V8 runtime cannot start",
+ ESJS_V8_SNAPSHOT_ASSET);
+ }
+ esjs::setStartupSnapshot(snapshot.data(), snapshot.size());
+#endif
esjs::init(engineLog, nullptr);
ESHOST_LOGI("JS engine: %s%s", esjs::engineName().c_str(), esjs::hasJit() ? " (JIT)" : " (interpreter)");
bootNote("engine: %s", esjs::engineName().c_str());
@@ -341,6 +351,12 @@ void initRuntime(HostState& h) {
registerInputBindings(h, global);
#if defined(ESTELLA_DESKTOP)
registerSteamBindings(h, global);
+#endif
+#if defined(ESTELLA_DESKTOP) || defined(__ANDROID__)
+ // Where a package can carry compiled systems: a desktop app beside its
+ // executable, an APK in lib/<abi>/ (the system linker finds it by name).
+ // Without these the SDK falls back to the wasm install, which a native core
+ // cannot serve — every @compiled system then stays interpreted.
registerAotBindings(h, global);
#endif
registerNetBindings(h, global);
diff --git a/native/host/bindings/AotBindings.cpp b/native/host/bindings/AotBindings.cpp
index e646e6ed6..467a9291a 100644
--- a/native/host/bindings/AotBindings.cpp
+++ b/native/host/bindings/AotBindings.cpp
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file AotBindings.cpp
- * @brief es_aot_* — the compiled systems a shipped desktop build loads.
+ * @brief es_aot_* — the compiled systems a shipped desktop or Android build loads.
* @details The web road hands the module the engine's memory and lets JS pack
* the rows. Here the engine IS the process: an address is a pointer
* nothing in JS can hold, so the rows are packed on this side and
diff --git a/native/host/js/esjs.hpp b/native/host/js/esjs.hpp
index 0d0cbb00c..a1cf48398 100644
--- a/native/host/js/esjs.hpp
+++ b/native/host/js/esjs.hpp
@@ -204,6 +204,11 @@ private:
/** Where the engine's own messages go: an uncaught exception, a rejected cache. */
using Logger = void (*)(bool error, const char* message);
+/** The startup snapshot an engine built with external startup data needs, handed
+ * over before {@link init} (V8 on Android). The bytes are copied. A no-op for an
+ * engine that has its snapshot built in, or none. */
+void setStartupSnapshot(const uint8_t* data, size_t size);
+
/** Bring the engine up: one runtime, one context, for the process. @p exePath is
* where an engine that ships data files beside the binary looks for them. */
void init(Logger log, const char* exePath);
diff --git a/native/host/js/esjs_quickjs.cpp b/native/host/js/esjs_quickjs.cpp
index b530d2495..d879b0e9a 100644
--- a/native/host/js/esjs_quickjs.cpp
+++ b/native/host/js/esjs_quickjs.cpp
@@ -342,6 +342,8 @@ void Ref::reset() {
// The engine
// =============================================================================
+void setStartupSnapshot(const uint8_t*, size_t) {}
+
void init(Logger log, const char*) {
g_log = log;
g_rt = JS_NewRuntime();
diff --git a/native/host/js/esjs_v8.cpp b/native/host/js/esjs_v8.cpp
index b56f334e6..17ed6a99d 100644
--- a/native/host/js/esjs_v8.cpp
+++ b/native/host/js/esjs_v8.cpp
@@ -419,6 +419,15 @@ void Ref::reset() {
// The engine
// =============================================================================
+std::vector<uint8_t> g_snapshot; // must outlive the isolate
+v8::StartupData g_snapshotData{nullptr, 0};
+
+void setStartupSnapshot(const uint8_t* data, size_t size) {
+ g_snapshot.assign(data, data + size);
+ g_snapshotData = {reinterpret_cast<const char*>(g_snapshot.data()), static_cast<int>(g_snapshot.size())};
+ v8::V8::SetSnapshotDataBlob(&g_snapshotData);
+}
+
void init(Logger log, const char* exePath) {
g_log = log;
#if defined(ESJS_V8_ICU)
diff --git a/native/host/platform/android.cpp b/native/host/platform/android.cpp
index 34c343e49..7ab3df49a 100644
--- a/native/host/platform/android.cpp
+++ b/native/host/platform/android.cpp
@@ -28,6 +28,7 @@
#include <chrono>
#include <cstdarg>
+#include <string>
#include <thread>
#include "Host.hpp"
@@ -954,7 +955,43 @@ std::string queryCacheDir(ANativeActivity* activity) {
} // namespace
+/**
+ * An app's stdout and stderr go nowhere on Android, and a native library that
+ * reports a fatal error by printing it and aborting (V8 does exactly that) then
+ * dies with a backtrace and no reason. Route both into logcat, line by line, once
+ * per process — before anything that could print.
+ */
+static void forwardStdioToLog() {
+ static bool started = false;
+ if (started) return;
+ int fds[2];
+ if (pipe(fds) != 0) return;
+ started = true;
+ setvbuf(stdout, nullptr, _IOLBF, 0);
+ setvbuf(stderr, nullptr, _IONBF, 0);
+ dup2(fds[1], STDOUT_FILENO);
+ dup2(fds[1], STDERR_FILENO);
+ close(fds[1]);
+ std::thread([fd = fds[0]] {
+ char buf[1024];
+ std::string line;
+ for (;;) {
+ const ssize_t n = read(fd, buf, sizeof(buf));
+ if (n <= 0) break;
+ for (ssize_t i = 0; i < n; ++i) {
+ if (buf[i] == '\n') {
+ __android_log_write(ANDROID_LOG_WARN, LOG_TAG, line.c_str());
+ line.clear();
+ } else {
+ line += buf[i];
+ }
+ }
+ }
+ }).detach();
+}
+
void android_main(android_app* app) {
+ forwardStdioToLog();
g_platform.device.activity = app->activity;
g_platform.assets = app->activity->assetManager; // APK assets/ (the exported project)
g_platform.vm = app->activity->vm; // for JNI HttpURLConnection (es_fetch)