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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sdk): WASM abort error channel — stop calling a dead module (RC3 part 1)
esengine97aacb8bafa5
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.mdindex 7f02c3f68..965c63dfa 100644--- a/docs/REARCHITECTURE.md+++ b/docs/REARCHITECTURE.md@@ -138,5 +138,14 @@- `SparseSet` 新增 `version()`:在组件缓冲**重分配**(emplace 扩容)、**relocate**(remove swap-pop、sort/rebuildSparse)时自增——作为 RC3 跨界指针失效守卫的**单一来源**,取代已删除的 `SchemaComponentPool::poolVersion`(后者还漏了 remove 时不自增的 bug)。- **验证**:native MSVC harness 编译+运行通过(version() 在 fill/remove/clear 后均自增;destroy 后回收的实体无残留组件);SDK typecheck + 2012 测试全过。-### RC3 / RC5 — 未开始-按执行顺序依次推进,全程在 RC1 的 `static_assert` + 握手护栏内进行,并尽量用独立 harness 即时编译验证。RC3 第一件事就是把 `getXxxPtr` 的失效守卫接到 RC2 新增的 `SparseSet::version()` 上。+### RC3 错误/生命周期 — 🟡 进行中(错误通道已落地并测试)+错误模型已定:**保持 `-fno-exceptions` + 显式状态 + onAbort 死亡标志**(不增体积/不降速)。+- ✅ **错误通道(已完成)**:新增 `moduleHealth.ts`——`WasmModuleAborted` + 按模块的死亡标志 + `installAbortGuard`(挂 emscripten `Module.onAbort`,保留既有 handler)。`handleWasmError` 对 `WasmModuleAborted` **重抛不吞**(abort 是终态,吞掉就是继续调用尸体)。`BuiltinBridge` 在 `connect` 装守卫,并在唯一收口 `resolveAndCache_` 把四个边界方法包成"调用前短路 + 调用中 abort 则致命重抛"。验证:typecheck + 8 个新测试 + 全套 2020 测试通过。+- ⏳ **RC3 剩余**(后续批次):+ 1. 把 `getXxxPtr` 的指针失效守卫接到 RC2 的 `SparseSet::version()`(需加一个按组件取 version 的绑定 + BuiltinBridge 复核)。+ 2. TS `_malloc/_free` 全部进 RAII `withMalloc()` 作用域(physics/timeline/runtimeLoader/tilemap…),抛异常也不泄漏。+ 3. C++ 边界校验始终开启(不被 release 的 `ES_ASSERT` 剥离)——目前生成的 embind 包装已有 `valid(entity)` 守卫,需审计补齐其余入口。+ 4. 各子系统桥接(physics/spine/tilemap/timeline)调用前接 `throwIfModuleAborted`。++### RC5 — 未开始+渲染单一路径 + GfxDevice 唯一入口 + u16→u32 + 统一 WasmBridge + 全 per-App。最大的一块,建议拆多批推进。diff --git a/sdk/src/ecs/BuiltinBridge.ts b/sdk/src/ecs/BuiltinBridge.tsindex 96a5b0f4e..f9b2ec5f0 100644--- a/sdk/src/ecs/BuiltinBridge.ts+++ b/sdk/src/ecs/BuiltinBridge.ts@@ -8,6 +8,7 @@ import type { BuiltinComponentDef } from '../component';import type { CppRegistry, ESEngineModule } from '../wasm';import { validateComponentData, formatValidationErrors } from '../validation';import { handleWasmError } from '../wasmError';+import { installAbortGuard, throwIfModuleAborted, isModuleAborted, WasmModuleAborted } from '../moduleHealth';import { COMPONENT_META, ABI_LAYOUT_HASH } from '../component.generated';import { PTR_LAYOUTS } from '../ptrLayouts.generated';import { PTR_ACCESSORS } from './ptrAccessors.generated';@@ -324,6 +325,12 @@ export class BuiltinBridge {this.builtinMethodCache_.clear();this.builtinEntitySets_.clear();+ // Install the terminal-abort guard so a C++ abort flips the module-dead+ // flag and subsequent boundary calls short-circuit (see moduleHealth.ts).+ if (module) {+ installAbortGuard(module);+ }+const verification = this.verifyAgainst_(cppRegistry, module);// An ABI hash mismatch is ALWAYS fatal, even in non-strict mode: the// loaded WASM and this SDK disagree on byte layout, so any fast-path@@ -459,11 +466,28 @@ export class BuiltinBridge {`Expected: add${cppName}, get${cppName}, has${cppName}, remove${cppName}`,);}+ // Gate every boundary call through the module-abort guard at this single+ // chokepoint: refuse to call a dead module (pre-check), and if a call+ // itself aborts the module, surface it as a fatal WasmModuleAborted+ // rather than letting the corpse return undefined memory.+ const guard = <A extends unknown[], R>(op: string, fn: (...a: A) => R): ((...a: A) => R) => {+ return (...a: A): R => {+ throwIfModuleAborted(this.module_, `${op}${cppName}`);+ try {+ return fn(...a);+ } catch (err) {+ if (isModuleAborted(this.module_)) {+ throw new WasmModuleAborted(`${op}${cppName}`, undefined, err);+ }+ throw err;+ }+ };+ };const methods: BuiltinMethods = {- add: (addFn as (e: Entity, d: unknown) => void).bind(reg),- get: (getFn as (e: Entity) => unknown).bind(reg),- has: (hasFn as (e: Entity) => boolean).bind(reg),- remove: (removeFn as (e: Entity) => void).bind(reg),+ add: guard('add', (addFn as (e: Entity, d: unknown) => void).bind(reg)),+ get: guard('get', (getFn as (e: Entity) => unknown).bind(reg)),+ has: guard('has', (hasFn as (e: Entity) => boolean).bind(reg)),+ remove: guard('remove', (removeFn as (e: Entity) => void).bind(reg)),};this.builtinMethodCache_.set(cppName, methods);return methods;diff --git a/sdk/src/moduleHealth.ts b/sdk/src/moduleHealth.tsnew file mode 100644index 000000000..ac2a81205--- /dev/null+++ b/sdk/src/moduleHealth.ts@@ -0,0 +1,98 @@+/**+ * @file moduleHealth.ts+ * @brief Terminal-abort tracking for the C++/WASM boundary.+ *+ * @details The engine compiles the WASM module with `-fno-exceptions`, so a C+++ * failure (OOM, failed assert, unreachable) calls `abort()` and tears+ * the module down permanently — it does NOT surface as a catchable JS+ * exception. Without tracking, the SDK keeps calling into the corpse,+ * reading and writing undefined memory.+ *+ * This module is the error channel for that model: install an+ * `onAbort` guard that flips a per-module "dead" flag, and have every+ * boundary call short-circuit with {@link WasmModuleAborted} instead of+ * invoking a dead module. The flag is terminal — a module never+ * recovers from abort.+ */++/** Thrown when a boundary call is attempted on a WASM module that has aborted. */+export class WasmModuleAborted extends Error {+ /** Where the rejected call originated (for diagnostics). */+ readonly context: string;+ /** The abort reason reported by the emscripten runtime, if any. */+ readonly reason: string | undefined;++ constructor(context: string, reason?: string, cause?: unknown) {+ super(+ `WASM module aborted; refusing to call into it (${context})` ++ (reason ? `: ${reason}` : ''),+ );+ this.name = 'WasmModuleAborted';+ this.context = context;+ this.reason = reason;+ if (cause !== undefined) {+ (this as { cause?: unknown }).cause = cause;+ }+ }+}++interface ModuleHealth {+ aborted: boolean;+ reason?: string;+ guardInstalled?: boolean;+}++// Health is keyed by module identity so multiple modules (main, side-modules,+// test mocks) are tracked independently and state is GC'd with the module.+const healthByModule = new WeakMap<object, ModuleHealth>();++function stateOf(module: object): ModuleHealth {+ let s = healthByModule.get(module);+ if (!s) {+ s = { aborted: false };+ healthByModule.set(module, s);+ }+ return s;+}++/** Mark a module as aborted (terminal). Idempotent; keeps the first reason. */+export function markModuleAborted(module: object, reason?: string): void {+ const s = stateOf(module);+ if (!s.aborted) {+ s.aborted = true;+ s.reason = reason;+ }+}++/** True if the module has aborted. False for null/undefined (nothing to call). */+export function isModuleAborted(module: object | null | undefined): boolean {+ return module ? stateOf(module).aborted : false;+}++/** Throw {@link WasmModuleAborted} if the module has aborted; otherwise no-op. */+export function throwIfModuleAborted(module: object | null | undefined, context: string): void {+ if (!module) return;+ const s = stateOf(module);+ if (s.aborted) {+ throw new WasmModuleAborted(context, s.reason);+ }+}++/**+ * Install a terminal abort guard on a module. The emscripten runtime invokes+ * `Module.onAbort(what)` when it aborts; we flip the dead flag so subsequent+ * boundary calls short-circuit. Any pre-existing `onAbort` is preserved and+ * still called. Idempotent per module.+ */+export function installAbortGuard(module: object): void {+ const s = stateOf(module);+ if (s.guardInstalled) return;+ s.guardInstalled = true;++ const m = module as { onAbort?: (what: unknown) => void };+ const prev = typeof m.onAbort === 'function' ? m.onAbort.bind(m) : null;+ m.onAbort = (what: unknown): void => {+ markModuleAborted(module, what === null || what === undefined ? undefined : String(what));+ if (prev) prev(what);+ };+}diff --git a/sdk/src/wasmError.ts b/sdk/src/wasmError.tsindex 540b5db19..8bed0620c 100644--- a/sdk/src/wasmError.ts+++ b/sdk/src/wasmError.ts@@ -1,5 +1,6 @@import { log } from './logger';import { getDefaultContext, type WasmErrorHandler } from './context';+import { WasmModuleAborted } from './moduleHealth';const THROTTLE_MS = 1000;@@ -8,6 +9,13 @@ export function setWasmErrorHandler(handler: WasmErrorHandler | null): void {}export function handleWasmError(error: unknown, context: string): void {+ // A module abort is terminal and unrecoverable — never swallow it into a+ // default value. Rethrow so it propagates out of every catch-and-continue+ // site (the module is dead; continuing would call into a corpse).+ if (error instanceof WasmModuleAborted) {+ throw error;+ }+const state = getDefaultContext().wasmError;const now = Date.now();if (now - state.lastReportTime < THROTTLE_MS) {diff --git a/sdk/tests/module-health.test.ts b/sdk/tests/module-health.test.tsnew file mode 100644index 000000000..3dba810be--- /dev/null+++ b/sdk/tests/module-health.test.ts@@ -0,0 +1,111 @@+/**+ * @file module-health.test.ts+ * @brief The WASM terminal-abort error channel: a module abort flips a dead+ * flag and boundary calls refuse to run rather than touching a corpse.+ */+import { describe, it, expect, vi } from 'vitest';+import {+ WasmModuleAborted, markModuleAborted, isModuleAborted,+ throwIfModuleAborted, installAbortGuard,+} from '../src/moduleHealth';+import { handleWasmError } from '../src/wasmError';+import { BuiltinBridge } from '../src/ecs/BuiltinBridge';+import { COMPONENT_META, ABI_LAYOUT_HASH } from '../src/component.generated';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import type { Entity } from '../src/types';++function stubMethod() { return undefined; }+function makeCompleteRegistry(): Record<string, (...args: unknown[]) => unknown> {+ const reg: Record<string, (...args: unknown[]) => unknown> = {};+ for (const name of Object.keys(COMPONENT_META)) {+ for (const prefix of ['add', 'get', 'has', 'remove']) {+ reg[`${prefix}${name}`] = stubMethod;+ }+ }+ return reg;+}++describe('moduleHealth primitive', () => {+ it('tracks abort state per module', () => {+ const m = {};+ expect(isModuleAborted(m)).toBe(false);+ markModuleAborted(m, 'OOM');+ expect(isModuleAborted(m)).toBe(true);+ });++ it('treats null/undefined as not-aborted (nothing to call)', () => {+ expect(isModuleAborted(null)).toBe(false);+ expect(isModuleAborted(undefined)).toBe(false);+ });++ it('throwIfModuleAborted carries context and reason', () => {+ const m = {};+ markModuleAborted(m, 'unreachable executed');+ let caught: WasmModuleAborted | null = null;+ try {+ throwIfModuleAborted(m, 'addSprite');+ } catch (e) {+ caught = e as WasmModuleAborted;+ }+ expect(caught).toBeInstanceOf(WasmModuleAborted);+ expect(caught!.context).toBe('addSprite');+ expect(caught!.reason).toBe('unreachable executed');+ expect(caught!.message).toContain('addSprite');+ expect(caught!.message).toContain('unreachable executed');+ });++ it('installAbortGuard flips the flag on abort and preserves a prior onAbort', () => {+ const prev = vi.fn();+ const m: { onAbort?: (what: unknown) => void } = { onAbort: prev };+ installAbortGuard(m);+ expect(isModuleAborted(m)).toBe(false);++ m.onAbort!('memory access out of bounds');+ expect(isModuleAborted(m)).toBe(true);+ expect(prev).toHaveBeenCalledWith('memory access out of bounds');+ });++ it('installAbortGuard is idempotent', () => {+ const m: { onAbort?: (what: unknown) => void } = {};+ installAbortGuard(m);+ const first = m.onAbort;+ installAbortGuard(m);+ expect(m.onAbort).toBe(first);+ });+});++describe('handleWasmError', () => {+ it('rethrows a WasmModuleAborted (fatal, never swallowed)', () => {+ expect(() => handleWasmError(new WasmModuleAborted('ctx'), 'ctx'))+ .toThrowError(WasmModuleAborted);+ });++ it('swallows ordinary transient errors', () => {+ expect(() => handleWasmError(new Error('transient'), 'ctx')).not.toThrow();+ });+});++describe('BuiltinBridge abort gating', () => {+ const firstName = Object.keys(COMPONENT_META)[0]!;++ it('refuses boundary calls once the module has aborted', () => {+ const bridge = new BuiltinBridge();+ const reg = makeCompleteRegistry() as unknown as CppRegistry;+ const module = {+ getBuiltinComponentNames: () => Object.keys(COMPONENT_META),+ getAbiLayoutHash: () => ABI_LAYOUT_HASH,+ } as unknown as ESEngineModule;++ bridge.connect(reg, module, { strict: true });+ const methods = bridge.getBuiltinMethods(firstName);++ // Healthy: calls pass through to the (stub) registry without throwing.+ expect(() => methods.has(1 as unknown as Entity)).not.toThrow();++ // Simulate a C++ abort firing the installed onAbort guard.+ (module as unknown as { onAbort: (w: unknown) => void }).onAbort('OOM');++ expect(() => methods.has(1 as unknown as Entity)).toThrowError(WasmModuleAborted);+ expect(() => methods.add(1 as unknown as Entity, {})).toThrowError(WasmModuleAborted);+ });+});