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(aot): a compiled module loads into the engine's real memory

esengine86ebd37e920a
diff --git a/build-tools/tasks/wasm.js b/build-tools/tasks/wasm.js
index 8e542831c..6c7905dfb 100644
--- a/build-tools/tasks/wasm.js
+++ b/build-tools/tasks/wasm.js
@@ -19,12 +19,17 @@ async function computeWasmHash(target, targetConfig, debug) {
const buildType = debug ? 'Debug' : 'Release';
const flagsKey = [...targetConfig.cmakeFlags, `CMAKE_BUILD_TYPE=${buildType}`].join('|');
+ // The toolchain files too: link flags live in cmake/Emscripten.cmake, and a
+ // hash that only covered CMakeLists.txt served a cached build after they
+ // changed — which is a wasm that does not match the flags it was asked for.
+ const toolchainHash = await hashDirectory(path.join(rootDir, 'cmake'), /\.cmake$/);
const configHash = await hashFiles([cmakeLists]);
const { createHash } = await import('crypto');
return createHash('md5')
.update(sourceHash)
.update(configHash)
+ .update(toolchainHash)
.update(flagsKey)
.digest('hex');
}
diff --git a/build-tools/utils/emscripten.d.ts b/build-tools/utils/emscripten.d.ts
new file mode 100644
index 000000000..63ec0e451
--- /dev/null
+++ b/build-tools/utils/emscripten.d.ts
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Types for the part of emscripten.js a TypeScript gate consumes.
+
+/** The `emcc` to run, or null where no activated emsdk was found. */
+export function emccPath(): string | null;
diff --git a/build-tools/utils/emscripten.js b/build-tools/utils/emscripten.js
index ed889d2b5..2510a7909 100644
--- a/build-tools/utils/emscripten.js
+++ b/build-tools/utils/emscripten.js
@@ -63,6 +63,22 @@ function candidateEmsdkRoots() {
return candidates;
}
+/**
+ * The `emcc` a gate should run, or null when this machine has no activated
+ * emsdk. Same discovery the build uses: a gate that looked only in
+ * `tools/emsdk` skipped itself on every machine whose emsdk lives elsewhere —
+ * which is the arrangement `pnpm emsdk:setup` itself tells you to prefer.
+ */
+export function emccPath() {
+ for (const root of candidateEmsdkRoots()) {
+ if (!isActivatedEmsdk(root)) continue;
+ const at = path.join(root, 'upstream', 'emscripten',
+ process.platform === 'win32' ? 'emcc.bat' : 'emcc');
+ if (existsSync(at)) return at;
+ }
+ return null;
+}
+
let emsdkActivated = false;
/**
diff --git a/cmake/Emscripten.cmake b/cmake/Emscripten.cmake
index 192cd408f..80116f39a 100644
--- a/cmake/Emscripten.cmake
+++ b/cmake/Emscripten.cmake
@@ -239,10 +239,9 @@ set(ES_EMSCRIPTEN_SDK_LINK_FLAGS
-sFORCE_FILESYSTEM=1
"-sEXPORT_NAME='ESEngineModule'"
"-sEXPORTED_FUNCTIONS=['_malloc','_free']"
- # 'wasmMemory' is the AOT contract: a compiled system module IMPORTS this
- # memory rather than owning one, so the game's own systems read the rows
- # where they already are (docs/REARCH_AOT.md §6.1). The glue keeps it in a
- # local otherwise, and an ArrayBuffer cannot be turned back into a Memory.
+ # wasmMemory is the Memory OBJECT, not a view of it. A compiled system module
+ # imports it as `env.memory` so it addresses the same bytes the engine does;
+ # HEAPU8.buffer is an ArrayBuffer and cannot be imported.
"-sEXPORTED_RUNTIME_METHODS=['ccall','cwrap','HEAPF32','HEAPU8','HEAPU32','GL','FS','addFunction','wasmMemory']"
-O3
-flto
diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.ts
index b030dd498..87a078dcf 100644
--- a/compiler/src/codegen.ts
+++ b/compiler/src/codegen.ts
@@ -2,19 +2,19 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file codegen.ts
- * @brief EIR -> C, against the SysCtx contract (docs/REARCH_AOT.md §10 Stage 2).
+ * @brief EIR -> C, against the SysCtx contract.
*
- * @details The backend emits C rather than LLVM IR, and the reason is in §17:
- * the LLVM half is a solved problem someone else maintains, and one C
- * output serves clang for aarch64 and emcc for wasm at once. What is
- * NOT solved anywhere is the half above it — EIR, and this lowering.
+ * @details The backend emits C rather than LLVM IR because the LLVM half is a
+ * solved problem someone else maintains, and one C output serves clang
+ * for aarch64 and emcc for wasm at once. What is NOT solved anywhere is
+ * the half above it — EIR, and this lowering.
*
* Two properties are the whole point, and both are visible in the
* output rather than asserted about it:
*
* - **Zero calls.** A generated system's only external names are the
- * static inlines in the runtime header. That is §6.5's empty import
- * section, arrived at by construction rather than by trimming.
+ * static inlines in the runtime header, so the wasm's import section
+ * is empty by construction rather than by trimming.
* - **Loads at constant offsets.** Every component field is
* `es_f32(base + ES_OFF_Comp_field)`, and the offset came from EHT.
* The offsets are macros so a debugger and a reader see the name.
@@ -47,6 +47,17 @@ export const CFLAGS: readonly string[] = [
'-std=c11', '-O2', '-ffp-contract=off', '-fexcess-precision=standard',
];
+/**
+ * What linking one of these into a wasm module takes. Load-bearing, not taste:
+ * the module owns no memory and has no entry, and the memory it is handed is
+ * the ENGINE's — which grows, so one declaring a smaller maximum does not run
+ * slower, it fails to instantiate with a LinkError.
+ */
+export const WASM_LINK_FLAGS: readonly string[] = [
+ '--no-entry', '-sSTANDALONE_WASM', '-sIMPORTED_MEMORY',
+ '-sALLOW_MEMORY_GROWTH=1', '-sERROR_ON_UNDEFINED_SYMBOLS=1',
+];
+
/** The odd constant the width is multiplied by before it is folded in. */
export const ADDR_MIX = '0x9e3779b97f4a7c15';
@@ -60,13 +71,25 @@ export interface CModule {
* with one of these is a read of a different field.
*/
readonly offsets: string;
- /** The translation unit: module functions and systems. */
+ /**
+ * The translation unit: module functions and systems, and NOTHING else. A
+ * module that shares the engine's memory must have no data section — a
+ * static of its own is written at a link-time address the engine already
+ * owns, which silently overwrites whatever is there.
+ */
readonly source: string;
+ /**
+ * The handshake constant and the declaration table, as a second translation
+ * unit. A host that links against the engine reads them out of the artifact;
+ * a host that loads the wasm reads the manifest instead, and must not
+ * compile this.
+ */
+ readonly decls: string;
/** Exported symbols, one per compiled system. */
readonly symbols: readonly string[];
/**
- * The §2.5 handshake: what this module baked in about the ENGINE and about
- * the PROJECT, each so a loader can say which one moved.
+ * The handshake: what this module baked in about the ENGINE and about the
+ * PROJECT, each so a loader can say which one moved.
*/
readonly handshake: { readonly engineAbi: string; readonly projectShapes: string };
}
@@ -78,10 +101,10 @@ export interface CModule {
/**
* Everything the generated code is allowed to reach. All of it is `static
* inline`, so the object file has no undefined symbol and the wasm has no
- * import — §6.5 holds because there was never anything to import.
+ * import — there was never anything to import.
*/
export const RUNTIME_H = `/* GENERATED by @estella/compiler — do not edit. */
-/* The Estella ABI, C side. docs/REARCH_AOT_ABI.md */
+/* The Estella ABI, C side. */
#ifndef ESTELLA_ABI_H
#define ESTELLA_ABI_H
@@ -103,7 +126,7 @@ export const RUNTIME_H = `/* GENERATED by @estella/compiler — do not edit. */
mixed into the handshake so a 32-bit artifact cannot load into a 64-bit host.
ES_ADDR_BASE is the other model: a host that owns one block and addresses it
- by offset. A wasm2c deployment (§5) is one, and so is the differential
+ by offset. A wasm2c deployment is one, and so is the differential
harness. Same structs, same offsets, one word wider or narrower. */
#if defined(ES_ADDR_BASE)
typedef uint32_t es_addr_t;
@@ -114,14 +137,14 @@ typedef uintptr_t es_addr_t;
#define ES_PTR(a) ((unsigned char *)(a))
#endif
-/* §2.2 — the packed rows the host materialised: for each row, the entity and
+/* The packed rows the host materialised: for each row, the entity and
then one base address per component the query named, in that order. */
typedef struct EsQueryRows {
es_addr_t rows;
es_addr_t count;
} EsQueryRows;
-/* §2.3 — four u32, sixteen bytes, at every address width. */
+/* A command: four u32, sixteen bytes, at every address width. */
typedef struct EsCmd {
uint32_t kind;
uint32_t a;
@@ -132,7 +155,7 @@ typedef struct EsCmd {
#define ES_CMD_DESPAWN ${CMD_DESPAWN}u
#define ES_CMD_REMOVE ${CMD_REMOVE}u
-/* §2.1 — ${SYSCTX_WORDS} addresses. §6.3 makes that a number needing a reason to grow. */
+/* ${SYSCTX_WORDS} addresses, and a number that needs a reason to grow. */
typedef struct EsSysCtx {
es_addr_t queries;
es_addr_t resources;
@@ -142,7 +165,7 @@ typedef struct EsSysCtx {
es_addr_t events;
} EsSysCtx;
-/* §6: what a host needs in order to CALL a system without glue written by hand.
+/* What a host needs in order to CALL a system without glue written by hand.
The compiler knows a system's queries and resources -- that is what _params
is -- so it says so here rather than leaving each host to be told twice. */
typedef struct EsQueryDecl {
@@ -160,8 +183,8 @@ typedef struct EsSystemDecl {
uint32_t resourceCount;
} EsSystemDecl;
-/* §6.1 asks that the C and TS sides of these structs have ONE author, and that a
- hand-written side fail to compile. The numbers below are written by that author
+/* The C and TS sides of these structs have ONE author, and a side that drifts
+ from it must fail to compile. The numbers below are written by that author
(compiler/src/abi.ts) into this file; these three declarations are how C says
no if a struct above ever stops matching them. */
typedef char es_check_sysctx[sizeof(EsSysCtx) == ${SYSCTX_WORDS} * sizeof(es_addr_t) ? 1 : -1];
@@ -527,7 +550,7 @@ class Emitter {
/**
* A command is four words written into the host's buffer and a counter
* bumped — no call, and nothing read back. The `cap` guard is the
- * contract's: §3 forbids writing past it, and the host is what sized it.
+ * contract's: writing past it is forbidden, and the host is what sized it.
*/
private emitCommand(s: Stmt & { s: 'emit' }, indent: number): void {
const kind = s.record === 'despawn' ? 'ES_CMD_DESPAWN' : 'ES_CMD_REMOVE';
@@ -545,7 +568,7 @@ class Emitter {
}
/**
- * The op EIR exists to keep (§4.2): a strided walk of a packed row array.
+ * The op EIR exists to keep: a strided walk of a packed row array.
* One `es_u32` per component per row and no lookup — the host already did
* the lookup once, in C++, which is where it is cheap.
*/
@@ -594,7 +617,7 @@ class Emitter {
this.line(0, '');
}
- /** `void es_sys_<Name>(uint32_t ctx)` — §2.1's one exported symbol. */
+ /** `void es_sys_<Name>(uint32_t ctx)` — the one exported symbol. */
system(sys: EirSystem): void {
const plan = this.plan!;
this.bind([...sys.params, ...sys.locals]);
@@ -694,11 +717,21 @@ export function emitC(module: EirModule, layout: AbiLayout, systems: readonly Ei
].join('\n');
const source = [
'/* GENERATED by @estella/compiler — do not edit. */',
- '/* docs/REARCH_AOT_ABI.md: this file calls the engine zero times. */',
+ '/* This file calls the engine zero times, and holds no data of its own. */',
'#include "estella_abi.h"',
'#include "estella_offsets.h"',
'',
- '/* §2.5: what this module baked in about the engine it was built for. A',
+ ...bodies,
+ ].join('\n');
+ const decls = [
+ '/* GENERATED by @estella/compiler — do not edit. */',
+ '/* The static half: what this module is, for a host that reads it out of',
+ ' the artifact rather than out of a manifest beside it. Separate because',
+ ' a wasm module sharing the ENGINE\'s memory must carry no data section —',
+ ' its bytes would land at a link-time address the engine already owns. */',
+ '#include "estella_abi.h"',
+ '',
+ '/* What this module baked in about the engine it was built for. A',
' host compares before it maps anything — a mismatch is not a wrong',
' answer, it is a read of a different field. The address width belongs',
' to the MACHINE, so it mixes in here rather than in the compiler and a',
@@ -707,7 +740,8 @@ export function emitC(module: EirModule, layout: AbiLayout, systems: readonly Ei
'const uint64_t es_abi_hash =',
` ES_ABI_ENGINE_DIGEST ^ (${ADDR_MIX}ULL * (uint64_t)sizeof(es_addr_t));`,
'',
- ...bodies,
+ ...systems.map((s) => `void ${cSymbol(s.name)}(es_addr_t es_ctx);`),
+ '',
...manifest,
].join('\n');
@@ -715,6 +749,7 @@ export function emitC(module: EirModule, layout: AbiLayout, systems: readonly Ei
header: RUNTIME_H,
offsets: offsetsHeader,
source,
+ decls,
symbols: systems.map((s) => cSymbol(s.name)),
handshake,
};
diff --git a/compiler/src/index.ts b/compiler/src/index.ts
index 3ca2bcc73..ff9e6d8e6 100644
--- a/compiler/src/index.ts
+++ b/compiler/src/index.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file index.ts
- * @brief Estella AOT compiler — public surface (docs/REARCH_AOT.md Stages 1-2).
+ * @brief Estella AOT compiler — public surface.
*/
export * from './eir';
export { brokenPromises, lowerProgram, type Diagnostic, type LowerResult } from './frontend';
@@ -15,5 +15,5 @@ export {
CMD_DESPAWN, CMD_REMOVE, CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS,
type AbiCall, type AbiHandshake, type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,
} from './abi';
-export { ADDR_MIX, CFLAGS, RUNTIME_H, cSymbol, emitC, type CModule } from './codegen';
+export { ADDR_MIX, CFLAGS, RUNTIME_H, WASM_LINK_FLAGS, cSymbol, emitC, type CModule } from './codegen';
export { builtinShapes } from './builtins';
diff --git a/compiler/tests/codegen.test.ts b/compiler/tests/codegen.test.ts
index 257f34851..d14bd48fa 100644
--- a/compiler/tests/codegen.test.ts
+++ b/compiler/tests/codegen.test.ts
@@ -4,8 +4,7 @@
* @file codegen.test.ts
* @brief The compiled code and the interpreter must produce the SAME BYTES.
*
- * @details Stage 2's exit criterion in miniature (docs/REARCH_AOT.md §10). Up to
- * here every test has compared an interpreter against node; both are
+ * @details Up to here every test has compared an interpreter against node; both are
* JavaScript, and neither is what ships. This one compiles the emitted
* C with a real compiler and runs it in another process.
*
@@ -19,8 +18,8 @@
*
* Two more properties are asserted because they are what make this a
* contract rather than a convention: the object file has no undefined
- * symbol besides the memory base (§6.5's empty import section, as far
- * as a native build can show it), and the generated C compiles with no
+ * symbol besides the memory base — the empty import section, as far as
+ * a native build can show it — and the generated C compiles with no
* warning at all.
*
* If no C compiler is on PATH the differential CANNOT run, and this
@@ -181,7 +180,7 @@ int main(int argc, char **argv) {
/**
* One executable per system. The entry symbol is a -D so main is shared, and so
* is the address model: `offset` is a host that owns one block (a wasm2c
- * deployment, §5), `pointer` is one that hands over real addresses (the C++
+ * deployment), `pointer` is one that hands over real addresses (the C++
* engine). Same generated source, compiled twice.
*/
type Addressing = 'offset' | 'pointer';
@@ -496,8 +495,8 @@ describe('the emitted C says what the interpreter says', () => {
expect(out.status, out.stderr).toBe(0);
expect(out.stderr.trim()).toBe('');
- // §6.5 is about the wasm import section; natively the same property is
- // "no undefined symbol". `es_memory` is the linear memory itself, which
+ // The contract is about the wasm import section; natively the same
+ // property is "no undefined symbol". `es_memory` is the linear memory itself, which
// on wasm is not an import at all — it IS the module's memory.
const nm = spawnSync('nm', [obj], { encoding: 'utf8' });
if (nm.status !== 0) {
@@ -516,7 +515,7 @@ describe('the emitted C says what the interpreter says', () => {
it('the artifact carries what it baked in about the engine', () => {
const layout = packLayout(shipped.module.comps);
const c = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);
- expect(c.source).toContain(`#define ES_ABI_ENGINE_DIGEST 0x${c.handshake.engineAbi}ULL`);
+ expect(c.decls).toContain(`#define ES_ABI_ENGINE_DIGEST 0x${c.handshake.engineAbi}ULL`);
expect(c.handshake.engineAbi).toMatch(/^[0-9a-f]{16}$/);
expect(c.handshake.projectShapes).toMatch(/^[0-9a-f]{16}$/);
});
@@ -550,9 +549,9 @@ describe('the emitted C says what the interpreter says', () => {
// A digest could only say "something moved". The order is what the host
// follows when it fills the ctx, so it is carried rather than compared.
const layout = packLayout(shipped.module.comps);
- const { source } = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);
- expect(source).toContain('{ "Transform", "Mover" }');
- expect(source).toContain('{ "Time" }');
+ const { decls } = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);
+ expect(decls).toContain('{ "Transform", "Mover" }');
+ expect(decls).toContain('{ "Time" }');
});
it('what the artifact exports is what a host computes, at both widths', () => {
@@ -566,6 +565,7 @@ describe('the emitted C says what the interpreter says', () => {
writeFileSync(join(dir, 'estella_abi.h'), c.header);
writeFileSync(join(dir, 'estella_offsets.h'), c.offsets);
writeFileSync(join(dir, 'systems.c'), c.source);
+ writeFileSync(join(dir, 'systems_decl.c'), c.decls);
writeFileSync(join(dir, 'main.c'), [
'#include <stdio.h>',
'#include "estella_abi.h"',
@@ -582,7 +582,8 @@ describe('the emitted C says what the interpreter says', () => {
for (const [flags, bytes] of [[['-DES_ADDR_BASE'], 4], [[], 8]] as const) {
const exe = join(dir, `h${bytes}${process.platform === 'win32' ? '.exe' : ''}`);
const built = spawnSync(CC!, [...CFLAGS, '-Wall', '-Wextra', ...flags, '-o', exe,
- join(dir, 'main.c'), join(dir, 'systems.c'), '-lm'], { encoding: 'utf8' });
+ join(dir, 'main.c'), join(dir, 'systems.c'), join(dir, 'systems_decl.c'), '-lm'],
+ { encoding: 'utf8' });
expect(built.status, built.stderr).toBe(0);
expect(built.stderr.trim()).toBe('');
const [got, width] = execFileSync(exe, { encoding: 'utf8' }).trim().split(' ');
@@ -596,7 +597,7 @@ describe('the emitted C says what the interpreter says', () => {
it('a component field is one load at a constant offset', () => {
const layout = packLayout(shipped.module.comps);
const { source } = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);
- // §4.2's whole reason for existing, readable in the output itself.
+ // EIR's whole reason for existing, readable in the output itself.
expect(source).toMatch(/es_f32\(\w+ \+ ES_OFF_Transform_position_x\)/);
expect(emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]).offsets)
.toMatch(/#define ES_OFF_Transform_position_x \d+u/);
diff --git a/compiler/tests/generated.test.ts b/compiler/tests/generated.test.ts
index e4759f6b6..981c398f2 100644
--- a/compiler/tests/generated.test.ts
+++ b/compiler/tests/generated.test.ts
@@ -70,6 +70,12 @@ describe('the C artifacts the engine builds against', () => {
artifact(join(ROOT, 'tests/aot/generated/move_system.c'), c.source);
});
+ /** The C++ host reads the table out of the artifact; a wasm host must not
+ * compile it, because a data section of its own overwrites the engine's. */
+ it('and the declarations, which only a linking host compiles', () => {
+ artifact(join(ROOT, 'tests/aot/generated/move_system_decl.c'), c.decls);
+ });
+
it('and the hash the harness compares, so it is not a second copy', () => {
artifact(join(ROOT, 'tests/aot/generated/move_system_hash.h'), [
'/* GENERATED by @estella/compiler — do not edit. */',
diff --git a/compiler/tests/wasm.test.ts b/compiler/tests/wasm.test.ts
index 0b196f582..ebab99070 100644
--- a/compiler/tests/wasm.test.ts
+++ b/compiler/tests/wasm.test.ts
@@ -8,12 +8,12 @@
* Web is the first target on the roadmap, and two of the contract's
* claims can only be asked of the real artifact.
*
- * §6.5 — the import section must be empty — was `nm` on an object file,
- * with a comment admitting that was as close as a native build gets.
+ * "The import section must be empty" was `nm` on an object file, with a
+ * comment admitting that was as close as a native build gets.
* `WebAssembly.Module.imports()` is the actual question.
*
- * §2.1.1 — an address is a pointer, and on wasm32 a pointer IS the
- * offset — stops being an argument and becomes a run.
+ * "An address is a pointer, and on wasm32 a pointer IS the offset"
+ * stops being an argument and becomes a run.
*
* Two shapes are built, and the second is the one that ships: a module
* that IMPORTS the engine's memory rather than owning one. See the
@@ -24,7 +24,7 @@
*/
import { describe, it, expect } from 'vitest';
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -37,6 +37,7 @@ import { AbiMemory, flushCommands, materialize, packLayout, planFor, runOnAbi }
import { CFLAGS, cSymbol, emitC } from '../src/codegen';
import type { AbiLayout } from '../src/abi';
import type { EirSystem } from '../src/eir';
+import { emccPath } from '../../build-tools/utils/emscripten.js';
const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));
const N = 24;
@@ -46,14 +47,7 @@ const IMAGE = 1 << 16;
/** Where the world goes in an IMPORTED memory: clear of the module's own data. */
const GUEST_BASE = 1 << 20;
-/** emsdk lives in the repo, unpacked by `pnpm emsdk:setup`. */
-function findEmcc(): string | null {
- const bat = join(ROOT, 'tools/emsdk/upstream/emscripten',
- process.platform === 'win32' ? 'emcc.bat' : 'emcc');
- return existsSync(bat) ? bat : null;
-}
-
-const EMCC = findEmcc();
+const EMCC = emccPath();
/** Whose linear memory the module runs in. */
type Memory = 'own' | 'imported';
@@ -209,7 +203,7 @@ describe('the emitted C as wasm', () => {
const moduleOf = (b: Buffer): WebAssembly.Module =>
new WebAssembly.Module(b as unknown as BufferSource);
- it('imports nothing at all — §6.5, asked of the wasm itself', () => {
+ it('imports nothing at all, asked of the wasm itself', () => {
// Not "no imports that matter": none. The contract has no call to make,
// so the section is empty by construction rather than by trimming.
expect(WebAssembly.Module.imports(moduleOf(own.bytes))).toEqual([]);
@@ -249,10 +243,10 @@ describe('the emitted C as wasm', () => {
});
/**
- * The shape that ships (§6.1). A module that IMPORTS the engine's memory is
- * in the same memory at the same offsets, so there is no boundary to
- * rebuild: §6's warning was about a module with its OWN, which is a
- * different thing.
+ * The shape that ships. A module that IMPORTS the engine's memory is in the
+ * same memory at the same offsets, so there is no boundary to rebuild — the
+ * cost that ruled out a standalone module was about one with its OWN memory,
+ * which is a different thing.
*/
it('a module that imports the engine memory imports NO functions', () => {
const imports = WebAssembly.Module.imports(moduleOf(guest.bytes));
diff --git a/pipeline/src/bundle/buildCompiledSystems.ts b/pipeline/src/bundle/buildCompiledSystems.ts
index 3bc61d0e5..3902a86f6 100644
--- a/pipeline/src/bundle/buildCompiledSystems.ts
+++ b/pipeline/src/bundle/buildCompiledSystems.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file AOT step: a project's `@compiled` systems, as wasm (docs/REARCH_AOT.md).
+ * @file AOT step: a project's `@compiled` systems, as wasm.
*
* The rest of `buildScripts` hands the realm JavaScript. This hands it a module
* of machine code for the systems the author PROMISED would compile, built with
@@ -9,14 +9,14 @@
*
* It imports the engine's memory rather than owning one, which is what keeps
* this cheap: the engine wasm stays prebuilt and only the game's own systems are
- * compiled here — a few hundred bytes, not a link (REARCH_AOT.md §6.1).
+ * compiled here — a few hundred bytes, not a link.
*
* Never throws. A project with no marked system is not a failure and not a
* build step; a marked system that will not compile IS one, because that is what
* the marker means.
*
- * The mode decides whether it runs at all. `dev` never compiles: §9 says the
- * editor's preview always interprets, so a machine with no emsdk builds and runs
+ * The mode decides whether it runs at all. `dev` never compiles, because the
+ * editor's preview always interprets: a machine with no emsdk builds and runs
* every project. `release` and `ship` do compile, and there a promise the subset
* cannot keep is an error rather than a quiet fallback — which is the difference
* the marker exists to make.
@@ -28,7 +28,7 @@ import { verifySystem } from '../../../compiler/src/verify';
import { inlineSystem } from '../../../compiler/src/inline';
import { builtinShapes } from '../../../compiler/src/builtins';
import { packLayout, planFor } from '../../../compiler/src/abi';
-import { CFLAGS, cSymbol, emitC } from '../../../compiler/src/codegen';
+import { CFLAGS, WASM_LINK_FLAGS, cSymbol, emitC } from '../../../compiler/src/codegen';
/** Where the C and the wasm land, beside the script bundle. */
const CACHE_DIR = '.esengine/cache/aot';
@@ -203,13 +203,12 @@ export async function buildCompiledSystems(
const built = await opts.run(opts.emcc, [
...CFLAGS, '-Wall', '-Wextra',
// No entry point and no JS glue, so the module's only import is the memory
- // it is given. §6.5 is a property of this command line as much as of the C.
- '--no-entry', '-sSTANDALONE_WASM', '-sIMPORTED_MEMORY', '-sERROR_ON_UNDEFINED_SYMBOLS=1',
- // An import may not declare a smaller maximum than the memory handed to it,
- // and the engine's grows (2GB). Without this the module takes a hand-made
- // 256-page test memory and REFUSES the real engine's.
- '-sALLOW_MEMORY_GROWTH=1',
+ // it is given. An empty import section is a property of this command line
+ // as much as of the C.
+ ...WASM_LINK_FLAGS,
`-sEXPORTED_FUNCTIONS=${exported}`,
+ // `c.decls` is deliberately NOT compiled here. It is the data half, and a
+ // data section is written at a link-time address the engine already owns.
'-o', wasmPath, path.join(dir, 'systems.c'),
], dir);
if (built.code !== 0 || !existsSync(wasmPath)) {
diff --git a/pipeline/tests/build-compiled-systems.test.ts b/pipeline/tests/build-compiled-systems.test.ts
index 6d21a45e4..f6078bbb7 100644
--- a/pipeline/tests/build-compiled-systems.test.ts
+++ b/pipeline/tests/build-compiled-systems.test.ts
@@ -9,23 +9,49 @@
* it. Real emcc where emsdk is unpacked, and a loud skip where it is
* not — a gate that never saw its subject is worse than a missing one.
*/
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, beforeAll } from 'vitest';
import { spawn } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { buildCompiledSystems, readCompiledManifest } from '../src/bundle/buildCompiledSystems';
+import { emccPath } from '../../build-tools/utils/emscripten.js';
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const EMCC = emccPath();
+
+/**
+ * A memory shaped like the engine's: growable to 2GB, and already 16MB, which
+ * is also the size the module REQUIRES — emcc writes its INITIAL_MEMORY into
+ * the import's declared minimum, so a host with a smaller memory gets a
+ * LinkError rather than a module that copes.
+ */
+const engineMemory = (): WebAssembly.Memory =>
+ new WebAssembly.Memory({ initial: 256, maximum: 32768 });
+
+/** wasm section ids, by the numbers the format assigns them. */
+const DATA_SECTION = 11;
-function findEmcc(): string | null {
- const at = path.join(ROOT, 'tools/emsdk/upstream/emscripten',
- process.platform === 'win32' ? 'emcc.bat' : 'emcc');
- return existsSync(at) ? at : null;
+/** Section id -> byte length, read straight out of the binary. */
+function sectionSizes(buf: Buffer): Map<number, number> {
+ const out = new Map<number, number>();
+ let p = 8;
+ const leb = (): number => {
+ let r = 0, shift = 0, b = 0;
+ do { b = buf[p++]!; r |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
+ return r >>> 0;
+ };
+ while (p < buf.length) {
+ const id = buf[p++]!;
+ const size = leb();
+ out.set(id, (out.get(id) ?? 0) + size);
+ p += size;
+ }
+ return out;
}
-const EMCC = findEmcc();
/** The toolchain's runner, in miniature: emcc is a .bat on Windows. */
const run = (cmd: string, args: string[], cwd: string): Promise<{ code: number; stderr: string }> =>
@@ -79,6 +105,57 @@ const UNMARKED = PROMISED.replace(`/**
*/
`, '').replace("{ name: 'MoveSystem' }", "{ name: 'QuietSystem' }");
+/**
+ * The engine wasm a build produces, or null on a checkout that has not built
+ * one. `build/wasm/web` is where the build writes it; desktop/public is the
+ * editor's copy, and is inside a submodule this repo may not have.
+ */
+function engineGlue(): string | null {
+ for (const at of ['build/wasm/web/esengine.js', 'desktop/public/wasm/esengine.js']) {
+ const p = path.join(ROOT, at);
+ if (existsSync(p)) return p;
+ }
+ return null;
+}
+
+const ENGINE_GLUE = engineGlue();
+
+/**
+ * The one place both halves are real: the engine wasm this repo builds, and a
+ * module compiled from a shipped system. Every other gate substitutes a fake
+ * for one of them, and the two things that go wrong here are invisible against
+ * a fake — a memory that cannot grow, and low addresses nobody owns.
+ */
+describe.skipIf(!EMCC || !ENGINE_GLUE)('loaded into the engine the build produces', () => {
+ it('reports whether this gate could run at all', () => {
+ if (EMCC && ENGINE_GLUE) console.log(`[real-engine] against ${ENGINE_GLUE}`);
+ else console.warn('[real-engine] did NOT run — no emsdk, or no built engine wasm.');
+ });
+
+ it('instantiates against the real memory and leaves the engine intact', async () => {
+ const root = project({ 'src/components.ts': COMPONENTS, 'src/systems.ts': PROMISED });
+ const out = await buildCompiledSystems(root, { mode: 'release', emcc: EMCC, run });
+ expect(out.errors).toEqual([]);
+
+ const { default: createEngine } = await import(pathToFileURL(ENGINE_GLUE!).href) as
+ { default: () => Promise<{ wasmMemory: WebAssembly.Memory; HEAPU8: Uint8Array; _malloc(n: number): number }> };
+ const engine = await createEngine();
+
+ // Without this export there is no way to hand a module the engine's memory:
+ // HEAPU8.buffer is an ArrayBuffer, and an import needs the Memory itself.
+ expect(engine.wasmMemory, 'the engine must export wasmMemory').toBeInstanceOf(WebAssembly.Memory);
+ expect(engine.HEAPU8.buffer).toBe(engine.wasmMemory.buffer);
+
+ const canary = engine.HEAPU8.slice(1024, 1024 + 4096);
+ const bytes = readFileSync(out.wasmPath!);
+ new WebAssembly.Instance(new WebAssembly.Module(bytes as unknown as BufferSource),
+ { env: { memory: engine.wasmMemory } });
+
+ expect([...engine.HEAPU8.slice(1024, 1024 + 4096)]).toEqual([...canary]);
+ expect(engine._malloc(16)).toBeGreaterThan(0);
+ });
+});
+
describe('the AOT build step', () => {
it('reports whether this gate could run at all', () => {
if (EMCC) console.log(`[aot-build] emcc at ${EMCC}`);
@@ -147,6 +224,79 @@ describe('the AOT build step', () => {
expect(out.manifest!.projectShapes).toMatch(/^[0-9a-f]{16}$/);
});
+ /**
+ * What a module loaded into the ENGINE's memory must not do, asked of the
+ * artifact rather than of the command line that made it. A fake host with a
+ * fixed-size memory and nothing at the low addresses answers neither.
+ */
+ describe.skipIf(!EMCC)('the module a real engine would load', () => {
+ let bytes: Buffer;
+ beforeAll(async () => {
+ const root = project({ 'src/components.ts': COMPONENTS, 'src/systems.ts': PROMISED });
+ const out = await buildCompiledSystems(root, { mode: 'release', emcc: EMCC, run });
+ expect(out.errors).toEqual([]);
+ bytes = readFileSync(out.wasmPath!);
+ });
+
+ it('carries no data section, because those bytes are the engine\'s', () => {
+ // A data section is written at instantiation, at an address the linker
+ // chose — which for a module built against an imported memory is wherever
+ // the ENGINE already keeps its statics.
+ expect(sectionSizes(bytes).get(DATA_SECTION) ?? 0).toBe(0);
+ });
+
+ it('instantiates against a GROWABLE memory, which is the only kind an engine has', () => {
+ // The engine links with -sALLOW_MEMORY_GROWTH, so its memory declares a
+ // maximum of 32768 pages. A module declaring a smaller one does not run
+ // slower — it does not instantiate at all, with a LinkError.
+ expect(() => new WebAssembly.Instance(
+ new WebAssembly.Module(bytes as unknown as BufferSource),
+ { env: { memory: engineMemory() } })).not.toThrow();
+ });
+
+ /**
+ * The same two checks against a module that DOES carry data, built the same
+ * way. Without it they could be passing because emcc dropped an unreferenced
+ * table — which is luck, not the property.
+ */
+ it('and both checks can see their subject', async () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'estella-aot-control-'));
+ writeFileSync(path.join(dir, 'has-data.c'), [
+ '#include <stdint.h>',
+ 'static const double kTable[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };',
+ 'void es_sys_Control(uint32_t ctx) {',
+ ' double *out = (double *)(uintptr_t)ctx;',
+ // A RUNTIME index: with a constant one the compiler folds the table into
+ // the instructions and the module has no data after all.
+ ' out[1] = kTable[(unsigned)out[0] & 7u];',
+ '}',
+ ].join('\n'));
+ const wasm = path.join(dir, 'has-data.wasm');
+ const built = await run(EMCC!, ['-O2', '--no-entry', '-sSTANDALONE_WASM', '-sIMPORTED_MEMORY',
+ '-sALLOW_MEMORY_GROWTH=1', '-sEXPORTED_FUNCTIONS=_es_sys_Control', '-o', wasm,
+ path.join(dir, 'has-data.c')], dir);
+ expect(built.code, built.stderr).toBe(0);
+
+ const withData = readFileSync(wasm);
+ expect(sectionSizes(withData).get(DATA_SECTION) ?? 0).toBeGreaterThan(0);
+
+ const memory = engineMemory();
+ const sentinel = new Uint8Array(memory.buffer, 1024, 4096).fill(0xab);
+ new WebAssembly.Instance(
+ new WebAssembly.Module(withData as unknown as BufferSource), { env: { memory } });
+ expect(sentinel.every((b) => b === 0xab)).toBe(false);
+ });
+
+ it('and leaves the bytes already in that memory alone', () => {
+ const memory = engineMemory();
+ // Where a linker puts a module's data. The engine's own statics live here.
+ const sentinel = new Uint8Array(memory.buffer, 1024, 4096).fill(0xab);
+ new WebAssembly.Instance(
+ new WebAssembly.Module(bytes as unknown as BufferSource), { env: { memory } });
+ expect(sentinel.every((b) => b === 0xab)).toBe(true);
+ });
+ });
+
it.skipIf(!EMCC)('rebuilding is not additive: the cache is what this build made', async () => {
const root = project({ 'src/components.ts': COMPONENTS, 'src/systems.ts': PROMISED });
await buildCompiledSystems(root, { mode: 'release', emcc: EMCC, run });
diff --git a/sdk/tests/aot-context.test.ts b/sdk/tests/aot-context.test.ts
index 07f344416..a81403db0 100644
--- a/sdk/tests/aot-context.test.ts
+++ b/sdk/tests/aot-context.test.ts
@@ -18,7 +18,7 @@
*/
import { describe, it, expect } from 'vitest';
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -28,8 +28,10 @@ import { WasmPoolMemory, type WasmHeap } from '../src/ecs/WasmPoolMemory';
import { AotContext, CMD_DESPAWN } from '../src/ecs/aot/AotContext';
import { AotResources } from '../src/ecs/aot/AotResources';
import type { Entity } from '../src/types';
+import { emccPath } from '../../build-tools/utils/emscripten.js';
+import { FakeEngine } from './fakeEngine';
+import { WASM_LINK_FLAGS } from '../../compiler/src/codegen';
-const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const e = (n: number): Entity => n as unknown as Entity;
const N = 16;
@@ -52,34 +54,12 @@ function packed(rows: readonly (readonly number[])[]): {
}
const FRAMES = 8;
-function findEmcc(): string | null {
- const at = path.join(ROOT, 'tools/emsdk/upstream/emscripten',
- process.platform === 'win32' ? 'emcc.bat' : 'emcc');
- return existsSync(at) ? at : null;
-}
-const EMCC = findEmcc();
+const EMCC = emccPath();
/**
* The engine, as far as this test needs one: a linear memory and a bump
* allocator over it. A real module differs in size, not in kind.
*/
-class Engine implements WasmHeap {
- // The module declares the minimum it expects; a host has to meet it.
- readonly memory = new WebAssembly.Memory({ initial: 256, maximum: 256 });
- HEAPU8 = new Uint8Array(this.memory.buffer);
- private next = 1024;
- _malloc(size: number): number {
- const at = this.next;
- this.next += (size + 15) & ~15;
- while (this.next > this.HEAPU8.byteLength) {
- this.memory.grow(1);
- this.HEAPU8 = new Uint8Array(this.memory.buffer);
- }
- return at;
- }
- _free(): void { /* a bump allocator frees nothing */ }
-}
-
/**
* A hand-written system in the shape the compiler emits. Written out rather than
* taken from the corpus so the test says what it is testing; the corpus version
@@ -131,8 +111,7 @@ function buildModule(): Uint8Array {
const out = path.join(dir, 'sys.wasm');
const built = spawnSync(EMCC!, [
'-std=c11', '-O2', '-ffp-contract=off', '-Wall', '-Wextra',
- '--no-entry', '-sSTANDALONE_WASM', '-sIMPORTED_MEMORY',
- '-sERROR_ON_UNDEFINED_SYMBOLS=1', '-sEXPORTED_FUNCTIONS=_es_sys_Decay',
+ ...WASM_LINK_FLAGS, '-sEXPORTED_FUNCTIONS=_es_sys_Decay',
'-o', out, path.join(dir, 'sys.c'),
], { encoding: 'utf8', cwd: dir, shell: process.platform === 'win32' });
if (built.status !== 0) throw new Error(`emcc failed:\n${built.stderr}`);
@@ -149,7 +128,7 @@ describe('a compiled system, called by the SDK', () => {
});
it.skipIf(!EMCC)('moves the SDK\'s own rows, exactly as TypeScript does', async () => {
- const engine = new Engine();
+ const engine = new FakeEngine();
const memory = new WasmPoolMemory(engine);
const instance = await WebAssembly.instantiate(
new WebAssembly.Module(buildModule() as unknown as BufferSource),
@@ -217,7 +196,7 @@ describe('a compiled system, called by the SDK', () => {
});
it.skipIf(!EMCC)('a call with no rows is a call, not a crash', async () => {
- const engine = new Engine();
+ const engine = new FakeEngine();
const memory = new WasmPoolMemory(engine);
const instance = await WebAssembly.instantiate(
new WebAssembly.Module(buildModule() as unknown as BufferSource),
diff --git a/sdk/tests/aot-dispatch.test.ts b/sdk/tests/aot-dispatch.test.ts
index 81f168789..9a3da519a 100644
--- a/sdk/tests/aot-dispatch.test.ts
+++ b/sdk/tests/aot-dispatch.test.ts
@@ -14,7 +14,7 @@
*/
import { describe, it, expect } from 'vitest';
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -31,8 +31,10 @@ import type { AotAddresses, AotRuntime } from '../src/ecs/aot/AotRuntime';
import type { AnyComponentDef } from '../src/ecs/component';
import { engineAbiDigest, projectShapeDigest } from '../src/ecs/aot/abiDigest';
import type { Entity } from '../src/types';
+import { emccPath } from '../../build-tools/utils/emscripten.js';
+import { FakeEngine } from './fakeEngine';
+import { WASM_LINK_FLAGS } from '../../compiler/src/codegen';
-const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const N = 20;
const FRAMES = 10;
/** What a build for THIS engine would have written into the manifest. */
@@ -40,25 +42,7 @@ const ENGINE = engineAbiDigest(4);
const DECAY_FIELDS = ['remaining', 'rate'];
const SHAPES = projectShapeDigest([{ name: 'Decay', fields: DECAY_FIELDS }]);
-function findEmcc(): string | null {
- const at = path.join(ROOT, 'tools/emsdk/upstream/emscripten',
- process.platform === 'win32' ? 'emcc.bat' : 'emcc');
- return existsSync(at) ? at : null;
-}
-const EMCC = findEmcc();
-
-/** A linear memory and a bump allocator: the engine, as far as rows care. */
-class Heap implements WasmHeap {
- readonly memory = new WebAssembly.Memory({ initial: 256, maximum: 256 });
- HEAPU8 = new Uint8Array(this.memory.buffer);
- private next = 4096;
- _malloc(size: number): number {
- const at = this.next;
- this.next += (size + 15) & ~15;
- return at;
- }
- _free(): void { /* a bump allocator frees nothing */ }
-}
+const EMCC = emccPath();
/** `Decay`: remaining -= rate, and despawn once it reaches zero. */
const SYSTEM_C = `#include <stdint.h>
@@ -98,8 +82,7 @@ function buildModule(): Uint8Array {
const out = path.join(dir, 'sys.wasm');
const built = spawnSync(EMCC!, [
'-std=c11', '-O2', '-ffp-contract=off', '-Wall', '-Wextra',
- '--no-entry', '-sSTANDALONE_WASM', '-sIMPORTED_MEMORY',
- '-sERROR_ON_UNDEFINED_SYMBOLS=1', '-sEXPORTED_FUNCTIONS=_es_sys_Decay',
+ ...WASM_LINK_FLAGS, '-sEXPORTED_FUNCTIONS=_es_sys_Decay',
'-o', out, path.join(dir, 'sys.c'),
], { encoding: 'utf8', cwd: dir, shell: process.platform === 'win32' });
if (built.status !== 0) throw new Error(`emcc failed:\n${built.stderr}`);
@@ -173,7 +156,7 @@ describe('the scheduler and its compiled twin', () => {
// Compiled, over rows in a linear memory the module shares.
const b = makeWorld();
- const heap = new Heap();
+ const heap = new FakeEngine();
const memory = new WasmPoolMemory(heap);
b.world.useScriptPoolMemory(memory);
const bEntities = seed(b.world, b.Decay);
@@ -209,6 +192,9 @@ describe('the scheduler and its compiled twin', () => {
// only that neither moved.
expect(aEntities.filter((e) => a.world.valid(e)).length).toBeLessThan(N);
expect(aEntities.filter((e) => a.world.valid(e)).length).toBeGreaterThan(0);
+ // Nothing the module did may reach the bytes the engine keeps for
+ // itself — not its data section on load, not a stack spill on a call.
+ expect(heap.staticsIntact()).toBe(true);
});
it.skipIf(!EMCC)('a twin marks Changed, which it cannot do for itself', async () => {
@@ -225,7 +211,7 @@ describe('the scheduler and its compiled twin', () => {
for (const _ of query as Iterable<unknown>) n++;
watched.push(n);
}, { name: 'Watcher' });
- const heap = new Heap();
+ const heap = new FakeEngine();
const memory = new WasmPoolMemory(heap);
if (compiled) w.world.useScriptPoolMemory(memory);
seed(w.world, w.Decay);
diff --git a/sdk/tests/aot-install.test.ts b/sdk/tests/aot-install.test.ts
index e64dad691..41309564b 100644
--- a/sdk/tests/aot-install.test.ts
+++ b/sdk/tests/aot-install.test.ts
@@ -19,7 +19,7 @@
*/
import { describe, it, expect } from 'vitest';
import { spawnSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -37,30 +37,15 @@ import type { AotManifest } from '../src/ecs/aot/AotSystems';
import type { AnyComponentDef } from '../src/ecs/component';
import type { WasmHeap } from '../src/ecs/WasmPoolMemory';
import type { Entity } from '../src/types';
+import { emccPath } from '../../build-tools/utils/emscripten.js';
+import { FakeEngine } from './fakeEngine';
+import { WASM_LINK_FLAGS } from '../../compiler/src/codegen';
-const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const N = 16;
-function findEmcc(): string | null {
- const at = path.join(ROOT, 'tools/emsdk/upstream/emscripten',
- process.platform === 'win32' ? 'emcc.bat' : 'emcc');
- return existsSync(at) ? at : null;
-}
-const EMCC = findEmcc();
+const EMCC = emccPath();
/** The engine module, as far as a compiled system needs one. */
-class Host implements WasmHeap {
- readonly memory = new WebAssembly.Memory({ initial: 256, maximum: 256 });
- HEAPU8 = new Uint8Array(this.memory.buffer);
- private next = 4096;
- _malloc(size: number): number {
- const at = this.next;
- this.next += (size + 15) & ~15;
- return at;
- }
- _free(): void { /* a bump allocator frees nothing */ }
-}
-
/** `Fade`: alpha -= step, in the shape the compiler emits. */
const SYSTEM_C = `#include <stdint.h>
#include <string.h>
@@ -114,8 +99,7 @@ function buildModule(): { bytes: Uint8Array; path: string } {
const out = path.join(dir, 'sys.wasm');
const built = spawnSync(EMCC!, [
'-std=c11', '-O2', '-ffp-contract=off', '-Wall', '-Wextra',
- '--no-entry', '-sSTANDALONE_WASM', '-sIMPORTED_MEMORY',
- '-sERROR_ON_UNDEFINED_SYMBOLS=1', '-sEXPORTED_FUNCTIONS=_es_sys_Fade',
+ ...WASM_LINK_FLAGS, '-sEXPORTED_FUNCTIONS=_es_sys_Fade',
'-o', out, path.join(dir, 'sys.c'),
], { encoding: 'utf8', cwd: dir, shell: process.platform === 'win32' });
if (built.status !== 0) throw new Error(`emcc failed:\n${built.stderr}`);
@@ -176,8 +160,9 @@ describe('installing a built module', () => {
const interpretedEntities = seed(interpreted.world, interpreted.Fade);
const compiled = project();
+ const engine = new FakeEngine();
await installAot({
- world: compiled.world, runner: compiled.runner, host: new Host(),
+ world: compiled.world, runner: compiled.runner, host: engine,
manifest: manifestFor(), wasm, resources: () => undefined,
});
const compiledEntities = seed(compiled.world, compiled.Fade);
@@ -193,12 +178,15 @@ describe('installing a built module', () => {
.toEqual(alphas(interpreted.world, interpreted.Fade, interpretedEntities));
// A world nothing touched would compare two untouched worlds.
expect(alphas(compiled.world, compiled.Fade, compiledEntities)[0]).not.toBeCloseTo(0.1, 10);
+ // Loading wrote a data section, or running spilled to a stack, only if
+ // the engine's own bytes moved. Both land at link-time addresses.
+ expect(engine.staticsIntact()).toBe(true);
});
it.skipIf(!EMCC)('refuses a module built for other component shapes', async () => {
const p = project();
await expect(installAot({
- world: p.world, runner: p.runner, host: new Host(),
+ world: p.world, runner: p.runner, host: new FakeEngine(),
// What a build would have written before `step` was added.
manifest: manifestFor(projectShapeDigest([{ name: 'Fade', fields: ['alpha'] }])),
wasm: moduleFor('a host that takes bytes', buildModule()),
@@ -210,7 +198,7 @@ describe('installing a built module', () => {
const p = project();
const entities = seed(p.world, p.Fade);
await installAot({
- world: p.world, runner: p.runner, host: new Host(),
+ world: p.world, runner: p.runner, host: new FakeEngine(),
manifest: manifestFor(), wasm: moduleFor('a host that takes bytes', buildModule()),
resources: () => undefined,
}).catch(() => { /* the ordering check below is the point */ });
diff --git a/sdk/tests/fakeEngine.ts b/sdk/tests/fakeEngine.ts
new file mode 100644
index 000000000..5b15c0157
--- /dev/null
+++ b/sdk/tests/fakeEngine.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fakeEngine.ts
+ * @brief The engine, as far as a compiled module can tell.
+ *
+ * @details A linear memory and a bump allocator — but shaped like the real one
+ * in the two ways that decide whether a module loads at all, both of
+ * which a plainer fake answers wrongly:
+ *
+ * - the memory GROWS. The engine links with `-sALLOW_MEMORY_GROWTH`,
+ * so its memory declares a maximum of 32768 pages. A module that
+ * declares a smaller one does not run slower, it does not
+ * instantiate: `WebAssembly.Instance` throws a LinkError.
+ * - the low addresses are TAKEN. A linker puts a module's data section
+ * at a fixed low address, and for a module sharing this memory that
+ * is on top of the engine's own statics. A fake that leaves those
+ * bytes zero cannot tell an overwrite from a no-op.
+ */
+import type { WasmHeap } from '../src/ecs/WasmPoolMemory';
+
+/** Where a linker puts a module's data, which is where the engine's statics are. */
+const STATICS_AT = 1024;
+const STATICS_LEN = 4096;
+/** What those bytes hold, so that anything overwriting them is visible. */
+const STATICS_BYTE = 0xab;
+
+export class FakeEngine implements WasmHeap {
+ /** 256 pages because that is the minimum a built module declares it needs. */
+ readonly memory = new WebAssembly.Memory({ initial: 256, maximum: 32768 });
+ HEAPU8 = new Uint8Array(this.memory.buffer);
+ private next = STATICS_AT + STATICS_LEN;
+
+ constructor() { this.statics().fill(STATICS_BYTE); }
+
+ _malloc(size: number): number {
+ const at = this.next;
+ this.next += (size + 15) & ~15;
+ while (this.next > this.HEAPU8.byteLength) {
+ this.memory.grow(1);
+ this.HEAPU8 = new Uint8Array(this.memory.buffer);
+ }
+ return at;
+ }
+
+ _free(): void { /* a bump allocator frees nothing */ }
+
+ /** The bytes the engine owns. Read after loading and after running. */
+ statics(): Uint8Array {
+ return new Uint8Array(this.memory.buffer, STATICS_AT, STATICS_LEN);
+ }
+
+ /** Whether anything wrote where the engine keeps its own data. */
+ staticsIntact(): boolean {
+ return this.statics().every((b) => b === STATICS_BYTE);
+ }
+}
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index b286df7ed..b4b7f75e8 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -36,9 +36,14 @@ add_test(NAME test_tilemap COMMAND test_tilemap)
# fresh); this harness is what holds the generated OFFSETS against the C++
# structs they are claims about. Header-only ECS + Log.cpp, so it builds without
# linking esengine and therefore without emscripten.
+# Both translation units: this host LINKS the artifact, so it reads the
+# declaration table out of it. A wasm host loads the module into the engine's
+# memory instead and must not compile that half — the table is a data section,
+# and its bytes land where the engine already keeps its own.
add_executable(test_aot_host
aot/test_aot_host.cpp
aot/generated/move_system.c
+ aot/generated/move_system_decl.c
${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
)
target_include_directories(test_aot_host PRIVATE
diff --git a/tests/aot/generated/move_system.c b/tests/aot/generated/move_system.c
index cddff8329..e3d6716f7 100644
--- a/tests/aot/generated/move_system.c
+++ b/tests/aot/generated/move_system.c
@@ -1,17 +1,8 @@
/* GENERATED by @estella/compiler — do not edit. */
-/* docs/REARCH_AOT_ABI.md: this file calls the engine zero times. */
+/* This file calls the engine zero times, and holds no data of its own. */
#include "estella_abi.h"
#include "estella_offsets.h"
-/* §2.5: what this module baked in about the engine it was built for. A
- host compares before it maps anything — a mismatch is not a wrong
- answer, it is a read of a different field. The address width belongs
- to the MACHINE, so it mixes in here rather than in the compiler and a
- 32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0x36cbaec9128499cdULL
-const uint64_t es_abi_hash =
- ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
-
void es_sys_MoveSystem(es_addr_t es_ctx) {
const EsSysCtx *es_c = (const EsSysCtx *)ES_PTR(es_ctx);
const EsQueryRows *es_queries = (const EsQueryRows *)ES_PTR(es_c->queries);
@@ -29,14 +20,3 @@ void es_sys_MoveSystem(es_addr_t es_ctx) {
}
}
}
-
-/* The systems in this file, and what each one needs filled in. */
-static const char *const es_sys_MoveSystem_q0_comps[] = { "Transform", "Mover" };
-static const unsigned char es_sys_MoveSystem_q0_mut[] = { 1u, 0u };
-static const EsQueryDecl es_sys_MoveSystem_queries[] = { { es_sys_MoveSystem_q0_comps, es_sys_MoveSystem_q0_mut, 2u } };
-static const char *const es_sys_MoveSystem_resources[] = { "Time" };
-
-const EsSystemDecl es_systems[] = {
- { "MoveSystem", es_sys_MoveSystem, es_sys_MoveSystem_queries, es_sys_MoveSystem_resources, 1u, 1u },
-};
-const uint32_t es_system_count = 1u;
diff --git a/tests/aot/generated/move_system_decl.c b/tests/aot/generated/move_system_decl.c
new file mode 100644
index 000000000..484cb69dd
--- /dev/null
+++ b/tests/aot/generated/move_system_decl.c
@@ -0,0 +1,28 @@
+/* GENERATED by @estella/compiler — do not edit. */
+/* The static half: what this module is, for a host that reads it out of
+ the artifact rather than out of a manifest beside it. Separate because
+ a wasm module sharing the ENGINE's memory must carry no data section —
+ its bytes would land at a link-time address the engine already owns. */
+#include "estella_abi.h"
+
+/* What this module baked in about the engine it was built for. A
+ host compares before it maps anything — a mismatch is not a wrong
+ answer, it is a read of a different field. The address width belongs
+ to the MACHINE, so it mixes in here rather than in the compiler and a
+ 32-bit artifact cannot load into a 64-bit host. */
+#define ES_ABI_ENGINE_DIGEST 0x36cbaec9128499cdULL
+const uint64_t es_abi_hash =
+ ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
+
+void es_sys_MoveSystem(es_addr_t es_ctx);
+
+/* The systems in this file, and what each one needs filled in. */
+static const char *const es_sys_MoveSystem_q0_comps[] = { "Transform", "Mover" };
+static const unsigned char es_sys_MoveSystem_q0_mut[] = { 1u, 0u };
+static const EsQueryDecl es_sys_MoveSystem_queries[] = { { es_sys_MoveSystem_q0_comps, es_sys_MoveSystem_q0_mut, 2u } };
+static const char *const es_sys_MoveSystem_resources[] = { "Time" };
+
+const EsSystemDecl es_systems[] = {
+ { "MoveSystem", es_sys_MoveSystem, es_sys_MoveSystem_queries, es_sys_MoveSystem_resources, 1u, 1u },
+};
+const uint32_t es_system_count = 1u;