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 heap on the device, so bulk data crosses the same way it does on the web

yhh31a509a02d7f
diff --git a/native/host/Bindings.hpp b/native/host/Bindings.hpp
index c1ba121c0..a861d8afa 100644
--- a/native/host/Bindings.hpp
+++ b/native/host/Bindings.hpp
@@ -29,6 +29,11 @@
namespace eshost {
+/** The linear heap bulk data crosses through — `es_heap` / `es_malloc` / `es_free`.
+ * What makes a `…Ptr` argument mean the same thing here as it does on the web
+ * (see heap.hpp), so an SDK subsystem module needs no native-only backend. */
+void registerHeapBindings(HostState& h, JSValue global);
+
/** Entity + hierarchy: the base Registry surface the SDK's World drives. */
void registerEcsBindings(HostState& h, JSValue global);
diff --git a/native/host/EsnShim.cpp b/native/host/EsnShim.cpp
index 1b17d9fa7..734860dfe 100644
--- a/native/host/EsnShim.cpp
+++ b/native/host/EsnShim.cpp
@@ -18,6 +18,9 @@
#include "esn_shim.hpp"
#include "Runtime.hpp"
+#include "heap.hpp"
+
+#include <cstring>
using namespace esengine;
@@ -69,13 +72,53 @@ void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, i
JS_FreeValue(ctx, arr);
}
-// The generated wrappers for entry points that take a `uintptr_t` buffer read
-// their bytes through this: on the web that argument is a wasm heap offset, here
-// it is memory the wrapper owns for the duration of the call.
void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out) {
eshost::readByteSource(ctx, v, out);
}
+// — The heap a `uintptr_t` argument addresses. A number IS the offset (the SDK
+// wrote through the shared ArrayBuffer); anything else is a buffer handed
+// straight across, which we copy into the arena so the binding still receives
+// memory inside the region BoundarySpan validates against. —
+
+uint32_t esn_argOffset(JSContext* ctx, JSValueConst v) {
+ if (JS_IsNumber(v)) {
+ uint32_t offset = 0;
+ JS_ToUint32(ctx, &offset, v);
+ return offset;
+ }
+ std::vector<esengine::u8> bytes;
+ eshost::readByteSource(ctx, v, bytes);
+ if (bytes.empty()) return 0;
+ const uint32_t offset = eshost::heapAlloc(bytes.size());
+ void* dst = eshost::heapPtr(offset, bytes.size());
+ if (!dst) return 0;
+ std::memcpy(dst, bytes.data(), bytes.size());
+ return offset;
+}
+
+void esn_argRelease(JSContext* ctx, JSValueConst v, uint32_t offset) {
+ if (JS_IsNumber(v)) return; // the caller owns it
+ eshost::heapFree(offset);
+}
+
+uintptr_t esn_heapAddr(uint32_t offset) {
+ return reinterpret_cast<uintptr_t>(eshost::heapPtr(offset, 0));
+}
+
+uint32_t esn_publish(EsnSlot& slot, const void* src, size_t bytes) {
+ if (!src || bytes == 0) return 0;
+ if (bytes > slot.capacity) {
+ eshost::heapFree(slot.offset);
+ slot.offset = eshost::heapAlloc(bytes);
+ slot.capacity = slot.offset ? bytes : 0;
+ }
+ void* dst = eshost::heapPtr(slot.offset, bytes);
+ if (!dst) return 0;
+ std::memcpy(dst, src, bytes);
+ return slot.offset;
+}
+
JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size) {
return JS_NewArrayBuffer(ctx, reinterpret_cast<uint8_t*>(ptr), size, nullptr, nullptr, false);
}
diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cpp
index b1c48b051..a9f9d512c 100644
--- a/native/host/Runtime.cpp
+++ b/native/host/Runtime.cpp
@@ -339,7 +339,9 @@ void initRuntime(HostState& h) {
JS_SetPropertyStr(h.js, perf, "now", JS_NewCFunction(h.js, js_performanceNow, "now", 0));
JS_SetPropertyStr(h.js, global, "performance", perf);
- // The es_* surface, one pillar at a time (see Bindings.hpp).
+ // The es_* surface, one pillar at a time (see Bindings.hpp). The heap comes
+ // first: it is what the generated entry points marshal buffers through.
+ registerHeapBindings(h, global);
registerEcsBindings(h, global);
registerRenderBindings(h, global);
registerAssetBindings(h, global);
diff --git a/native/host/bindings/HeapBindings.cpp b/native/host/bindings/HeapBindings.cpp
new file mode 100644
index 000000000..d568ed023
--- /dev/null
+++ b/native/host/bindings/HeapBindings.cpp
@@ -0,0 +1,192 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file HeapBindings.cpp
+ * @brief The linear heap a `uintptr_t` argument addresses on a device.
+ * @details See heap.hpp for why this exists. The allocator is a plain implicit
+ * block list with first fit and lazy coalescing — the traffic is a
+ * handful of scratch buffers per frame (tile arrays, polygon vertices,
+ * the readback slots), not a general-purpose workload, and being simple
+ * enough to audit matters more here than fitting a pathological pattern:
+ * a wrong offset is memory corruption on the wrong side of the boundary.
+ *
+ * Registering the arena with `BoundarySpan` is the point of having ONE
+ * region: a JS-supplied span is range-checked on a device exactly as it
+ * is against wasm's linear memory, instead of degrading to a null check.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "Bindings.hpp"
+#include "heap.hpp"
+#include "esn_shim.hpp"
+
+#include "esengine/bindings/BoundarySpan.hpp"
+
+#include <cstdlib>
+#include <cstring>
+
+namespace eshost {
+namespace {
+
+// 32 MiB of address space. It has to hold the largest single buffer any
+// subsystem marshals — a full tilemap layer's tile array is the big one — and
+// pages that are never written never become resident, so the reservation is
+// cheap. Exhaustion is logged, never silent.
+constexpr size_t kHeapBytes = 32u * 1024u * 1024u;
+
+// Payload alignment. 8 keeps a Float64Array view valid at any allocated offset,
+// which is also what emscripten's malloc guarantees.
+constexpr uint32_t kAlign = 8;
+
+/** Block header. `size` is the payload size; the payload follows immediately, so
+ * the next header sits at `header + 8 + size`. */
+struct Block {
+ uint32_t size;
+ uint32_t used;
+};
+
+uint8_t* g_base = nullptr;
+size_t g_highWater = 0;
+bool g_failed = false;
+
+Block* blockAt(uint32_t headerOffset) {
+ return reinterpret_cast<Block*>(g_base + headerOffset);
+}
+
+uint32_t roundUp(size_t n) {
+ return static_cast<uint32_t>((n + kAlign - 1) & ~static_cast<size_t>(kAlign - 1));
+}
+
+} // namespace
+
+uint8_t* heapBase() {
+ if (g_base || g_failed) return g_base;
+ g_base = static_cast<uint8_t*>(std::malloc(kHeapBytes));
+ if (!g_base) {
+ g_failed = true;
+ ESHOST_LOGE("heap: could not reserve %zu bytes — subsystems that marshal buffers "
+ "(physics, tilemaps, spine) will not run", kHeapBytes);
+ return nullptr;
+ }
+ // One free block spanning everything. Offset 0 is the first header, so no
+ // payload can ever live there and 0 keeps its null meaning.
+ Block* first = blockAt(0);
+ first->size = static_cast<uint32_t>(kHeapBytes - sizeof(Block));
+ first->used = 0;
+ // Same guarantee as the sandbox: a span from JS must land inside this region.
+ esengine::setBoundaryRegion(reinterpret_cast<uintptr_t>(g_base), kHeapBytes);
+ ESHOST_LOGI("heap: %zu KiB arena at %p (JS sees it as one ArrayBuffer)",
+ kHeapBytes / 1024, static_cast<void*>(g_base));
+ return g_base;
+}
+
+size_t heapSize() { return kHeapBytes; }
+
+size_t heapHighWater() { return g_highWater; }
+
+uint32_t heapAlloc(size_t bytes) {
+ if (bytes == 0 || !heapBase()) return 0;
+ const uint32_t want = roundUp(bytes);
+ if (want > kHeapBytes) return 0;
+
+ uint32_t offset = 0;
+ while (offset + sizeof(Block) <= kHeapBytes) {
+ Block* block = blockAt(offset);
+ if (!block->used) {
+ // Coalesce free neighbours as we pass them, which is the only
+ // defragmentation this allocator does — enough for scratch traffic
+ // that frees what it allocates.
+ for (;;) {
+ const uint32_t nextHeader = offset + static_cast<uint32_t>(sizeof(Block)) + block->size;
+ if (nextHeader + sizeof(Block) > kHeapBytes) break;
+ Block* next = blockAt(nextHeader);
+ if (next->used) break;
+ block->size += static_cast<uint32_t>(sizeof(Block)) + next->size;
+ }
+ if (block->size >= want) {
+ // Split when the tail can still hold a header plus one aligned unit.
+ if (block->size - want >= sizeof(Block) + kAlign) {
+ const uint32_t tail = offset + static_cast<uint32_t>(sizeof(Block)) + want;
+ Block* rest = blockAt(tail);
+ rest->size = block->size - want - static_cast<uint32_t>(sizeof(Block));
+ rest->used = 0;
+ block->size = want;
+ }
+ block->used = 1;
+ const uint32_t payload = offset + static_cast<uint32_t>(sizeof(Block));
+ if (payload + block->size > g_highWater) g_highWater = payload + block->size;
+ return payload;
+ }
+ }
+ offset += static_cast<uint32_t>(sizeof(Block)) + block->size;
+ }
+ ESHOST_LOGE("heap: out of memory (wanted %u bytes, arena is %zu KiB, high water %zu KiB)",
+ want, kHeapBytes / 1024, g_highWater / 1024);
+ return 0;
+}
+
+void heapFree(uint32_t offset) {
+ if (offset == 0 || !g_base) return;
+ if (offset < sizeof(Block) || offset >= kHeapBytes || (offset % kAlign) != 0) {
+ ESHOST_LOGE("heap: free(%u) is not an allocated offset", offset);
+ return;
+ }
+ Block* block = blockAt(offset - static_cast<uint32_t>(sizeof(Block)));
+ if (!block->used) {
+ ESHOST_LOGE("heap: double free at offset %u", offset);
+ return;
+ }
+ block->used = 0;
+}
+
+void* heapPtr(uint32_t offset, size_t bytes) {
+ if (offset == 0 || !g_base) return nullptr;
+ if (offset >= kHeapBytes || bytes > kHeapBytes - offset) {
+ ESHOST_LOGE("heap: offset %u (+%zu bytes) is outside the arena", offset, bytes);
+ return nullptr;
+ }
+ return g_base + offset;
+}
+
+namespace {
+
+// es_heap() -> ArrayBuffer over the whole arena. The SDK builds its typed-array
+// views on this once (`createNativeHeap`); the arena never moves, so unlike a
+// growable wasm heap the views stay valid for the process lifetime.
+JSValue js_heap(JSContext* ctx, JSValueConst, int, JSValueConst*) {
+ uint8_t* base = heapBase();
+ if (!base) return JS_NULL;
+ return esn_arraybuffer(ctx, base, heapSize());
+}
+
+// es_malloc(bytes) -> offset (0 when full, which reads as null like _malloc).
+JSValue js_malloc(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
+ if (argc < 1) return JS_NewUint32(ctx, 0);
+ int64_t bytes = 0;
+ JS_ToInt64(ctx, &bytes, argv[0]);
+ if (bytes <= 0) return JS_NewUint32(ctx, 0);
+ return JS_NewUint32(ctx, heapAlloc(static_cast<size_t>(bytes)));
+}
+
+// es_free(offset).
+JSValue js_free(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
+ if (argc < 1) return JS_UNDEFINED;
+ uint32_t offset = 0;
+ JS_ToUint32(ctx, &offset, argv[0]);
+ heapFree(offset);
+ return JS_UNDEFINED;
+}
+
+} // namespace
+
+void registerHeapBindings(HostState& h, JSValue global) {
+ JS_SetPropertyStr(h.js, global, "es_heap", JS_NewCFunction(h.js, js_heap, "es_heap", 0));
+ JS_SetPropertyStr(h.js, global, "es_malloc", JS_NewCFunction(h.js, js_malloc, "es_malloc", 1));
+ JS_SetPropertyStr(h.js, global, "es_free", JS_NewCFunction(h.js, js_free, "es_free", 1));
+}
+
+} // namespace eshost
diff --git a/native/host/esn_shim.hpp b/native/host/esn_shim.hpp
index 04af3aca4..6a6e15dab 100644
--- a/native/host/esn_shim.hpp
+++ b/native/host/esn_shim.hpp
@@ -14,6 +14,7 @@ extern "C" {
#include "esengine/resource/ResourceManager.hpp" // esengine::resource::ResourceManager
#include "esengine/core/Types.hpp" // esengine::u8
+#include <cstdint>
#include <vector>
// --- provided by the host (host/Runtime.cpp) ---------------------------------
@@ -32,11 +33,38 @@ void esn_getvec(JSContext* ctx, JSValueConst obj, const char* key, float* dst, i
// Wrap [ptr, ptr+size) as a zero-copy JS ArrayBuffer (native owns the memory).
JSValue esn_arraybuffer(JSContext* ctx, void* ptr, size_t size);
// Read a JS byte source (ArrayBuffer, typed-array view, or plain number array)
-// into `out`. Backs the generated wrappers for entry points that take a
-// `uintptr_t` buffer: on the web that is a wasm heap offset, here it is real
-// memory the wrapper owns for the duration of the call.
+// into `out`.
void esn_bytes(JSContext* ctx, JSValueConst v, std::vector<esengine::u8>& out);
+// --- the heap a `uintptr_t` argument addresses (see host/heap.hpp) ------------
+// A generated wrapper reads such an argument through this pair, so the entry
+// points that marshal bulk data — tile arrays, polygon vertices, spine meshes —
+// mean the same thing on both platforms.
+//
+// a number → an offset into the host's heap arena, exactly as it is an offset
+// into wasm's linear memory on the web. Shared memory, so an entry
+// point that WRITES into the buffer is seen by JS.
+// a JS buffer → copied into the arena for the duration of the call, for callers
+// that hand bytes straight across (the renderer's native backend).
+//
+// Returns 0 when there is nothing to pass, which every binding treats as null.
+uint32_t esn_argOffset(JSContext* ctx, JSValueConst v);
+// Release what esn_argOffset copied in. A no-op when the argument was an offset.
+void esn_argRelease(JSContext* ctx, JSValueConst v, uint32_t offset);
+// Resolve a heap offset to the real address a binding takes, or 0 if out of range.
+uintptr_t esn_heapAddr(uint32_t offset);
+
+// One entry point's readback slot. An entry point that RETURNS a pointer hands
+// back memory the module owns (a static buffer, a vector's storage) which is not
+// in the heap JS reads; the wrapper copies the `@heapreturn` byte count into its
+// own slot and answers that offset. One slot per entry point — so two consecutive
+// readbacks never clobber each other — grown on demand, never shrunk.
+struct EsnSlot {
+ uint32_t offset = 0;
+ size_t capacity = 0;
+};
+uint32_t esn_publish(EsnSlot& slot, const void* src, size_t bytes);
+
// --- provided by the generated files -----------------------------------------
// Components (NativeBindings.generated.cpp) and the engine's binding entry
// points (NativeFunctionBindings.generated.cpp), from the same declarations the
diff --git a/native/host/heap.hpp b/native/host/heap.hpp
new file mode 100644
index 000000000..1ecd3944c
--- /dev/null
+++ b/native/host/heap.hpp
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file heap.hpp
+ * @brief The host's linear heap — what a `uintptr_t` argument means on a device.
+ * @details Half the engine's binding surface marshals bulk data as a pointer plus
+ * a count: tile arrays, polygon vertices, body transforms, spine meshes.
+ * On the web that pointer is an offset into wasm's linear memory, which JS
+ * holds as `Module.HEAPF32` and writes through directly. A native host had
+ * no such thing, so every one of those entry points was web-only — the
+ * reason physics, tilemaps and spine could not run on a device.
+ *
+ * This is that memory: ONE arena the host allocates and JS sees as a
+ * zero-copy `ArrayBuffer`, with `malloc`/`free` over it. Offsets into it
+ * are what cross the boundary, so an SDK module interface
+ * (`HEAPF32` + `_malloc` + a `…Ptr` argument) is satisfied natively by the
+ * same code that satisfies it on the web — no per-subsystem backend.
+ *
+ * It is also what lets `BoundarySpan` do its real job here: the arena is a
+ * bounded region, so a JS-supplied span is range-checked on a device
+ * exactly as it is in the sandbox (see `setBoundaryRegion`).
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace eshost {
+
+/**
+ * Reserve the arena on first use and answer its base. Null only if the
+ * reservation failed, which is fatal for any subsystem that marshals buffers.
+ * Untouched pages never become resident, so the reservation costs address space,
+ * not memory.
+ */
+uint8_t* heapBase();
+
+/** Arena size in bytes (constant for the process lifetime, so JS views built over
+ * it stay valid — unlike a growable wasm heap). */
+size_t heapSize();
+
+/**
+ * Allocate @p bytes and return its OFFSET, or 0 when the arena is full (0 is
+ * never a valid allocation, so it reads as null the way `_malloc` does). First
+ * fit over an implicit block list, coalescing free neighbours as it scans.
+ */
+uint32_t heapAlloc(size_t bytes);
+
+/** Release an offset from {@link heapAlloc}. A 0 offset is a no-op. */
+void heapFree(uint32_t offset);
+
+/**
+ * Resolve an offset to a real address, or nullptr when it is out of range.
+ * @param bytes The span length when the caller knows it (0 = unknown, then only
+ * the offset itself is checked; the binding's own `BoundarySpan`
+ * validates the length).
+ */
+void* heapPtr(uint32_t offset, size_t bytes);
+
+/** Peak bytes handed out, for the boot log — an arena that runs out should say so
+ * before a subsystem starts silently dropping buffers. */
+size_t heapHighWater();
+
+// Publishing a module-owned buffer INTO the heap (what an entry point that returns
+// a pointer needs) goes through `EsnSlot` / `esn_publish` in esn_shim.hpp: that is
+// the layer the generated wrappers are written against, and one mechanism is
+// enough.
+
+} // namespace eshost
diff --git a/sdk/src/ecs/engineApi.ts b/sdk/src/ecs/engineApi.ts
index 62943b946..ac706a08d 100644
--- a/sdk/src/ecs/engineApi.ts
+++ b/sdk/src/ecs/engineApi.ts
@@ -21,14 +21,20 @@
import type { App } from '../app';
import type { NativeEngineApi } from './nativeEngineApi.generated';
+import type { NativeHeap } from './nativeHeap';
-/** The engine surface a plugin may call, from either core. */
-export type EngineApi = NativeEngineApi;
+/**
+ * The engine surface a plugin may call, from either core: the entry points plus
+ * the heap they marshal bulk data through. A wasm module answers both by
+ * construction; a native host answers the heap from its arena (see nativeHeap.ts),
+ * so a plugin that writes a tile array and passes an offset works on both.
+ */
+export type EngineApi = NativeEngineApi & Partial<NativeHeap>;
-let native_: NativeEngineApi | null = null;
+let native_: EngineApi | null = null;
/** Install the native host's engine API (by the native runtime); null clears it. */
-export function setNativeEngineApi(api: NativeEngineApi | null): void {
+export function setNativeEngineApi(api: EngineApi | null): void {
native_ = api;
}
diff --git a/sdk/src/ecs/nativeHeap.ts b/sdk/src/ecs/nativeHeap.ts
new file mode 100644
index 000000000..85b17293b
--- /dev/null
+++ b/sdk/src/ecs/nativeHeap.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ecs/nativeHeap.ts
+ * @brief The heap a native core marshals bulk data through.
+ *
+ * Half the engine's surface passes bulk data as an offset plus a count: tile
+ * arrays, polygon vertices, body transforms, spine meshes. On the web that offset
+ * addresses wasm's linear memory, which the SDK writes through `module.HEAPF32`
+ * and hands over as a number. A native core had no such memory, so every one of
+ * those calls was web-only — which is why physics, tilemaps and spine could not
+ * run on a device even though their C++ compiles natively.
+ *
+ * The host now reserves one arena and exposes it as a single `ArrayBuffer`
+ * (`native/host/heap.hpp`). This builds the same views over it that an emscripten
+ * module exposes, so a subsystem's module interface — `HEAPF32` + `_malloc` +
+ * a `…Ptr` argument — is satisfied by the same SDK code on both platforms.
+ *
+ * One difference, in the native build's favour: the arena never moves, so these
+ * views stay valid for the process lifetime instead of being invalidated by heap
+ * growth.
+ */
+
+/** The heap members a subsystem module interface asks for. */
+export interface NativeHeap {
+ HEAPU8: Uint8Array;
+ HEAPU16: Uint16Array;
+ HEAPU32: Uint32Array;
+ HEAPI32: Int32Array;
+ HEAPF32: Float32Array;
+ HEAPF64: Float64Array;
+ _malloc(bytes: number): number;
+ _free(offset: number): void;
+}
+
+/** The host globals that carry it. */
+export const HEAP_BINDINGS = {
+ heap: 'es_heap',
+ malloc: 'es_malloc',
+ free: 'es_free',
+} as const;
+
+/** Whether this host bound the heap at all. A core that marshals nothing may not. */
+export function hasHeapBindings(scope: Record<string, unknown>): boolean {
+ return typeof scope[HEAP_BINDINGS.heap] === 'function'
+ && typeof scope[HEAP_BINDINGS.malloc] === 'function'
+ && typeof scope[HEAP_BINDINGS.free] === 'function';
+}
+
+/**
+ * Build the heap views over a host scope (the QuickJS global object; a plain
+ * object in tests). Null when the host bound no heap, which every caller treats
+ * the way it treats a core that left a subsystem out.
+ */
+export function createNativeHeap(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): NativeHeap | null {
+ if (!hasHeapBindings(scope)) return null;
+ const buffer = (scope[HEAP_BINDINGS.heap] as () => ArrayBuffer | null)();
+ if (!buffer) return null;
+ const malloc = scope[HEAP_BINDINGS.malloc] as (bytes: number) => number;
+ const free = scope[HEAP_BINDINGS.free] as (offset: number) => void;
+ return {
+ HEAPU8: new Uint8Array(buffer),
+ HEAPU16: new Uint16Array(buffer),
+ HEAPU32: new Uint32Array(buffer),
+ HEAPI32: new Int32Array(buffer),
+ HEAPF32: new Float32Array(buffer),
+ HEAPF64: new Float64Array(buffer),
+ _malloc: (bytes: number) => malloc(bytes),
+ _free: (offset: number) => free(offset),
+ };
+}
diff --git a/sdk/tests/native-heap.test.ts b/sdk/tests/native-heap.test.ts
new file mode 100644
index 000000000..dd60d0529
--- /dev/null
+++ b/sdk/tests/native-heap.test.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The native heap is what makes a `…Ptr` argument mean the same thing on a device
+// as it does on the web: an offset into memory both sides can see. These drive the
+// SDK half against a mock host arena — the same shape the real host exposes
+// (native/host/bindings/HeapBindings.cpp) — so the marshalling that physics,
+// tilemaps and particles rely on is checked without a device.
+import { describe, it, expect } from 'vitest';
+import { createNativeHeap, hasHeapBindings, HEAP_BINDINGS } from '../src/ecs/nativeHeap';
+
+/** A mock host arena: one buffer plus a bump allocator, offsets never 0. */
+function mockHost(bytes = 1024): Record<string, unknown> {
+ const buffer = new ArrayBuffer(bytes);
+ let next = 8;
+ const live = new Set<number>();
+ return {
+ [HEAP_BINDINGS.heap]: () => buffer,
+ [HEAP_BINDINGS.malloc]: (size: number) => {
+ const offset = next;
+ next += Math.ceil(size / 8) * 8;
+ if (next > bytes) return 0;
+ live.add(offset);
+ return offset;
+ },
+ [HEAP_BINDINGS.free]: (offset: number) => { live.delete(offset); },
+ __live: live,
+ };
+}
+
+describe('createNativeHeap', () => {
+ it('is absent until the host binds all three globals', () => {
+ expect(hasHeapBindings({})).toBe(false);
+ expect(createNativeHeap({})).toBeNull();
+ const partial = mockHost();
+ delete partial[HEAP_BINDINGS.free];
+ expect(hasHeapBindings(partial)).toBe(false);
+ });
+
+ it('views every element type over the one arena', () => {
+ const heap = createNativeHeap(mockHost())!;
+ expect(heap.HEAPU8.buffer).toBe(heap.HEAPF32.buffer);
+ expect(heap.HEAPU8.byteLength).toBe(1024);
+ expect(heap.HEAPF32.length).toBe(256);
+ expect(heap.HEAPU16.length).toBe(512);
+ expect(heap.HEAPF64.length).toBe(128);
+ });
+
+ it('round-trips a float buffer through an offset, the way an entry point reads it', () => {
+ const heap = createNativeHeap(mockHost())!;
+ const tiles = new Float32Array([1.5, -2.25, 3, 4]);
+ const ptr = heap._malloc(tiles.length * 4);
+ expect(ptr).toBeGreaterThan(0);
+ heap.HEAPF32.set(tiles, ptr / 4);
+ // What the C++ side does with (ptr, count): read from the shared arena.
+ expect(Array.from(heap.HEAPF32.subarray(ptr / 4, ptr / 4 + tiles.length)))
+ .toEqual([1.5, -2.25, 3, 4]);
+ heap._free(ptr);
+ });
+
+ it('writes through the arena are visible to the host, not to a copy', () => {
+ const host = mockHost();
+ const heap = createNativeHeap(host)!;
+ const ptr = heap._malloc(4);
+ heap.HEAPU32[ptr / 4] = 0xdeadbeef;
+ // The host's own view of the same memory (it handed us its buffer).
+ const hostView = new Uint32Array((host[HEAP_BINDINGS.heap] as () => ArrayBuffer)());
+ expect(hostView[ptr / 4]).toBe(0xdeadbeef);
+ });
+
+ it('answers 0 when the arena is full, which reads as null', () => {
+ const heap = createNativeHeap(mockHost(64))!;
+ expect(heap._malloc(4096)).toBe(0);
+ });
+
+ it('frees what it allocated', () => {
+ const host = mockHost();
+ const heap = createNativeHeap(host)!;
+ const ptr = heap._malloc(16);
+ expect((host.__live as Set<number>).has(ptr)).toBe(true);
+ heap._free(ptr);
+ expect((host.__live as Set<number>).has(ptr)).toBe(false);
+ });
+});
diff --git a/src/esengine/bindings/BoundarySpan.hpp b/src/esengine/bindings/BoundarySpan.hpp
index f4d14958a..64942b5e4 100644
--- a/src/esengine/bindings/BoundarySpan.hpp
+++ b/src/esengine/bindings/BoundarySpan.hpp
@@ -31,16 +31,48 @@
namespace esengine {
namespace detail {
-inline usize boundaryHeapSize() {
+#ifndef __EMSCRIPTEN__
+// The bounded region a native host marshals JS buffers through (its heap arena).
+// Zero until the host registers one, and then this gate is as strict on a device
+// as it is in the sandbox.
+inline uintptr_t g_boundaryBase = 0;
+inline usize g_boundarySize = 0;
+#endif
+
+/** Whether [ptr, ptr+bytes) is inside the memory JS can legitimately address.
+ * Reports the region it checked against, so a rejection names what it compared. */
+inline bool boundaryContains(uintptr_t ptr, u64 bytes, uintptr_t* base, u64* size) {
#ifdef __EMSCRIPTEN__
- return emscripten_get_heap_size();
+ // wasm: linear memory, addressed from 0.
+ *base = 0;
+ *size = static_cast<u64>(emscripten_get_heap_size());
#else
- // Native builds have no single linear-memory bound; null/overflow checks still apply.
- return SIZE_MAX;
+ *base = g_boundaryBase;
+ *size = static_cast<u64>(g_boundarySize);
+ if (*size == 0) {
+ // No host region registered: a pointer here came from C++, not from JS
+ // (or the host predates the arena). Null/overflow checks still applied.
+ return true;
+ }
#endif
+ if (static_cast<u64>(ptr) < static_cast<u64>(*base)) return false;
+ const u64 offset = static_cast<u64>(ptr) - static_cast<u64>(*base);
+ return offset <= *size && bytes <= *size - offset;
}
} // namespace detail
+#ifndef __EMSCRIPTEN__
+/**
+ * @brief Declare the region a native host lets JS address (its heap arena).
+ * @details Called once, when the host reserves the arena. Until then a native
+ * build only null/overflow-checks, since there is no bound to check.
+ */
+inline void setBoundaryRegion(uintptr_t base, usize size) {
+ detail::g_boundaryBase = base;
+ detail::g_boundarySize = size;
+}
+#endif
+
/**
* @brief Validates a JS-supplied pointer to @p count elements of T and returns it typed.
* @return The typed pointer, or nullptr (after an always-on error log) when the pointer
@@ -61,13 +93,16 @@ inline const T* boundarySpan(uintptr_t ptr, u64 count, const char* what) {
what, static_cast<unsigned long long>(count));
return nullptr;
}
- const u64 heap = static_cast<u64>(detail::boundaryHeapSize());
- if (static_cast<u64>(ptr) > heap || bytes > heap - static_cast<u64>(ptr)) {
+ uintptr_t base = 0;
+ u64 size = 0;
+ if (!detail::boundaryContains(ptr, bytes, &base, &size)) {
std::fprintf(stderr,
- "[boundary] %s: span [%llu + %llu bytes] exceeds the wasm heap (%llu); rejected\n",
+ "[boundary] %s: span [%llu + %llu bytes] leaves the heap "
+ "(%llu bytes at %llu); rejected\n",
what, static_cast<unsigned long long>(ptr),
static_cast<unsigned long long>(bytes),
- static_cast<unsigned long long>(heap));
+ static_cast<unsigned long long>(size),
+ static_cast<unsigned long long>(base));
return nullptr;
}
return reinterpret_cast<const T*>(ptr);
diff --git a/tools/eht/generators/native_functions.py b/tools/eht/generators/native_functions.py
index 2eb226b24..af2586337 100644
--- a/tools/eht/generators/native_functions.py
+++ b/tools/eht/generators/native_functions.py
@@ -20,9 +20,11 @@ The mapping is small because the declarations are:
host has exactly one of each, so they are implicit and
consume no JS argument (see ``_IMPLICIT_REFS``)
scalars u32/i32/f32/f64/bool/int/float/double
- ``uintptr_t`` ptr a JS ArrayBuffer / typed array; the wrapper copies the
- bytes and passes a real pointer (the same BoundarySpan
- validation runs inside the binding)
+ ``uintptr_t`` ptr an offset into the host's heap arena — the same thing it is
+ on the web, where the heap is wasm's linear memory (see
+ native/host/heap.hpp). A JS buffer handed straight across is
+ still accepted and copied in. Either way the binding's own
+ BoundarySpan validation runs, now against a real region.
returns void / integer / float / bool
Anything else — ``emscripten::val`` results, ``std::string``, typed pointers — is
@@ -38,8 +40,22 @@ _INT_TYPES = {'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64',
'int', 'int32_t', 'uint32_t', 'size_t', 'long'}
_FLOAT_TYPES = {'f32', 'f64', 'float', 'double'}
_BOOL_TYPES = {'bool'}
+_STRING = 'std::string'
_VOID = 'void'
+# A pointer-returning entry point hands back memory the MODULE owns (a static
+# buffer, a vector's storage), which is not in the heap JS can read. The
+# declaration says how many bytes it covers and the wrapper copies them into a
+# stable heap slot, returning that offset — so the SDK reads the result exactly as
+# it reads a wasm one, and nothing about the buffer's extent is guessed:
+#
+# // @heapreturn physics_getDynamicBodyCount() * PHYSICS_BODY_STRIDE_BYTES
+# uintptr_t physics_getDynamicBodyTransforms();
+#
+# The expression is C++, evaluated in the generated TU right after the call — at
+# GLOBAL scope, so any engine name in it needs qualifying (`esengine::f32`).
+_HEAP_RETURN = re.compile(r'@heapreturn\s+(?P<expr>.+?)\s*$', re.MULTILINE)
+
# Reference parameters the host answers for itself: it runs exactly one registry
# and one resource manager, so these consume no JS argument and the wrapper passes
# the shim's accessor. Everything else taken by reference is a genuine object the
@@ -75,6 +91,12 @@ class Function(NamedTuple):
# wrapper carries them verbatim, so the generated TU tracks whatever the
# build enables instead of assuming a fixed feature set.
guards: Tuple[str, ...] = ()
+ # The C++ byte-count expression from an `@heapreturn` annotation, for an entry
+ # point that returns module-owned memory (see _HEAP_RETURN).
+ heap_return: Optional[str] = None
+ # C entry points (`extern "C"`) are not in namespace esengine, so the wrapper
+ # calls them unqualified.
+ extern_c: bool = False
class Skipped(NamedTuple):
@@ -141,21 +163,46 @@ def parse_header(text: str) -> Tuple[List[Function], List[Skipped]]:
hi = mid - 1
return guards_per_line[lo] if guards_per_line else ()
+ # A header that opens `extern "C"` declares C entry points throughout (the
+ # standalone modules — physics, spine, video — are written that way), so their
+ # wrappers must call them unqualified.
+ extern_c = 'extern "C"' in body
+
for match in _DECL.finditer(body):
ret = _clean(match.group('ret'))
name = match.group('name')
if name in {'if', 'for', 'while', 'switch', 'return', 'namespace', 'class'}:
continue
+ heap_return = _heap_return_before(body, match.start())
params, reason = _parse_params(match.group('args'))
- if reason is None and not _returnable(ret):
- reason = f'returns {ret}'
+ if reason is None and not _returnable(ret, heap_return):
+ reason = (f'returns {ret}; annotate it with `@heapreturn <bytes>` if it hands '
+ f'back module memory') if ret == 'uintptr_t' else f'returns {ret}'
if reason is not None:
skipped.append(Skipped(name, reason))
continue
- functions.append(Function(name, ret, params, guards_at(match.start())))
+ functions.append(Function(name, ret, params, guards_at(match.start()),
+ heap_return, extern_c))
return functions, skipped
+def _heap_return_before(body: str, pos: int) -> Optional[str]:
+ """The `@heapreturn` expression annotating the declaration at @p pos, if any.
+
+ Read from the comment block immediately above it — the annotation belongs next
+ to the declaration it describes, not in a table somewhere else.
+ """
+ head = body[:pos].rstrip()
+ lines: List[str] = []
+ for line in reversed(head.splitlines()):
+ token = line.strip()
+ if not token.startswith('//') and not token.startswith('*') and not token.startswith('/*'):
+ break
+ lines.append(token)
+ match = _HEAP_RETURN.search('\n'.join(lines))
+ return match.group('expr').strip() if match else None
+
+
def _parse_params(args: str) -> Tuple[List[Param], Optional[str]]:
params: List[Param] = []
args = args.strip()
@@ -173,6 +220,10 @@ def _parse_params(args: str) -> Tuple[List[Param], Optional[str]]:
if implicit:
params.append(Param(implicit, parts[-1]))
continue
+ # `const std::string&` — a JS string, read as UTF-8 for the call's duration.
+ if parts[0] == _STRING:
+ params.append(Param(_STRING, parts[-1]))
+ continue
if '&' in decl or '*' in decl:
return params, f'takes {decl}'
cpp_type = ' '.join(parts[:-1]) if len(parts) > 1 else parts[0]
@@ -184,8 +235,11 @@ def _parse_params(args: str) -> Tuple[List[Param], Optional[str]]:
return params, None
-def _returnable(ret: str) -> bool:
- return ret == _VOID or ret in _INT_TYPES | _FLOAT_TYPES | _BOOL_TYPES
+def _returnable(ret: str, heap_return: Optional[str] = None) -> bool:
+ if ret == 'uintptr_t':
+ # Only with an annotation saying how much memory it covers.
+ return heap_return is not None
+ return ret == _VOID or ret == _STRING or ret in _INT_TYPES | _FLOAT_TYPES | _BOOL_TYPES
# The engine's short scalar aliases live in namespace esengine; the plain C++
@@ -217,6 +271,9 @@ class NativeFunctionsGenerator:
out.append(' (void)argc; (void)argv;')
call_args: List[str] = []
+ # (local, js argument index) per buffer argument, so a copied-in buffer is
+ # released after the call — see esn_argRelease.
+ ptr_releases: List[Tuple[str, int]] = []
js_index = 0
for param in fn.params:
if param.cpp_type in _IMPLICIT_REFS:
@@ -224,12 +281,21 @@ class NativeFunctionsGenerator:
continue
local = f'a{js_index}'
if param.cpp_type == 'uintptr_t':
- # A JS buffer: copy the bytes, then hand the binding a real pointer.
- # Its own BoundarySpan check still runs on the other side.
- out.append(f' std::vector<esengine::u8> {local}_bytes;')
- out.append(f' esn_bytes(ctx, argv[{js_index}], {local}_bytes);')
- out.append(f' const uintptr_t {local} = {local}_bytes.empty() ? 0 '
- f': reinterpret_cast<uintptr_t>({local}_bytes.data());')
+ # A heap offset, the same as it is on the web — the host's arena
+ # plays the part of wasm's linear memory (see host/heap.hpp). A JS
+ # buffer handed straight across is copied in and released after the
+ # call. The binding's own BoundarySpan check runs either way, and
+ # now against a real region.
+ out.append(f' const uint32_t {local}_off = esn_argOffset(ctx, argv[{js_index}]);')
+ out.append(f' const uintptr_t {local} = esn_heapAddr({local}_off);')
+ ptr_releases.append((local, js_index))
+ elif param.cpp_type == _STRING:
+ # A JS string, owned by the wrapper for the call. An absent or
+ # non-string argument reads as empty rather than aborting the call,
+ # matching how embind coerces one.
+ out.append(f' const char* {local}_c = JS_ToCString(ctx, argv[{js_index}]);')
+ out.append(f' const std::string {local} = {local}_c ? {local}_c : "";')
+ out.append(f' if ({local}_c) JS_FreeCString(ctx, {local}_c);')
elif param.cpp_type in _BOOL_TYPES:
out.append(f' const bool {local} = JS_ToBool(ctx, argv[{js_index}]) != 0;')
elif param.cpp_type in _FLOAT_TYPES:
@@ -243,16 +309,44 @@ class NativeFunctionsGenerator:
call_args.append(local)
js_index += 1
- call = f'esengine::{fn.name}({", ".join(call_args)})'
+ scope = '' if fn.extern_c else 'esengine::'
+ call = f'{scope}{fn.name}({", ".join(call_args)})'
+ releases = [f' esn_argRelease(ctx, argv[{index}], {local}_off);'
+ for local, index in ptr_releases]
if fn.ret == _VOID:
out.append(f' {call};')
+ out.extend(releases)
out.append(' return JS_UNDEFINED;')
- elif fn.ret in _BOOL_TYPES:
- out.append(f' return JS_NewBool(ctx, {call});')
- elif fn.ret in _FLOAT_TYPES:
- out.append(f' return JS_NewFloat64(ctx, static_cast<double>({call}));')
else:
- out.append(f' return JS_NewInt64(ctx, static_cast<int64_t>({call}));')
+ # Hold the result, release the scratch, then convert — a wrapper must
+ # not leak the copy on the returning paths.
+ if fn.ret in _BOOL_TYPES:
+ out.append(f' const bool result = {call};')
+ out.extend(releases)
+ out.append(' return JS_NewBool(ctx, result);')
+ elif fn.ret in _FLOAT_TYPES:
+ out.append(f' const double result = static_cast<double>({call});')
+ out.extend(releases)
+ out.append(' return JS_NewFloat64(ctx, result);')
+ elif fn.ret == _STRING:
+ out.append(f' const std::string result = {call};')
+ out.extend(releases)
+ out.append(' return JS_NewStringLen(ctx, result.data(), result.size());')
+ elif fn.ret == 'uintptr_t':
+ # Module-owned memory: copy `@heapreturn` bytes into this entry
+ # point's own heap slot and answer the offset, so the SDK reads the
+ # result the same way it reads a wasm pointer. One slot per entry
+ # point, so two consecutive readbacks cannot clobber each other.
+ out.append(' static EsnSlot slot;')
+ out.append(f' const uintptr_t src = {call};')
+ out.append(f' const size_t bytes = static_cast<size_t>({fn.heap_return});')
+ out.extend(releases)
+ out.append(' return JS_NewUint32(ctx, esn_publish(slot, '
+ 'reinterpret_cast<const void*>(src), bytes));')
+ else:
+ out.append(f' const int64_t result = static_cast<int64_t>({call});')
+ out.extend(releases)
+ out.append(' return JS_NewInt64(ctx, result);')
out.append('}')
out.extend('#endif' for _ in fn.guards)
out.append('')
@@ -262,12 +356,14 @@ class NativeFunctionsGenerator:
# The same declarations, as the object a native host answers them through.
# The SDK's plugins call these by the module's own names, so a plugin reaches
# whichever core is present without knowing which (see ecs/engineApi.ts).
- _TS_RETURN = {'void': 'void', 'bool': 'boolean'}
+ _TS_RETURN = {'void': 'void', 'bool': 'boolean', _STRING: 'string'}
@staticmethod
def _ts_type(cpp: str) -> str:
if cpp in _BOOL_TYPES:
return 'boolean'
+ if cpp == _STRING:
+ return 'string'
if cpp in _IMPLICIT_REFS:
return 'unknown'
return 'number'
@@ -280,8 +376,7 @@ class NativeFunctionsGenerator:
def generate_ts(self) -> str:
"""The native engine API: every generated entry point, callable by the
name the wasm module exposes it under."""
- functions = [f for f in self._functions() if not any(p.cpp_type == 'uintptr_t' for p in f.params)]
- pointer_taking = [f.name for f in self._functions() if any(p.cpp_type == 'uintptr_t' for p in f.params)]
+ functions = self._functions()
lines = [
'// SPDX-License-Identifier: Apache-2.0',
@@ -294,9 +389,10 @@ class NativeFunctionsGenerator:
'// and reaches whichever core is present. Generated from the SAME bindings',
'// headers embind registers from, so the two surfaces cannot drift.',
'//',
- '// Every member is optional: a core answers what it compiles. Entry points that',
- '// take a heap pointer are NOT here — those need a real backend that decides how',
- '// bytes cross (see RendererBackend), not a name forwarded.',
+ '// Every member is optional: a core answers what it compiles. A `…Ptr`',
+ '// argument is an offset into the heap the core marshals through — wasm linear',
+ '// memory on the web, the host arena on a device — so a caller writes it the',
+ '// same way on both (see ecs/nativeHeap.ts).',
'',
'export interface NativeEngineApi {',
]
@@ -304,10 +400,6 @@ class NativeFunctionsGenerator:
lines.append(f' {self._ts_signature(fn)}')
lines.append('}')
lines.append('')
- if pointer_taking:
- lines.append('// Not forwarded (they take a heap pointer): '
- + ', '.join(sorted(pointer_taking)) + '.')
- lines.append('')
lines.extend([
'/** Build the API over a host scope (the QuickJS global object; a plain object',
' * in tests). A name the host did not bind simply stays absent. */',
@@ -350,6 +442,7 @@ class NativeFunctionsGenerator:
f'#include "{self.shim_header}"',
'',
'#include <cstdint>',
+ '#include <string>',
'#include <vector>',
'',
]