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(sdk): exception-safe WASM scratch allocation (RC3 part 2)

esengine0a6986d0d9ed
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.md
index 965c63dfa..4633cf9b9 100644
--- a/docs/REARCHITECTURE.md
+++ b/docs/REARCHITECTURE.md
@@ -141,11 +141,11 @@
### RC3 错误/生命周期 — 🟡 进行中(错误通道已落地并测试)
错误模型已定:**保持 `-fno-exceptions` + 显式状态 + onAbort 死亡标志**(不增体积/不降速)。
- ✅ **错误通道(已完成)**:新增 `moduleHealth.ts`——`WasmModuleAborted` + 按模块的死亡标志 + `installAbortGuard`(挂 emscripten `Module.onAbort`,保留既有 handler)。`handleWasmError` 对 `WasmModuleAborted` **重抛不吞**(abort 是终态,吞掉就是继续调用尸体)。`BuiltinBridge` 在 `connect` 装守卫,并在唯一收口 `resolveAndCache_` 把四个边界方法包成"调用前短路 + 调用中 abort 则致命重抛"。验证:typecheck + 8 个新测试 + 全套 2020 测试通过。
+- ✅ **RAII `_malloc`(已完成)**:新增 `wasmScratch.ts`——`withScratch(mod, alloc => …)` / `withMalloc`,作用域内分配的所有缓冲在回调返回**或抛异常**时按逆序释放。把 9 个文件的全部瞬时分配站点(runtimeLoader、TextureLoader、PhysicsSystem×3、TimelineUploader×6、ModuleBackend、SpineController×4、tilemapAPI×3、tiledLoader×4、TextRenderer)迁到该助手;持久缓冲(material/draw/renderer/geometry 的 alloc-once)与已有 try/finally 的站点不动。验证:5 个新 helper 测试 + typecheck + 全套 2025 测试;逐一人工复核 TimelineUploader/SpineController 等复杂多缓冲迁移,行为逐字节保持。
- ⏳ **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`。
+ 2. C++ 边界校验始终开启(不被 release 的 `ES_ASSERT` 剥离)——目前生成的 embind 包装已有 `valid(entity)` 守卫,需审计补齐其余入口。
+ 3. 各子系统桥接(physics/spine/tilemap/timeline)调用前接 `throwIfModuleAborted`。
### RC5 — 未开始
渲染单一路径 + GfxDevice 唯一入口 + u16→u32 + 统一 WasmBridge + 全 per-App。最大的一块,建议拆多批推进。
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index d1bcb828a..90972f42b 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -2,6 +2,7 @@ import type { AssetLoader, LoadContext, TextureResult } from '../AssetLoader';
import { platformCreateCanvas, platformCreateImage } from '../../platform';
import { requireResourceManager } from '../../resourceManager';
import type { ESEngineModule } from '../../wasm';
+import { withMalloc } from '../../wasmScratch';
/**
* Texture import-time settings. Applied when the GL texture is first uploaded,
@@ -67,10 +68,10 @@ export class TextureLoader implements AssetLoader<TextureResult> {
width: number, height: number, pixels: Uint8Array, flipY: boolean,
): Promise<TextureResult> {
const rm = requireResourceManager();
- const ptr = this.module_._malloc(pixels.length);
- this.module_.HEAPU8.set(pixels, ptr);
- const handle = rm.createTexture(width, height, ptr, pixels.length, 1, flipY);
- this.module_._free(ptr);
+ const handle = withMalloc(this.module_, pixels.length, ptr => {
+ this.module_.HEAPU8.set(pixels, ptr);
+ return rm.createTexture(width, height, ptr, pixels.length, 1, flipY);
+ });
return { handle, width, height };
}
@@ -194,10 +195,10 @@ export class TextureLoader implements AssetLoader<TextureResult> {
unpremultiplyAlpha(pixels);
const rm = requireResourceManager();
- const ptr = this.module_._malloc(pixels.length);
- this.module_.HEAPU8.set(pixels, ptr);
- const handle = rm.createTexture(width, height, ptr, pixels.length, 1, flip);
- this.module_._free(ptr);
+ const handle = withMalloc(this.module_, pixels.length, ptr => {
+ this.module_.HEAPU8.set(pixels, ptr);
+ return rm.createTexture(width, height, ptr, pixels.length, 1, flip);
+ });
return { handle, width, height };
}
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index 51cfd0ec1..dc5e6cc7a 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -34,6 +34,7 @@ import {
type CollisionEnterEvent,
type SensorEvent,
} from './PhysicsTypes';
+import { withMalloc } from '../wasmScratch';
// =============================================================================
// Canvas pixelsPerUnit live read
@@ -125,18 +126,18 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity,
const verts = poly.vertices;
const count = Math.min(verts.length, 8);
const byteSize = count * 2 * 4;
- const ptr = module._malloc(byteSize);
- const base = ptr >> 2;
- for (let i = 0; i < count; i++) {
- module.HEAPF32[base + i * 2] = verts[i].x;
- module.HEAPF32[base + i * 2 + 1] = verts[i].y;
- }
- module._physics_addPolygonShape(
- entity, ptr, count, poly.radius ?? 0,
- poly.density, poly.friction, poly.restitution, poly.isSensor ? 1 : 0,
- category, mask
- );
- module._free(ptr);
+ withMalloc(module, byteSize, ptr => {
+ const base = ptr >> 2;
+ for (let i = 0; i < count; i++) {
+ module.HEAPF32[base + i * 2] = verts[i].x;
+ module.HEAPF32[base + i * 2 + 1] = verts[i].y;
+ }
+ module._physics_addPolygonShape(
+ entity, ptr, count, poly.radius ?? 0,
+ poly.density, poly.friction, poly.restitution, poly.isSensor ? 1 : 0,
+ category, mask
+ );
+ });
}
if (world.has(entity, ChainCollider)) {
@@ -144,18 +145,18 @@ function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity,
const pts = chain.points;
if (pts.length < 4) return;
const byteSize = pts.length * 2 * 4;
- const ptr = module._malloc(byteSize);
- const base = ptr >> 2;
- for (let i = 0; i < pts.length; i++) {
- module.HEAPF32[base + i * 2] = pts[i].x;
- module.HEAPF32[base + i * 2 + 1] = pts[i].y;
- }
- module._physics_addChainShape(
- entity, ptr, pts.length, chain.isLoop ? 1 : 0,
- chain.friction, chain.restitution,
- chain.categoryBits ?? 0x0001, chain.maskBits ?? 0xFFFF
- );
- module._free(ptr);
+ withMalloc(module, byteSize, ptr => {
+ const base = ptr >> 2;
+ for (let i = 0; i < pts.length; i++) {
+ module.HEAPF32[base + i * 2] = pts[i].x;
+ module.HEAPF32[base + i * 2 + 1] = pts[i].y;
+ }
+ module._physics_addChainShape(
+ entity, ptr, pts.length, chain.isLoop ? 1 : 0,
+ chain.friction, chain.restitution,
+ chain.categoryBits ?? 0x0001, chain.maskBits ?? 0xFFFF
+ );
+ });
}
}
@@ -307,13 +308,13 @@ export function syncDynamicTransforms(
if (!hasParented && engineMod?.registry_batchSyncPhysicsTransforms) {
const byteLen = count * PHYSICS_BODY_BYTES;
- const engineBuf = engineMod._malloc(byteLen);
- engineMod.HEAPU8.set(
- new Uint8Array(module.HEAPU8.buffer, ptr, byteLen),
- engineBuf,
- );
- engineMod.registry_batchSyncPhysicsTransforms(registry, engineBuf, count, ppu);
- engineMod._free(engineBuf);
+ withMalloc(engineMod, byteLen, engineBuf => {
+ engineMod.HEAPU8.set(
+ new Uint8Array(module.HEAPU8.buffer, ptr, byteLen),
+ engineBuf,
+ );
+ engineMod.registry_batchSyncPhysicsTransforms(registry, engineBuf, count, ppu);
+ });
return;
}
diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.ts
index 41147436a..6c6e8d159 100644
--- a/sdk/src/runtimeLoader.ts
+++ b/sdk/src/runtimeLoader.ts
@@ -28,6 +28,7 @@ import { requireResourceManager } from './resourceManager';
import { parseTmjJson, resolveRelativePath } from './tilemap/tiledLoader';
import { registerTilemapSource } from './tilemap/tilesetCache';
import { log } from './logger';
+import { withMalloc } from './wasmScratch';
// =============================================================================
// Public Interface
@@ -60,19 +61,16 @@ function createTextureFromPixels(
params?: TextureParams,
): number {
const rm = requireResourceManager();
- const ptr = module._malloc(result.pixels.length);
- module.HEAPU8.set(result.pixels, ptr);
-
- let handle: number;
- if (params && (params.filterMode || params.wrapMode) && rm.createTextureEx) {
- const filter = FILTER_MODE_MAP[params.filterMode ?? 'linear'] ?? 1;
- const wrap = WRAP_MODE_MAP[params.wrapMode ?? 'clamp'] ?? 1;
- handle = rm.createTextureEx(result.width, result.height, ptr, result.pixels.length, 1, flipY, filter, wrap);
- } else {
- handle = rm.createTexture(result.width, result.height, ptr, result.pixels.length, 1, flipY);
- }
- module._free(ptr);
- return handle;
+ return withMalloc(module, result.pixels.length, ptr => {
+ module.HEAPU8.set(result.pixels, ptr);
+
+ if (params && (params.filterMode || params.wrapMode) && rm.createTextureEx) {
+ const filter = FILTER_MODE_MAP[params.filterMode ?? 'linear'] ?? 1;
+ const wrap = WRAP_MODE_MAP[params.wrapMode ?? 'clamp'] ?? 1;
+ return rm.createTextureEx(result.width, result.height, ptr, result.pixels.length, 1, flipY, filter, wrap);
+ }
+ return rm.createTexture(result.width, result.height, ptr, result.pixels.length, 1, flipY);
+ });
}
async function loadTextures(
diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.ts
index 1d0b6edb3..146617c2c 100644
--- a/sdk/src/spine/ModuleBackend.ts
+++ b/sdk/src/spine/ModuleBackend.ts
@@ -3,6 +3,7 @@ import type { ESEngineModule, CppRegistry } from '../wasm';
import type { SpineModuleController } from './SpineController';
import type { RawSpineEvent, ConstraintList, TransformMixData, PathMixData } from './SpineController';
import { log } from '../logger';
+import { withScratch } from '../wasmScratch';
interface EntityInfo {
skelHandle: number;
@@ -230,31 +231,30 @@ export class ModuleBackend {
totalIdxBytes += e.indices.byteLength;
}
- const vertBase = coreModule._malloc(totalVertBytes);
- const idxBase = coreModule._malloc(totalIdxBytes);
+ withScratch(coreModule, alloc => {
+ const vertBase = alloc(totalVertBytes);
+ const idxBase = alloc(totalIdxBytes);
- let vOff = 0;
- let iOff = 0;
- for (const e of this.cachedEntries_) {
- const vertPtr = vertBase + vOff;
- const idxPtr = idxBase + iOff;
-
- coreModule.HEAPF32.set(e.vertices, vertPtr >> 2);
- new Uint16Array(coreModule.HEAPU8.buffer, idxPtr, e.indices.length).set(e.indices);
+ let vOff = 0;
+ let iOff = 0;
+ for (const e of this.cachedEntries_) {
+ const vertPtr = vertBase + vOff;
+ const idxPtr = idxBase + iOff;
- submitFn.call(coreModule, registry,
- vertPtr, e.vertices.length / 8,
- idxPtr, e.indices.length,
- e.textureId, e.blendMode,
- e.entity, e.info.skeletonScale, e.info.flipX, e.info.flipY,
- e.info.layer, 0);
+ coreModule.HEAPF32.set(e.vertices, vertPtr >> 2);
+ new Uint16Array(coreModule.HEAPU8.buffer, idxPtr, e.indices.length).set(e.indices);
- vOff += e.vertices.byteLength;
- iOff += e.indices.byteLength;
- }
+ submitFn.call(coreModule, registry,
+ vertPtr, e.vertices.length / 8,
+ idxPtr, e.indices.length,
+ e.textureId, e.blendMode,
+ e.entity, e.info.skeletonScale, e.info.flipX, e.info.flipY,
+ e.info.layer, 0);
- coreModule._free(vertBase);
- coreModule._free(idxBase);
+ vOff += e.vertices.byteLength;
+ iOff += e.indices.byteLength;
+ }
+ });
}
removeEntity(entity: Entity): void {
diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.ts
index a9e52b30f..8c8dc64d2 100644
--- a/sdk/src/spine/SpineController.ts
+++ b/sdk/src/spine/SpineController.ts
@@ -6,6 +6,7 @@
import type { Entity, Vec2 } from '../types';
import type { SpineWasmModule, SpineWrappedAPI } from './SpineModuleLoader';
import { log } from '../logger';
+import { withMalloc, withScratch } from '../wasmScratch';
export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';
@@ -75,23 +76,23 @@ export class SpineModuleController {
// =========================================================================
loadSkeleton(skelData: Uint8Array | string, atlasText: string, isBinary: boolean): number {
- let ptr: number;
- let len: number;
- if (typeof skelData === 'string') {
- const encoder = new TextEncoder();
- const bytes = encoder.encode(skelData);
- len = bytes.length;
- ptr = this.raw_._malloc(len + 1);
- this.raw_.HEAPU8.set(bytes, ptr);
- this.raw_.HEAPU8[ptr + len] = 0;
- } else {
- len = skelData.length;
- ptr = this.raw_._malloc(len);
- this.raw_.HEAPU8.set(skelData, ptr);
- }
- const result = this.api_.loadSkeleton(ptr, len, atlasText, atlasText.length, isBinary);
- this.raw_._free(ptr);
- return result;
+ return withScratch(this.raw_, alloc => {
+ let ptr: number;
+ let len: number;
+ if (typeof skelData === 'string') {
+ const encoder = new TextEncoder();
+ const bytes = encoder.encode(skelData);
+ len = bytes.length;
+ ptr = alloc(len + 1);
+ this.raw_.HEAPU8.set(bytes, ptr);
+ this.raw_.HEAPU8[ptr + len] = 0;
+ } else {
+ len = skelData.length;
+ ptr = alloc(len);
+ this.raw_.HEAPU8.set(skelData, ptr);
+ }
+ return this.api_.loadSkeleton(ptr, len, atlasText, atlasText.length, isBinary);
+ });
}
getLastError(): string {
@@ -174,22 +175,20 @@ export class SpineModuleController {
}
getBonePosition(instanceId: number, boneName: string): Vec2 | null {
- const xPtr = this.raw_._malloc(4);
- const yPtr = this.raw_._malloc(4);
+ return withScratch(this.raw_, alloc => {
+ const xPtr = alloc(4);
+ const yPtr = alloc(4);
- const found = this.api_.getBonePosition(instanceId, boneName, xPtr, yPtr);
+ const found = this.api_.getBonePosition(instanceId, boneName, xPtr, yPtr);
- if (!found) {
- this.raw_._free(xPtr);
- this.raw_._free(yPtr);
- return null;
- }
+ if (!found) {
+ return null;
+ }
- const x = this.raw_.HEAPF32[xPtr >> 2];
- const y = this.raw_.HEAPF32[yPtr >> 2];
- this.raw_._free(xPtr);
- this.raw_._free(yPtr);
- return { x, y };
+ const x = this.raw_.HEAPF32[xPtr >> 2];
+ const y = this.raw_.HEAPF32[yPtr >> 2];
+ return { x, y };
+ });
}
getBoneRotation(instanceId: number, boneName: string): number {
@@ -197,19 +196,18 @@ export class SpineModuleController {
}
getBounds(instanceId: number): { x: number; y: number; width: number; height: number } {
- const ptr = this.raw_._malloc(16);
- this.api_.getBounds(instanceId, ptr, ptr + 4, ptr + 8, ptr + 12);
+ return withMalloc(this.raw_, 16, ptr => {
+ this.api_.getBounds(instanceId, ptr, ptr + 4, ptr + 8, ptr + 12);
- const f32 = this.raw_.HEAPF32;
- const base = ptr >> 2;
- const result = {
- x: f32[base],
- y: f32[base + 1],
- width: f32[base + 2],
- height: f32[base + 3],
- };
- this.raw_._free(ptr);
- return result;
+ const f32 = this.raw_.HEAPF32;
+ const base = ptr >> 2;
+ return {
+ x: f32[base],
+ y: f32[base + 1],
+ width: f32[base + 2],
+ height: f32[base + 3],
+ };
+ });
}
// =========================================================================
@@ -230,40 +228,38 @@ export class SpineModuleController {
blendMode: number;
}[] = [];
- const metaPtr = this.raw_._malloc(8);
- const texIdPtr = metaPtr;
- const blendPtr = metaPtr + 4;
-
- for (let i = 0; i < batchCount; i++) {
- const vertexCount = this.api_.getMeshBatchVertexCount(instanceId, i);
- const indexCount = this.api_.getMeshBatchIndexCount(instanceId, i);
- if (vertexCount <= 0 || indexCount <= 0) continue;
-
- const vertBytes = vertexCount * 8 * 4;
- const idxBytes = indexCount * 2;
- const vertPtr = this.raw_._malloc(vertBytes);
- const idxPtr = this.raw_._malloc(idxBytes);
-
- this.api_.getMeshBatchData(
- instanceId, i, vertPtr, idxPtr, texIdPtr, blendPtr);
-
- const vertices = new Float32Array(
- this.raw_.HEAPF32.buffer, vertPtr, vertexCount * 8);
- const indices = new Uint16Array(
- this.raw_.HEAPU8.buffer, idxPtr, indexCount);
-
- batches.push({
- vertices: new Float32Array(vertices),
- indices: new Uint16Array(indices),
- textureId: this.raw_.HEAPU32[texIdPtr >> 2],
- blendMode: this.raw_.HEAPU32[blendPtr >> 2],
- });
-
- this.raw_._free(vertPtr);
- this.raw_._free(idxPtr);
- }
-
- this.raw_._free(metaPtr);
+ withMalloc(this.raw_, 8, metaPtr => {
+ const texIdPtr = metaPtr;
+ const blendPtr = metaPtr + 4;
+
+ for (let i = 0; i < batchCount; i++) {
+ const vertexCount = this.api_.getMeshBatchVertexCount(instanceId, i);
+ const indexCount = this.api_.getMeshBatchIndexCount(instanceId, i);
+ if (vertexCount <= 0 || indexCount <= 0) continue;
+
+ const vertBytes = vertexCount * 8 * 4;
+ const idxBytes = indexCount * 2;
+ withScratch(this.raw_, alloc => {
+ const vertPtr = alloc(vertBytes);
+ const idxPtr = alloc(idxBytes);
+
+ this.api_.getMeshBatchData(
+ instanceId, i, vertPtr, idxPtr, texIdPtr, blendPtr);
+
+ const vertices = new Float32Array(
+ this.raw_.HEAPF32.buffer, vertPtr, vertexCount * 8);
+ const indices = new Uint16Array(
+ this.raw_.HEAPU8.buffer, idxPtr, indexCount);
+
+ batches.push({
+ vertices: new Float32Array(vertices),
+ indices: new Uint16Array(indices),
+ textureId: this.raw_.HEAPU32[texIdPtr >> 2],
+ blendMode: this.raw_.HEAPU32[blendPtr >> 2],
+ });
+ });
+ }
+ });
return batches;
}
diff --git a/sdk/src/tilemap/tiledLoader.ts b/sdk/src/tilemap/tiledLoader.ts
index f4e33c816..babdf9baf 100644
--- a/sdk/src/tilemap/tiledLoader.ts
+++ b/sdk/src/tilemap/tiledLoader.ts
@@ -38,6 +38,7 @@ function uploadTiledLayerTiles(entity: Entity, layer: TiledLayerData): void {
import { RigidBody, BoxCollider, CircleCollider, BodyType } from '../physics/PhysicsComponents';
import { mergeCollisionTiles } from './collisionMerge';
import { log } from '../logger';
+import { withMalloc } from '../wasmScratch';
export interface TiledChunkData {
x: number;
@@ -349,11 +350,10 @@ export async function parseTiledMap(
const encoder = new TextEncoder();
const encoded = encoder.encode(jsonString);
- const ptr = api._malloc(encoded.byteLength);
- api.HEAPU8.set(encoded, ptr);
-
- const handle = api.tiled_loadMap(ptr, encoded.byteLength);
- api._free(ptr);
+ const handle = withMalloc(api, encoded.byteLength, ptr => {
+ api.HEAPU8.set(encoded, ptr);
+ return api.tiled_loadMap(ptr, encoded.byteLength);
+ });
if (handle === 0) return null;
@@ -367,10 +367,10 @@ export async function parseTiledMap(
}
const tsjContent = await resolveExternal(source);
const tsjEncoded = encoder.encode(tsjContent);
- const tsjPtr = api._malloc(tsjEncoded.byteLength);
- api.HEAPU8.set(tsjEncoded, tsjPtr);
- const ok = api.tiled_loadExternalTileset(handle, i, tsjPtr, tsjEncoded.byteLength);
- api._free(tsjPtr);
+ const ok = withMalloc(api, tsjEncoded.byteLength, tsjPtr => {
+ api.HEAPU8.set(tsjEncoded, tsjPtr);
+ return api.tiled_loadExternalTileset(handle, i, tsjPtr, tsjEncoded.byteLength);
+ });
if (!ok) {
api.tiled_freeMap(handle);
return null;
@@ -413,20 +413,21 @@ export async function parseTiledMap(
const cw = api.tiled_getLayerChunkWidth(handle, i, c);
const ch = api.tiled_getLayerChunkHeight(handle, i, c);
const count = cw * ch;
- const ptr = api._malloc(count * 2);
- api.tiled_getLayerChunkTiles(handle, i, c, ptr, count);
- const chunkTiles = new Uint16Array(count);
- chunkTiles.set(new Uint16Array(api.HEAPU8.buffer, ptr, count));
- api._free(ptr);
+ const chunkTiles = withMalloc(api, count * 2, ptr => {
+ api.tiled_getLayerChunkTiles(handle, i, c, ptr, count);
+ const out = new Uint16Array(count);
+ out.set(new Uint16Array(api.HEAPU8.buffer, ptr, count));
+ return out;
+ });
chunks.push({ x: cx, y: cy, width: cw, height: ch, tiles: chunkTiles });
}
} else {
const tileCount = w * h;
- const tilePtr = api._malloc(tileCount * 2);
- api.tiled_getLayerTiles(handle, i, tilePtr, tileCount);
tiles = new Uint16Array(tileCount);
- tiles.set(new Uint16Array(api.HEAPU8.buffer, tilePtr, tileCount));
- api._free(tilePtr);
+ withMalloc(api, tileCount * 2, tilePtr => {
+ api.tiled_getLayerTiles(handle, i, tilePtr, tileCount);
+ tiles.set(new Uint16Array(api.HEAPU8.buffer, tilePtr, tileCount));
+ });
}
result.layers.push({
diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.ts
index a4d85f06a..d869a32e7 100644
--- a/sdk/src/tilemap/tilemapAPI.ts
+++ b/sdk/src/tilemap/tilemapAPI.ts
@@ -1,4 +1,5 @@
import type { ESEngineModule } from '../wasm';
+import { withMalloc } from '../wasmScratch';
interface TilemapModule {
tilemap_initLayer(entity: number, width: number, height: number,
@@ -137,12 +138,13 @@ export const TilemapAPI = {
},
setTiles(entity: number, tiles: Uint16Array): void {
- if (!module_) return;
+ const m = module_;
+ if (!m) return;
const bytes = tiles.byteLength;
- const ptr = module_._malloc(bytes);
- new Uint16Array(module_.HEAPU8.buffer, ptr, tiles.length).set(tiles);
- module_.tilemap_setTiles(entity, ptr, tiles.length);
- module_._free(ptr);
+ withMalloc(m, bytes, ptr => {
+ new Uint16Array(m.HEAPU8.buffer, ptr, tiles.length).set(tiles);
+ m.tilemap_setTiles(entity, ptr, tiles.length);
+ });
},
hasLayer(entity: number): boolean {
@@ -191,17 +193,18 @@ export const TilemapAPI = {
setTileAnimation(entity: number, tileId: number,
frames: { tileId: number; duration: number }[]): void {
- if (!module_ || frames.length === 0) return;
+ const m = module_;
+ if (!m || frames.length === 0) return;
const buf = new Uint32Array(frames.length * 2);
for (let i = 0; i < frames.length; i++) {
buf[i * 2] = frames[i].tileId;
buf[i * 2 + 1] = frames[i].duration;
}
const bytes = buf.byteLength;
- const ptr = module_._malloc(bytes);
- new Uint32Array(module_.HEAPU8.buffer, ptr, buf.length).set(buf);
- module_.tilemap_setTileAnimation(entity, tileId, ptr, frames.length);
- module_._free(ptr);
+ withMalloc(m, bytes, ptr => {
+ new Uint32Array(m.HEAPU8.buffer, ptr, buf.length).set(buf);
+ m.tilemap_setTileAnimation(entity, tileId, ptr, frames.length);
+ });
},
advanceAnimations(entity: number, dtMs: number): void {
@@ -238,12 +241,13 @@ export const TilemapAPI = {
setChunkTiles(entity: number, chunkX: number, chunkY: number,
tiles: Uint16Array, width: number, height: number): void {
- if (!module_) return;
+ const m = module_;
+ if (!m) return;
const bytes = tiles.byteLength;
- const ptr = module_._malloc(bytes);
- new Uint16Array(module_.HEAPU8.buffer, ptr, tiles.length).set(tiles);
- module_.tilemap_setChunkTiles(entity, chunkX, chunkY, ptr, width, height);
- module_._free(ptr);
+ withMalloc(m, bytes, ptr => {
+ new Uint16Array(m.HEAPU8.buffer, ptr, tiles.length).set(tiles);
+ m.tilemap_setChunkTiles(entity, chunkX, chunkY, ptr, width, height);
+ });
},
setGridType(entity: number, type: number): void {
diff --git a/sdk/src/timeline/TimelineUploader.ts b/sdk/src/timeline/TimelineUploader.ts
index b4d8b2db5..c6d530f5f 100644
--- a/sdk/src/timeline/TimelineUploader.ts
+++ b/sdk/src/timeline/TimelineUploader.ts
@@ -1,6 +1,7 @@
import type { ESEngineModule } from '../wasm';
import type { TimelineAsset, PropertyTrack, Track } from './TimelineTypes';
import { TrackType, InterpType } from './TimelineTypes';
+import { withScratch } from '../wasmScratch';
export { AnimTargetField, AnimTargetComponent, FIELD_MAP, COMPONENT_MAP } from './animTargets.generated';
import { AnimTargetField, AnimTargetComponent, FIELD_MAP, COMPONENT_MAP } from './animTargets.generated';
@@ -22,18 +23,18 @@ function resolveField(component: string, property: string): AnimTargetField {
return FIELD_MAP[component]?.[property] ?? AnimTargetField.CustomField;
}
-function allocString(module: ESEngineModule, str: string): [number, number] {
+function allocString(
+ module: ESEngineModule,
+ alloc: (size: number) => number,
+ str: string,
+): [number, number] {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
- const ptr = module._malloc(bytes.length);
+ const ptr = alloc(bytes.length);
new Uint8Array(module.HEAPU8.buffer, ptr, bytes.length).set(bytes);
return [ptr, bytes.length];
}
-function freePtr(module: ESEngineModule, ptr: number): void {
- module._free(ptr);
-}
-
export interface UploadedTrackInfo {
type: string;
component?: string;
@@ -98,195 +99,173 @@ function uploadPropertyTrack(module: ESEngineModule, handle: number, track: Prop
return;
}
- const [childPtr, childLen] = allocString(module, track.childPath);
-
- const fieldsPtr = module._malloc(channelCount);
- const fieldsArr = new Uint8Array(module.HEAPU8.buffer, fieldsPtr, channelCount);
- for (let i = 0; i < channelCount; i++) {
- fieldsArr[i] = resolveField(track.component, track.channels[i].property);
- }
+ withScratch(module, alloc => {
+ const [childPtr, childLen] = allocString(module, alloc, track.childPath);
- let totalKeyframes = 0;
- const counts: number[] = [];
- for (const ch of track.channels) {
- counts.push(ch.keyframes.length);
- totalKeyframes += ch.keyframes.length;
- }
+ const fieldsPtr = alloc(channelCount);
+ const fieldsArr = new Uint8Array(module.HEAPU8.buffer, fieldsPtr, channelCount);
+ for (let i = 0; i < channelCount; i++) {
+ fieldsArr[i] = resolveField(track.component, track.channels[i].property);
+ }
- const countsPtr = module._malloc(channelCount * 4);
- new Int32Array(module.HEAPU8.buffer, countsPtr, channelCount).set(counts);
-
- const dataPtr = module._malloc(totalKeyframes * 5 * 4);
- const dataArr = new Float32Array(module.HEAPU8.buffer, dataPtr, totalKeyframes * 5);
- let offset = 0;
- for (const ch of track.channels) {
- for (const kf of ch.keyframes) {
- dataArr[offset++] = kf.time;
- dataArr[offset++] = kf.value;
- dataArr[offset++] = kf.inTangent;
- dataArr[offset++] = kf.outTangent;
- dataArr[offset++] = interpTypeToNum(kf.interpolation);
+ let totalKeyframes = 0;
+ const counts: number[] = [];
+ for (const ch of track.channels) {
+ counts.push(ch.keyframes.length);
+ totalKeyframes += ch.keyframes.length;
}
- }
- module._tl_addPropertyTrack(handle, childPtr, childLen, component,
- fieldsPtr, channelCount, dataPtr, countsPtr);
+ const countsPtr = alloc(channelCount * 4);
+ new Int32Array(module.HEAPU8.buffer, countsPtr, channelCount).set(counts);
+
+ const dataPtr = alloc(totalKeyframes * 5 * 4);
+ const dataArr = new Float32Array(module.HEAPU8.buffer, dataPtr, totalKeyframes * 5);
+ let offset = 0;
+ for (const ch of track.channels) {
+ for (const kf of ch.keyframes) {
+ dataArr[offset++] = kf.time;
+ dataArr[offset++] = kf.value;
+ dataArr[offset++] = kf.inTangent;
+ dataArr[offset++] = kf.outTangent;
+ dataArr[offset++] = interpTypeToNum(kf.interpolation);
+ }
+ }
- freePtr(module, childPtr);
- freePtr(module, fieldsPtr);
- freePtr(module, countsPtr);
- freePtr(module, dataPtr);
+ module._tl_addPropertyTrack(handle, childPtr, childLen, component,
+ fieldsPtr, channelCount, dataPtr, countsPtr);
+ });
}
function uploadCustomPropertyTrack(module: ESEngineModule, handle: number, track: PropertyTrack): void {
const channelCount = track.channels.length;
- const [childPtr, childLen] = allocString(module, track.childPath);
- const [compPtr, compLen] = allocString(module, track.component);
-
- const pathStrings = track.channels.map(c => new TextEncoder().encode(c.property));
- let totalPathBytes = 0;
- for (const p of pathStrings) totalPathBytes += p.length;
+ withScratch(module, alloc => {
+ const [childPtr, childLen] = allocString(module, alloc, track.childPath);
+ const [compPtr, compLen] = allocString(module, alloc, track.component);
- const fieldPathsPtr = module._malloc(totalPathBytes);
- let pathOffset = 0;
- for (const p of pathStrings) {
- new Uint8Array(module.HEAPU8.buffer, fieldPathsPtr + pathOffset, p.length).set(p);
- pathOffset += p.length;
- }
+ const pathStrings = track.channels.map(c => new TextEncoder().encode(c.property));
+ let totalPathBytes = 0;
+ for (const p of pathStrings) totalPathBytes += p.length;
- const fieldPathLensPtr = module._malloc(channelCount * 4);
- new Int32Array(module.HEAPU8.buffer, fieldPathLensPtr, channelCount).set(pathStrings.map(p => p.length));
+ const fieldPathsPtr = alloc(totalPathBytes);
+ let pathOffset = 0;
+ for (const p of pathStrings) {
+ new Uint8Array(module.HEAPU8.buffer, fieldPathsPtr + pathOffset, p.length).set(p);
+ pathOffset += p.length;
+ }
- let totalKeyframes = 0;
- const counts: number[] = [];
- for (const ch of track.channels) {
- counts.push(ch.keyframes.length);
- totalKeyframes += ch.keyframes.length;
- }
+ const fieldPathLensPtr = alloc(channelCount * 4);
+ new Int32Array(module.HEAPU8.buffer, fieldPathLensPtr, channelCount).set(pathStrings.map(p => p.length));
- const countsPtr = module._malloc(channelCount * 4);
- new Int32Array(module.HEAPU8.buffer, countsPtr, channelCount).set(counts);
-
- const dataPtr = module._malloc(totalKeyframes * 5 * 4);
- const dataArr = new Float32Array(module.HEAPU8.buffer, dataPtr, totalKeyframes * 5);
- let dOffset = 0;
- for (const ch of track.channels) {
- for (const kf of ch.keyframes) {
- dataArr[dOffset++] = kf.time;
- dataArr[dOffset++] = kf.value;
- dataArr[dOffset++] = kf.inTangent;
- dataArr[dOffset++] = kf.outTangent;
- dataArr[dOffset++] = interpTypeToNum(kf.interpolation);
+ let totalKeyframes = 0;
+ const counts: number[] = [];
+ for (const ch of track.channels) {
+ counts.push(ch.keyframes.length);
+ totalKeyframes += ch.keyframes.length;
}
- }
- module._tl_addCustomPropertyTrack(handle, childPtr, childLen, compPtr, compLen,
- fieldPathsPtr, fieldPathLensPtr, channelCount,
- dataPtr, countsPtr);
+ const countsPtr = alloc(channelCount * 4);
+ new Int32Array(module.HEAPU8.buffer, countsPtr, channelCount).set(counts);
+
+ const dataPtr = alloc(totalKeyframes * 5 * 4);
+ const dataArr = new Float32Array(module.HEAPU8.buffer, dataPtr, totalKeyframes * 5);
+ let dOffset = 0;
+ for (const ch of track.channels) {
+ for (const kf of ch.keyframes) {
+ dataArr[dOffset++] = kf.time;
+ dataArr[dOffset++] = kf.value;
+ dataArr[dOffset++] = kf.inTangent;
+ dataArr[dOffset++] = kf.outTangent;
+ dataArr[dOffset++] = interpTypeToNum(kf.interpolation);
+ }
+ }
- freePtr(module, childPtr);
- freePtr(module, compPtr);
- freePtr(module, fieldPathsPtr);
- freePtr(module, fieldPathLensPtr);
- freePtr(module, countsPtr);
- freePtr(module, dataPtr);
+ module._tl_addCustomPropertyTrack(handle, childPtr, childLen, compPtr, compLen,
+ fieldPathsPtr, fieldPathLensPtr, channelCount,
+ dataPtr, countsPtr);
+ });
}
function uploadSpineTrack(module: ESEngineModule, handle: number, track: Track): void {
if (track.type !== TrackType.Spine) return;
- const [childPtr, childLen] = allocString(module, track.childPath);
- const clipCount = track.clips.length;
-
- const floatsPtr = module._malloc(clipCount * 4 * 4);
- const floats = new Float32Array(module.HEAPU8.buffer, floatsPtr, clipCount * 4);
- const animPtrsPtr = module._malloc(clipCount * 4);
- const animPtrs = new Uint32Array(module.HEAPU8.buffer, animPtrsPtr, clipCount);
- const animLensPtr = module._malloc(clipCount * 4);
- const animLens = new Int32Array(module.HEAPU8.buffer, animLensPtr, clipCount);
-
- const animStrPtrs: number[] = [];
- for (let i = 0; i < clipCount; i++) {
- const clip = track.clips[i];
- floats[i * 4] = clip.start;
- floats[i * 4 + 1] = clip.duration;
- floats[i * 4 + 2] = clip.speed;
- floats[i * 4 + 3] = clip.loop ? 1.0 : 0.0;
- const [aPtr, aLen] = allocString(module, clip.animation);
- animPtrs[i] = aPtr;
- animLens[i] = aLen;
- animStrPtrs.push(aPtr);
- }
-
- module._tl_addSpineTrack(handle, childPtr, childLen,
- floatsPtr, animPtrsPtr, animLensPtr, clipCount, track.blendIn);
+ withScratch(module, alloc => {
+ const [childPtr, childLen] = allocString(module, alloc, track.childPath);
+ const clipCount = track.clips.length;
+
+ const floatsPtr = alloc(clipCount * 4 * 4);
+ const floats = new Float32Array(module.HEAPU8.buffer, floatsPtr, clipCount * 4);
+ const animPtrsPtr = alloc(clipCount * 4);
+ const animPtrs = new Uint32Array(module.HEAPU8.buffer, animPtrsPtr, clipCount);
+ const animLensPtr = alloc(clipCount * 4);
+ const animLens = new Int32Array(module.HEAPU8.buffer, animLensPtr, clipCount);
+
+ for (let i = 0; i < clipCount; i++) {
+ const clip = track.clips[i];
+ floats[i * 4] = clip.start;
+ floats[i * 4 + 1] = clip.duration;
+ floats[i * 4 + 2] = clip.speed;
+ floats[i * 4 + 3] = clip.loop ? 1.0 : 0.0;
+ const [aPtr, aLen] = allocString(module, alloc, clip.animation);
+ animPtrs[i] = aPtr;
+ animLens[i] = aLen;
+ }
- freePtr(module, childPtr);
- freePtr(module, floatsPtr);
- freePtr(module, animPtrsPtr);
- freePtr(module, animLensPtr);
- for (const p of animStrPtrs) freePtr(module, p);
+ module._tl_addSpineTrack(handle, childPtr, childLen,
+ floatsPtr, animPtrsPtr, animLensPtr, clipCount, track.blendIn);
+ });
}
function uploadAudioTrack(module: ESEngineModule, handle: number, track: Track): void {
if (track.type !== TrackType.Audio) return;
- const [childPtr, childLen] = allocString(module, track.childPath);
- const eventCount = track.events.length;
-
- const floatsPtr = module._malloc(eventCount * 2 * 4);
- const floats = new Float32Array(module.HEAPU8.buffer, floatsPtr, eventCount * 2);
- const clipPtrsPtr = module._malloc(eventCount * 4);
- const clipPtrs = new Uint32Array(module.HEAPU8.buffer, clipPtrsPtr, eventCount);
- const clipLensPtr = module._malloc(eventCount * 4);
- const clipLens = new Int32Array(module.HEAPU8.buffer, clipLensPtr, eventCount);
-
- const strPtrs: number[] = [];
- for (let i = 0; i < eventCount; i++) {
- const evt = track.events[i];
- floats[i * 2] = evt.time;
- floats[i * 2 + 1] = evt.volume;
- const [cPtr, cLen] = allocString(module, evt.clip);
- clipPtrs[i] = cPtr;
- clipLens[i] = cLen;
- strPtrs.push(cPtr);
- }
-
- module._tl_addAudioTrack(handle, childPtr, childLen,
- floatsPtr, clipPtrsPtr, clipLensPtr, eventCount);
+ withScratch(module, alloc => {
+ const [childPtr, childLen] = allocString(module, alloc, track.childPath);
+ const eventCount = track.events.length;
+
+ const floatsPtr = alloc(eventCount * 2 * 4);
+ const floats = new Float32Array(module.HEAPU8.buffer, floatsPtr, eventCount * 2);
+ const clipPtrsPtr = alloc(eventCount * 4);
+ const clipPtrs = new Uint32Array(module.HEAPU8.buffer, clipPtrsPtr, eventCount);
+ const clipLensPtr = alloc(eventCount * 4);
+ const clipLens = new Int32Array(module.HEAPU8.buffer, clipLensPtr, eventCount);
+
+ for (let i = 0; i < eventCount; i++) {
+ const evt = track.events[i];
+ floats[i * 2] = evt.time;
+ floats[i * 2 + 1] = evt.volume;
+ const [cPtr, cLen] = allocString(module, alloc, evt.clip);
+ clipPtrs[i] = cPtr;
+ clipLens[i] = cLen;
+ }
- freePtr(module, childPtr);
- freePtr(module, floatsPtr);
- freePtr(module, clipPtrsPtr);
- freePtr(module, clipLensPtr);
- for (const p of strPtrs) freePtr(module, p);
+ module._tl_addAudioTrack(handle, childPtr, childLen,
+ floatsPtr, clipPtrsPtr, clipLensPtr, eventCount);
+ });
}
function uploadActivationTrack(module: ESEngineModule, handle: number, track: Track): void {
if (track.type !== TrackType.Activation) return;
- const [childPtr, childLen] = allocString(module, track.childPath);
-
- const rangesPtr = module._malloc(track.ranges.length * 2 * 4);
- const rangesArr = new Float32Array(module.HEAPU8.buffer, rangesPtr, track.ranges.length * 2);
- for (let i = 0; i < track.ranges.length; i++) {
- rangesArr[i * 2] = track.ranges[i].start;
- rangesArr[i * 2 + 1] = track.ranges[i].end;
- }
-
- module._tl_addActivationTrack(handle, childPtr, childLen,
- rangesPtr, track.ranges.length);
+ withScratch(module, alloc => {
+ const [childPtr, childLen] = allocString(module, alloc, track.childPath);
+
+ const rangesPtr = alloc(track.ranges.length * 2 * 4);
+ const rangesArr = new Float32Array(module.HEAPU8.buffer, rangesPtr, track.ranges.length * 2);
+ for (let i = 0; i < track.ranges.length; i++) {
+ rangesArr[i * 2] = track.ranges[i].start;
+ rangesArr[i * 2 + 1] = track.ranges[i].end;
+ }
- freePtr(module, childPtr);
- freePtr(module, rangesPtr);
+ module._tl_addActivationTrack(handle, childPtr, childLen,
+ rangesPtr, track.ranges.length);
+ });
}
function uploadSpriteAnimTrack(module: ESEngineModule, handle: number, track: Track): void {
if (track.type !== TrackType.SpriteAnim) return;
- const [childPtr, childLen] = allocString(module, track.childPath);
- const [clipPtr, clipLen] = allocString(module, track.clip);
-
- module._tl_addSpriteAnimTrack(handle, childPtr, childLen,
- clipPtr, clipLen, track.startTime);
+ withScratch(module, alloc => {
+ const [childPtr, childLen] = allocString(module, alloc, track.childPath);
+ const [clipPtr, clipLen] = allocString(module, alloc, track.clip);
- freePtr(module, childPtr);
- freePtr(module, clipPtr);
+ module._tl_addSpriteAnimTrack(handle, childPtr, childLen,
+ clipPtr, clipLen, track.startTime);
+ });
}
diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.ts
index 9fd6f95df..c09b14728 100644
--- a/sdk/src/ui/TextRenderer.ts
+++ b/sdk/src/ui/TextRenderer.ts
@@ -15,6 +15,7 @@ import { parseRichText } from './RichTextParser';
import { createFontSet, fontIndex, layoutRichText, measureLayoutWidth, type LayoutLine } from './RichTextLayout';
import type { ImageResolver } from './ImageResolver';
import { log } from '../logger';
+import { withMalloc } from '../wasmScratch';
interface SizedRect {
size: { x: number; y: number };
@@ -328,12 +329,10 @@ export class TextRenderer {
const pixels = new Uint8Array(imageData.data.buffer);
const rm = requireResourceManager();
- const ptr = this.module._malloc(pixels.length);
- this.module.HEAPU8.set(pixels, ptr);
-
- const textureHandle = rm.createTexture(width, height, ptr, pixels.length, 1, true);
-
- this.module._free(ptr);
+ const textureHandle = withMalloc(this.module, pixels.length, ptr => {
+ this.module.HEAPU8.set(pixels, ptr);
+ return rm.createTexture(width, height, ptr, pixels.length, 1, true);
+ });
return { textureHandle, width, height };
}
diff --git a/sdk/src/wasmScratch.ts b/sdk/src/wasmScratch.ts
new file mode 100644
index 000000000..95855c2b0
--- /dev/null
+++ b/sdk/src/wasmScratch.ts
@@ -0,0 +1,62 @@
+/**
+ * @file wasmScratch.ts
+ * @brief Exception-safe transient allocation on the WASM heap.
+ *
+ * @details The boundary repeatedly does `ptr = _malloc(n); …write/​call…; _free(ptr)`.
+ * When the intervening work throws (a validation error, a module
+ * abort, an out-of-bounds write), the `_free` is skipped and the WASM
+ * heap leaks permanently. {@link withScratch} makes that structurally
+ * impossible: every allocation taken from its `alloc` callback is freed
+ * when the callback returns OR throws.
+ *
+ * The callback MUST be synchronous — do not `await` between alloc and
+ * the implicit free, or the buffer is freed while still in use.
+ */
+
+/** Minimal slice of an emscripten module: just the heap allocator. */
+export interface WasmAllocator {
+ _malloc(size: number): number;
+ _free(ptr: number): void;
+}
+
+/**
+ * Run `fn` with a scratch allocator; free everything it allocated on exit,
+ * whether `fn` returns normally or throws. Frees in reverse allocation order.
+ *
+ * @example
+ * const offset = withScratch(module, alloc => {
+ * const ptr = alloc(pixels.length);
+ * module.HEAPU8.set(pixels, ptr);
+ * return module.uploadTexture(ptr, pixels.length); // may throw — ptr still freed
+ * });
+ */
+export function withScratch<R>(
+ mod: WasmAllocator,
+ fn: (alloc: (size: number) => number) => R,
+): R {
+ const ptrs: number[] = [];
+ const alloc = (size: number): number => {
+ const p = mod._malloc(size);
+ if (p) ptrs.push(p);
+ return p;
+ };
+ try {
+ return fn(alloc);
+ } finally {
+ for (let i = ptrs.length - 1; i >= 0; i--) {
+ mod._free(ptrs[i]!);
+ }
+ }
+}
+
+/**
+ * Convenience for the single-buffer case: allocate `size` bytes, run `fn` with
+ * the pointer, and free it on exit (normal or throw).
+ */
+export function withMalloc<R>(
+ mod: WasmAllocator,
+ size: number,
+ fn: (ptr: number) => R,
+): R {
+ return withScratch(mod, alloc => fn(alloc(size)));
+}
diff --git a/sdk/tests/wasm-scratch.test.ts b/sdk/tests/wasm-scratch.test.ts
new file mode 100644
index 000000000..78cf4eb94
--- /dev/null
+++ b/sdk/tests/wasm-scratch.test.ts
@@ -0,0 +1,81 @@
+/**
+ * @file wasm-scratch.test.ts
+ * @brief withScratch frees every allocation on normal return AND on throw.
+ */
+import { describe, it, expect } from 'vitest';
+import { withScratch, withMalloc, type WasmAllocator } from '../src/wasmScratch';
+
+/** Fake allocator that hands out increasing pointers and records frees. */
+function makeAllocator() {
+ let next = 8; // non-zero base
+ const freed: number[] = [];
+ const live = new Set<number>();
+ const mod: WasmAllocator = {
+ _malloc(size: number) {
+ const p = next;
+ next += Math.max(size, 1);
+ live.add(p);
+ return p;
+ },
+ _free(ptr: number) {
+ freed.push(ptr);
+ live.delete(ptr);
+ },
+ };
+ return { mod, freed, live };
+}
+
+describe('withScratch', () => {
+ it('frees a single allocation after normal return', () => {
+ const { mod, live } = makeAllocator();
+ const r = withScratch(mod, alloc => {
+ const p = alloc(64);
+ expect(p).toBeGreaterThan(0);
+ return p;
+ });
+ expect(r).toBeGreaterThan(0);
+ expect(live.size).toBe(0);
+ });
+
+ it('frees all allocations in reverse order', () => {
+ const { mod, freed, live } = makeAllocator();
+ let a = 0, b = 0, c = 0;
+ withScratch(mod, alloc => {
+ a = alloc(16);
+ b = alloc(16);
+ c = alloc(16);
+ });
+ expect(live.size).toBe(0);
+ expect(freed).toEqual([c, b, a]);
+ });
+
+ it('frees everything even when the callback throws', () => {
+ const { mod, live } = makeAllocator();
+ expect(() => {
+ withScratch(mod, alloc => {
+ alloc(16);
+ alloc(16);
+ throw new Error('boom');
+ });
+ }).toThrowError('boom');
+ expect(live.size).toBe(0);
+ });
+
+ it('propagates the callback return value', () => {
+ const { mod } = makeAllocator();
+ const r = withScratch(mod, () => 'result');
+ expect(r).toBe('result');
+ });
+
+ it('withMalloc allocates one buffer and frees it on throw', () => {
+ const { mod, live, freed } = makeAllocator();
+ expect(() => {
+ withMalloc(mod, 128, ptr => {
+ expect(ptr).toBeGreaterThan(0);
+ throw new Error('mid-use');
+ });
+ }).toThrowError('mid-use');
+ expect(live.size).toBe(0);
+ expect(freed.length).toBe(1);
+ });
+});