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.

test(aot): a module cannot be paired with another build's manifest

esengineafbf73a1abf8
diff --git a/compiler/src/abi.ts b/compiler/src/abi.ts
index 27e262751..f62f6470a 100644
--- a/compiler/src/abi.ts
+++ b/compiler/src/abi.ts
@@ -22,7 +22,7 @@ import {
CMD_WORDS as CMD_WORDS_, CMD_DESPAWN as CMD_DESPAWN_, CMD_REMOVE as CMD_REMOVE_,
EVENT_OUT_WORDS as EVENT_OUT_WORDS_,
QUERYROWS_WORDS as QUERYROWS_WORDS_, SYSCTX_WORDS as SYSCTX_WORDS_,
- engineAbiDigest, projectShapeDigest, type ShapeDigestInput,
+ engineAbiDigest, fnv1a64, projectShapeDigest, type ShapeDigestInput,
} from '../../sdk/src/ecs/aot/abiDigest';
import { resourceNames } from './builtins';
import { resourceBlockBytes, resourceMethodBit } from '../../sdk/src/ecs/resourceShapes';
@@ -487,6 +487,13 @@ export function runOnAbi(sys: EirSystem, mem: AbiMemory, layout: AbiLayout, fns:
export interface AbiHandshake {
readonly engineAbi: string;
readonly projectShapes: string;
+ /**
+ * Which BUILD this is: the artifact bakes it and the sidecar carries the
+ * same number, so a loader can ask what neither digest above answers — are
+ * these two halves one build? An IDENTITY proof, so both come from this one
+ * value. Not the engine or the width; `engineAbi` answers those.
+ */
+ readonly moduleContract: string;
}
export function abiHandshake(
@@ -510,12 +517,32 @@ export function abiHandshake(
if (!shape || shape.storage !== 'host') continue;
shapes.push({ name, fields: [...shape.fields.keys()] });
}
+ const engineAbi = engineAbiDigest(addressBytes);
+ const projectShapes = projectShapeDigest(shapes);
return {
- engineAbi: engineAbiDigest(addressBytes),
- projectShapes: projectShapeDigest(shapes),
+ engineAbi,
+ projectShapes,
+ moduleContract: fnv1a64([projectShapes, ...plans.map(contractLine)].join('\n')),
};
}
+/**
+ * One system's declaration as the runtime reads it: what it queries and may
+ * write, what it resources, and the event payload layout its compiled code
+ * baked in. Everything a host or a runtime takes from the sidecar rather than
+ * from the code.
+ */
+function contractLine(p: SysPlan): string {
+ const channel = (c: { slot: number; event: string }) => `${c.slot}:${c.event}`;
+ return [
+ p.system,
+ p.queries.map((q) => q.map((a) => `${a.comp}${a.mut ? '!' : ''}`).join(',')).join(';'),
+ p.resources.map((r) => `${r.name}${r.mut ? '!' : ''}`).join(','),
+ p.readers.map(channel).join(','),
+ p.writers.map(channel).join(','),
+ ].join('|');
+}
+
/**
* The constant the artifact actually exports, for a host that has to compare.
* `addrBytes` is `sizeof(es_addr_t)` on the side doing the comparing — 4 where
diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.ts
index acdd7c1b7..a72c6ee83 100644
--- a/compiler/src/codegen.ts
+++ b/compiler/src/codegen.ts
@@ -32,7 +32,7 @@ import { EXACT_COEFFICIENTS as EX } from '../../sdk/src/math/exact';
import {
CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS, EVENT_OUT_WORDS, CMD_DESPAWN, CMD_REMOVE,
abiHandshake, planFor,
- type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,
+ type AbiHandshake, type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,
} from './abi';
import {
BOOL, F64,
@@ -93,7 +93,7 @@ export interface CModule {
* 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 };
+ readonly handshake: AbiHandshake;
}
// =============================================================================
@@ -878,6 +878,14 @@ export function emitC(
'#include "estella_abi.h"',
'#include "estella_offsets.h"',
'',
+ // Functions rather than a constant: a module sharing the engine's
+ // memory may carry no data section, and both roads compile this file.
+ '/* Which BUILD this is, for a loader holding the sidecar written beside',
+ ' it. The two digests above answer "is this engine right" and "are the',
+ ' project shapes right"; neither answers "are these two the same pair". */',
+ `ES_EXPORT uint32_t es_module_contract_lo(void) { return 0x${handshake.moduleContract.slice(8)}u; }`,
+ `ES_EXPORT uint32_t es_module_contract_hi(void) { return 0x${handshake.moduleContract.slice(0, 8)}u; }`,
+ '',
...bodies,
].join('\n');
const decls = [
diff --git a/compiler/tests/abi.test.ts b/compiler/tests/abi.test.ts
index 6c8d01a49..abc09f94d 100644
--- a/compiler/tests/abi.test.ts
+++ b/compiler/tests/abi.test.ts
@@ -19,7 +19,9 @@ import { lowerProgram } from '../src/frontend';
import { verifySystem } from '../src/verify';
import { runSystem, type EirWorld, type Row } from '../src/interp';
import { builtinShapes } from '../src/builtins';
-import { AbiMemory, packLayout, runOnAbi } from '../src/abi';
+import { AbiMemory, abiHandshake, packLayout, runOnAbi, type SysPlan } from '../src/abi';
+import { emitC } from '../src/codegen';
+import { inlineSystem } from '../src/inline';
import { moveSystem } from '../../examples/ecs-basics/src/systems/move';
import { lifetimeSystem } from '../../examples/ecs-basics/src/systems/lifetime';
@@ -164,3 +166,49 @@ describe('the ABI is sufficient for the systems the subset compiles', () => {
// shipped artifact — an empty wasm import section — and wasm.test.ts asks it
// of the artifact itself.
});
+
+/**
+ * Two builds of one engine, over one project's shapes, agree on both digests
+ * while declaring different queries, mut flags and event payloads — and those
+ * are what a runtime's bookkeeping reads out of the sidecar. Probed against
+ * real artifacts before this existed: same engineAbi, same projectShapes.
+ */
+describe('which build a module is', () => {
+ const shape = new Map([['Mover', { storage: 'host' as const, fields: new Map([['speed', 'f32']]) }]]);
+
+ /** One system's plan, as `planFor` would hand it over. */
+ const plan = (over: Partial<SysPlan> = {}): SysPlan => ({
+ system: 'MoveSystem', queries: [[{ comp: 'Mover', mut: true }]],
+ resources: [], channels: [], readers: [], writers: [],
+ slots: new Map(), ...over,
+ } as SysPlan);
+
+ const contractOf = (p: SysPlan) => abiHandshake(shape as never, [p], 8).moduleContract;
+
+ it('changes when a mut flag does, where neither other digest can', () => {
+ const writes = plan();
+ const reads = plan({ queries: [[{ comp: 'Mover', mut: false }]] });
+ const a = abiHandshake(shape as never, [writes], 8);
+ const b = abiHandshake(shape as never, [reads], 8);
+ expect(a.engineAbi).toBe(b.engineAbi);
+ expect(a.projectShapes).toBe(b.projectShapes);
+ expect(a.moduleContract).not.toBe(b.moduleContract);
+ });
+
+ it('changes for a resource, a reader and a writer alike', () => {
+ const base = contractOf(plan());
+ expect(contractOf(plan({ resources: [{ name: 'Score', mut: true }] }))).not.toBe(base);
+ expect(contractOf(plan({ readers: [{ slot: 0, event: 'Hit' }] }))).not.toBe(base);
+ expect(contractOf(plan({ writers: [{ slot: 0, event: 'Hit' }] }))).not.toBe(base);
+ });
+
+ it('is what the artifact bakes, in the halves a data-free module can carry', () => {
+ const fixture = resolve(ROOT, 'compiler/tests/fixtures/in-subset.ts');
+ const lowered = lowerProgram([fixture], builtinShapes());
+ const move = lowered.module.systems.find((s) => s.name === 'FixturePing')!;
+ const c = emitC(lowered.module, packLayout(lowered.module.comps),
+ [inlineSystem(move, lowered.module.fns)], 8);
+ expect(c.source).toContain(`es_module_contract_lo(void) { return 0x${c.handshake.moduleContract.slice(8)}u; }`);
+ expect(c.source).toContain(`es_module_contract_hi(void) { return 0x${c.handshake.moduleContract.slice(0, 8)}u; }`);
+ });
+});
diff --git a/compiler/tests/generated.test.ts b/compiler/tests/generated.test.ts
index 0d044e591..6e8c03175 100644
--- a/compiler/tests/generated.test.ts
+++ b/compiler/tests/generated.test.ts
@@ -107,6 +107,9 @@ describe('the C artifacts the engine builds against', () => {
'/* GENERATED by @estella/compiler — do not edit. */',
'/* The contract half of the handshake. The width half is the harness. */',
`#define ES_EXPECTED_CONTRACT_HASH 0x${c.handshake.engineAbi}ULL`,
+ '/* And which BUILD the artifact beside this one is, which the sidecar',
+ ' written with it has to carry too. */',
+ `#define ES_EXPECTED_MODULE_CONTRACT 0x${c.handshake.moduleContract}ULL`,
'',
].join('\n'));
});
diff --git a/native/host/bindings/AotBindings.cpp b/native/host/bindings/AotBindings.cpp
index cf2e290d6..cd568dd1e 100644
--- a/native/host/bindings/AotBindings.cpp
+++ b/native/host/bindings/AotBindings.cpp
@@ -38,6 +38,7 @@
#include "esengine/aot/AotDispatcher.hpp"
#include "esengine/aot/EngineDigest.generated.h"
+#include <cstdio>
#include <deque>
#include <string>
#include <unordered_map>
@@ -147,6 +148,19 @@ JSValue js_index(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
return JS_NewInt32(ctx, at == aot::Dispatcher::npos ? -1 : static_cast<int>(at));
}
+/**
+ * es_aot_contract() -> which BUILD the open module is, as 16 hex digits, or ""
+ * where it cannot say. The SDK holds the sidecar written beside it and is the
+ * only half that can compare the two.
+ */
+JSValue js_contract(JSContext* ctx, JSValueConst, int, JSValueConst*) {
+ const std::uint64_t value = state().dispatcher.contract();
+ if (value == 0) return JS_NewString(ctx, "");
+ char hex[17];
+ std::snprintf(hex, sizeof(hex), "%016llx", static_cast<unsigned long long>(value));
+ return JS_NewString(ctx, hex);
+}
+
/** es_aot_bound(i) -> whether that system resolved; an unbound one interprets. */
JSValue js_bound(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
if (argc < 1) return JS_FALSE;
@@ -277,6 +291,7 @@ void registerAotBindings(HostState& h, JSValue global) {
fn("es_aot_install", js_install, 1);
fn("es_aot_index", js_index, 1);
fn("es_aot_bound", js_bound, 1);
+ fn("es_aot_contract", js_contract, 0);
fn("es_aot_script_rows", js_scriptRows, 8);
fn("es_aot_resource", js_resource, 3);
fn("es_aot_run", js_run, 2);
diff --git a/pipeline/src/bundle/buildCompiledSystems.ts b/pipeline/src/bundle/buildCompiledSystems.ts
index c4ac1e765..6a5e84345 100644
--- a/pipeline/src/bundle/buildCompiledSystems.ts
+++ b/pipeline/src/bundle/buildCompiledSystems.ts
@@ -65,6 +65,9 @@ export interface CompiledSystemsManifest {
*/
engineAbi: string;
projectShapes: string;
+ /** Which BUILD this is: the artifact bakes the same number, so a loader can
+ * refuse a module paired with another build's sidecar. */
+ moduleContract: string;
systems: CompiledSystemInfo[];
}
@@ -293,6 +296,7 @@ export async function buildCompiledSystems(
const manifest: CompiledSystemsManifest = {
engineAbi: c.handshake.engineAbi,
projectShapes: c.handshake.projectShapes,
+ moduleContract: c.handshake.moduleContract,
systems: inlined.map((sys) => {
const plan = planFor(sys);
return {
diff --git a/pipeline/tests/build-compiled-systems.test.ts b/pipeline/tests/build-compiled-systems.test.ts
index 726964316..8efa8591b 100644
--- a/pipeline/tests/build-compiled-systems.test.ts
+++ b/pipeline/tests/build-compiled-systems.test.ts
@@ -389,3 +389,55 @@ describe('the AOT build step, for a host that loads a library', () => {
expect(out.errors[0]).not.toMatch(/emsdk/);
});
});
+
+
+/**
+ * Two builds of one engine over one project's shapes. Probed before the pairing
+ * existed: both produced the SAME engineAbi and the SAME projectShapes, and the
+ * artifact's baked handshake is a pure function of those — so a runtime reading
+ * the wrong sidecar's mut flags had nothing to stop it.
+ */
+describe('which build a native artifact is', () => {
+ const COMPONENTS_2 = `import { defineComponent } from 'esengine';
+export const Mover = defineComponent('Mover', { speed: 100, directionX: 1, directionY: 0 });
+`;
+ const WRITES_TRANSFORM = `import { defineSystem, Query, Mut, Transform } from 'esengine';
+import { Mover } from './components';
+/** @compiled */
+export const moveSystem = defineSystem(
+ [Query(Mut(Transform), Mover)],
+ (query) => { for (const [, t, m] of query) { t.position.x += m.speed; } },
+ { name: 'MoveSystem' },
+);
+`;
+ const WRITES_MOVER = `import { defineSystem, Query, Mut, Transform } from 'esengine';
+import { Mover } from './components';
+/** @compiled */
+export const moveSystem = defineSystem(
+ [Query(Transform, Mut(Mover))],
+ (query) => { for (const [, t, m] of query) { m.speed = t.position.x; } },
+ { name: 'MoveSystem' },
+);
+`;
+
+ it.skipIf(!HOST_CC)('separates two builds the other digests cannot', async () => {
+ const build = (src: string) => buildCompiledSystems(
+ project({ 'src/components.ts': COMPONENTS_2, 'src/systems.ts': src }),
+ { mode: 'release', target: 'native', cc: HOST_CC, run });
+ const a = await build(WRITES_TRANSFORM);
+ const b = await build(WRITES_MOVER);
+ expect(a.errors).toEqual([]);
+ expect(b.errors).toEqual([]);
+
+ // The two really are different modules: one writes Transform, one Mover.
+ expect(JSON.stringify(a.manifest!.systems)).not.toEqual(JSON.stringify(b.manifest!.systems));
+ // And neither digest that existed can say so.
+ expect(a.manifest!.engineAbi).toBe(b.manifest!.engineAbi);
+ expect(a.manifest!.projectShapes).toBe(b.manifest!.projectShapes);
+ // This one can, which is the whole of its job.
+ expect(a.manifest!.moduleContract).not.toBe(b.manifest!.moduleContract);
+ // And the same build twice is the same pair, or it would refuse itself.
+ expect((await build(WRITES_TRANSFORM)).manifest!.moduleContract)
+ .toBe(a.manifest!.moduleContract);
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 978140819..7fb314d8c 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -542,6 +542,7 @@ WasmHeap & { readonly memory: WebAssembly.Memory }
## AotManifest — interface @experimental
```
engineAbi: string
+moduleContract: string | undefined
projectShapes: string
systems: readonly AotSystemDecl[]
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 0cdfe7764..db6fca58f 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -542,6 +542,7 @@ WasmHeap & { readonly memory: WebAssembly.Memory }
## AotManifest — interface @experimental
```
engineAbi: string
+moduleContract: string | undefined
projectShapes: string
systems: readonly AotSystemDecl[]
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index f4b239d2b..4df0d017c 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -537,6 +537,7 @@ WasmHeap & { readonly memory: WebAssembly.Memory }
## AotManifest — interface @experimental
```
engineAbi: string
+moduleContract: string | undefined
projectShapes: string
systems: readonly AotSystemDecl[]
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 2b2d4c05e..00fa50506 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -537,6 +537,7 @@ WasmHeap & { readonly memory: WebAssembly.Memory }
## AotManifest — interface @experimental
```
engineAbi: string
+moduleContract: string | undefined
projectShapes: string
systems: readonly AotSystemDecl[]
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index efd196df0..925e3b806 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -537,6 +537,7 @@ WasmHeap & { readonly memory: WebAssembly.Memory }
## AotManifest — interface @experimental
```
engineAbi: string
+moduleContract: string | undefined
projectShapes: string
systems: readonly AotSystemDecl[]
```
diff --git a/sdk/src/ecs/aot/AotSystems.ts b/sdk/src/ecs/aot/AotSystems.ts
index c24dd7b57..998bce267 100644
--- a/sdk/src/ecs/aot/AotSystems.ts
+++ b/sdk/src/ecs/aot/AotSystems.ts
@@ -44,6 +44,13 @@ export interface AotManifest {
readonly engineAbi: string;
/** The project's own component shapes, scoped to the ones it names. */
readonly projectShapes: string;
+ /**
+ * Which BUILD this sidecar belongs to. The artifact bakes the same number,
+ * so the two can be asked the question neither digest above answers: are
+ * these halves from one run? Optional only for a module built before it
+ * existed, which a loader treats as unpaired rather than as paired.
+ */
+ readonly moduleContract?: string;
readonly systems: readonly AotSystemDecl[];
}
@@ -118,6 +125,13 @@ export class AotSystems {
* could bind only some of it still loaded all of it. Default: all.
*/
runs: (name: string) => boolean = () => true,
+ /**
+ * What the ARTIFACT says it was built as, or null where this road
+ * cannot ask it. Two builds over one engine and one project agree on
+ * both digests below while declaring different queries, mut flags and
+ * event payloads — which is what the bookkeeping here reads.
+ */
+ moduleContract: string | null = null,
): void {
// Two questions with two fixes, so two answers rather than one that can
// only say "something moved".
@@ -128,6 +142,13 @@ export class AotSystems {
+ 'Rebuild the module against this engine — a wrong offset reads a different '
+ 'field rather than failing.');
}
+ if (moduleContract !== null && manifest.moduleContract !== moduleContract) {
+ throw new Error(
+ `AOT module refused: the module was built as ${moduleContract} and the manifest `
+ + `beside it says ${manifest.moduleContract ?? '(nothing)'}. They are from `
+ + 'different builds — the declarations this runtime reads are not the ones the '
+ + 'module compiled. Rebuild both.');
+ }
const shapes = projectShapeDigest(scriptShapes(manifest, resolve, resourceFields));
if (manifest.projectShapes !== shapes) {
throw new Error(
diff --git a/sdk/src/ecs/aot/installAot.ts b/sdk/src/ecs/aot/installAot.ts
index 8ee314c9d..aaf3c0cc0 100644
--- a/sdk/src/ecs/aot/installAot.ts
+++ b/sdk/src/ecs/aot/installAot.ts
@@ -82,6 +82,18 @@ export async function installAot(opts: InstallAotOptions): Promise<AotRuntime> {
* world's first pooled component, and a runner may not exist until the first
* frame. A caller holding the result attaches it when it does.
*/
+/**
+ * What the module says it was built as. Two exported functions rather than a
+ * constant: a module sharing the engine's memory carries no data section.
+ */
+function moduleContractOf(exports: Readonly<Record<string, unknown>>): string | null {
+ const lo = exports['es_module_contract_lo'];
+ const hi = exports['es_module_contract_hi'];
+ if (typeof lo !== 'function' || typeof hi !== 'function') return null;
+ const half = (n: number) => (n >>> 0).toString(16).padStart(8, '0');
+ return half((hi as () => number)()) + half((lo as () => number)());
+}
+
export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'>): Promise<AotRuntime> {
const memory = new WasmPoolMemory(opts.host);
opts.world.useScriptPoolMemory(memory);
@@ -98,7 +110,7 @@ export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'>): Promi
opts.resourceFields ?? ((name) => {
const value = opts.resources(name);
return value === undefined ? undefined : Object.keys(value);
- }));
+ }), 4, () => true, moduleContractOf(exports));
const runtime: AotRuntime = {
systems,
diff --git a/sdk/src/ecs/aot/installNativeAot.ts b/sdk/src/ecs/aot/installNativeAot.ts
index d9dabefce..ab6f65df3 100644
--- a/sdk/src/ecs/aot/installNativeAot.ts
+++ b/sdk/src/ecs/aot/installNativeAot.ts
@@ -42,6 +42,9 @@ export interface NativeAotBindings {
resource(name: string, offset: number, bytes: number): boolean;
run(index: number, scriptEpoch: number): number;
reset(): void;
+ /** Which BUILD the module is, or '' where the host cannot say — an older
+ * runtime template, which is unpaired and not paired. */
+ contract?(): string;
}
export interface InstallNativeAotOptions {
@@ -109,6 +112,7 @@ export function nativeAotBindings(
run: (index, scriptEpoch) =>
(run as (i: number, e: number) => number)(index, scriptEpoch),
reset: call<void>('es_aot_reset', undefined as void),
+ contract: call<string>('es_aot_contract', ''),
};
}
@@ -152,8 +156,12 @@ export function installNativeAot(opts: InstallNativeAotOptions): AotRuntime | nu
throw new Error(`AOT: ${decl.name} is the host's to call, not this runtime's`);
};
}
+ // The artifact is the host's to read here, so the pairing comes back from
+ // it rather than off an export this side can reach.
+ const paired = bindings.contract?.() ?? '';
systems.install(opts.manifest, exports, (name) => getComponent(name),
- () => [], NATIVE_ADDRESS_BYTES, (name) => byName.has(name));
+ () => [], NATIVE_ADDRESS_BYTES, (name) => byName.has(name),
+ paired === '' ? null : paired);
// Every script component any twin names, so one epoch change re-reports all
// of them rather than whichever twin happened to run first.
diff --git a/sdk/tests/aot-native-install.test.ts b/sdk/tests/aot-native-install.test.ts
index 4aaa13146..a27125245 100644
--- a/sdk/tests/aot-native-install.test.ts
+++ b/sdk/tests/aot-native-install.test.ts
@@ -325,3 +325,58 @@ describe('a capability a loading host cannot hand compiled code', () => {
expect(f.calls).toEqual(['PlainSystem']);
});
});
+
+
+/**
+ * Probed against two real native builds before this existed: one writing
+ * Transform, one writing Mover, same engine and same components — SAME
+ * engineAbi, SAME projectShapes, and the artifact's baked hash is a pure
+ * function of those. Nothing paired a sidecar to the module it describes.
+ */
+describe('a module and the sidecar written beside it', () => {
+ const PAIRED = 'aaaabbbbccccdddd';
+ const paired = (contract: string | null): AotManifest => ({
+ ...MANIFEST,
+ moduleContract: contract ?? undefined,
+ });
+
+ function install(manifest: AotManifest, hostSays: string | undefined) {
+ const order = manifest.systems.map((s) => s.name);
+ const bindings: NativeAotBindings = {
+ install: () => order.length,
+ index: (name) => order.indexOf(name),
+ bound: () => true,
+ scriptRows: () => true,
+ resource: () => true,
+ run: () => 0,
+ reset: () => {},
+ ...(hostSays === undefined ? {} : { contract: () => hostSays }),
+ };
+ declareDrift();
+ const world = new World();
+ return () => installNativeAot({
+ world, runner: new SystemRunner(world, new ResourceStorage()),
+ modulePath: 'systems.dll', manifest, heap: fakeHeap(), bindings,
+ });
+ }
+
+ it('are refused when they are from different builds', () => {
+ expect(install(paired('0123456789abcdef'), PAIRED)).toThrow(/different builds/);
+ });
+
+ it('are refused when the module is paired and the sidecar predates pairing', () => {
+ expect(install(paired(null), PAIRED)).toThrow(/different builds/);
+ });
+
+ it('install when they agree', () => {
+ expect(install(paired(PAIRED), PAIRED)).not.toThrow();
+ });
+
+ /** A host too old to answer cannot be asked; that is unpaired, and it is
+ * the one case this cannot turn into a refusal without breaking every
+ * runtime template built before the question existed. */
+ it('install where the host cannot say which build the module is', () => {
+ expect(install(paired(PAIRED), '')).not.toThrow();
+ expect(install(paired(PAIRED), undefined)).not.toThrow();
+ });
+});
diff --git a/src/esengine/aot/AotDispatcher.hpp b/src/esengine/aot/AotDispatcher.hpp
index c5a4aefc1..e439329d3 100644
--- a/src/esengine/aot/AotDispatcher.hpp
+++ b/src/esengine/aot/AotDispatcher.hpp
@@ -64,6 +64,10 @@ public:
/** How many systems the module declared — bound or not. */
std::size_t count() const { return bound_.size(); }
+ /** Which BUILD the open module is, or 0 where it cannot say. The SDK holds
+ * the sidecar and is the half that can compare. */
+ std::uint64_t contract() const { return module_.contract(); }
+
/** The declared name at that index, or an empty string out of range. */
const char* nameAt(std::size_t i) const { return i < names_.size() ? names_[i] : ""; }
diff --git a/src/esengine/aot/AotModule.hpp b/src/esengine/aot/AotModule.hpp
index f0a60b4a8..070c651b8 100644
--- a/src/esengine/aot/AotModule.hpp
+++ b/src/esengine/aot/AotModule.hpp
@@ -44,6 +44,7 @@ public:
close();
handle_ = std::exchange(other.handle_, nullptr);
systems_ = std::exchange(other.systems_, {});
+ contract_ = std::exchange(other.contract_, 0);
}
return *this;
}
@@ -75,9 +76,17 @@ public:
return fail("it was built against a different engine or address width");
}
systems_ = std::span<const EsSystemDecl>(decls, *count);
+ contract_ = readContract_();
return true;
}
+ /**
+ * Which BUILD this module is, for a caller holding the sidecar written
+ * beside it. Zero where the module predates it — which the caller must read
+ * as "cannot say", never as "paired".
+ */
+ std::uint64_t contract() const { return contract_; }
+
bool isOpen() const { return handle_ != nullptr; }
/** Every system this module carries, as the artifact declares them. */
@@ -94,13 +103,28 @@ public:
void close() {
// The declarations live IN the library, so they stop existing with it.
systems_ = {};
+ contract_ = 0;
core::closeLibrary(handle_);
handle_ = nullptr;
}
private:
+ /**
+ * Two functions rather than one constant: a module that shares the engine's
+ * memory may carry no data section, and the same translation unit serves
+ * both roads. Absent means a module built before pairing existed.
+ */
+ std::uint64_t readContract_() const {
+ using Half = std::uint32_t (*)();
+ auto* lo = reinterpret_cast<Half>(core::librarySymbol(handle_, "es_module_contract_lo"));
+ auto* hi = reinterpret_cast<Half>(core::librarySymbol(handle_, "es_module_contract_hi"));
+ if (lo == nullptr || hi == nullptr) return 0;
+ return (static_cast<std::uint64_t>(hi()) << 32) | lo();
+ }
+
void* handle_ = nullptr;
std::span<const EsSystemDecl> systems_{};
+ std::uint64_t contract_ = 0;
};
} // namespace esengine::aot
diff --git a/tests/aot/generated/move_system.c b/tests/aot/generated/move_system.c
index f29fd3ccd..297d748fa 100644
--- a/tests/aot/generated/move_system.c
+++ b/tests/aot/generated/move_system.c
@@ -3,6 +3,12 @@
#include "estella_abi.h"
#include "estella_offsets.h"
+/* Which BUILD this is, for a loader holding the sidecar written beside
+ it. The two digests above answer "is this engine right" and "are the
+ project shapes right"; neither answers "are these two the same pair". */
+ES_EXPORT uint32_t es_module_contract_lo(void) { return 0x714ea1e3u; }
+ES_EXPORT uint32_t es_module_contract_hi(void) { return 0x10bf77bbu; }
+
ES_EXPORT 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);
diff --git a/tests/aot/generated/move_system_hash.h b/tests/aot/generated/move_system_hash.h
index 062d08ee5..cdbca52d7 100644
--- a/tests/aot/generated/move_system_hash.h
+++ b/tests/aot/generated/move_system_hash.h
@@ -1,3 +1,6 @@
/* GENERATED by @estella/compiler — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
#define ES_EXPECTED_CONTRACT_HASH 0xaa8849ed8d31d9a0ULL
+/* And which BUILD the artifact beside this one is, which the sidecar
+ written with it has to carry too. */
+#define ES_EXPECTED_MODULE_CONTRACT 0x10bf77bb714ea1e3ULL
diff --git a/tests/aot/test_aot_host.cpp b/tests/aot/test_aot_host.cpp
index 281c7c9ce..f575b0c16 100644
--- a/tests/aot/test_aot_host.cpp
+++ b/tests/aot/test_aot_host.cpp
@@ -47,6 +47,8 @@ extern "C" {
/** The compiled system. One symbol, and it calls nothing. */
void es_sys_MoveSystem(es_addr_t ctx);
extern const std::uint64_t es_abi_hash;
+std::uint32_t es_module_contract_lo();
+std::uint32_t es_module_contract_hi();
/** The manifest: what the artifact says its systems need filled in. */
extern const EsSystemDecl es_systems[];
extern const std::uint32_t es_system_count;
@@ -241,6 +243,15 @@ TEST_CASE("the host and the artifact agree on the handshake") {
CHECK(es_abi_hash == aot::abiHash(ES_EXPECTED_CONTRACT_HASH));
}
+// Which BUILD the artifact is, for a loader holding the sidecar beside it: two
+// builds agree on the handshake above while declaring different mut flags. Two
+// functions, because a module sharing the engine's memory has no data section.
+TEST_CASE("the artifact says which build it is") {
+ const std::uint64_t said =
+ (static_cast<std::uint64_t>(es_module_contract_hi()) << 32) | es_module_contract_lo();
+ CHECK(said == ES_EXPECTED_MODULE_CONTRACT);
+}
+
TEST_CASE("the artifact says what it needs, and nobody writes that list twice") {
const EsSystemDecl* decl = declOf("MoveSystem");
REQUIRE(decl != nullptr);