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.

refactor(compiler): an address is the machine's, an offset is the contract's

yhh1dcc58ae4ed7
diff --git a/compiler/src/abi.ts b/compiler/src/abi.ts
index 355853d7e..0af5fd28b 100644
--- a/compiler/src/abi.ts
+++ b/compiler/src/abi.ts
@@ -380,6 +380,18 @@ export function abiHash(layout: AbiLayout, plans: readonly SysPlan[]): string {
return fnv1a64(parts.join('\n'));
}
+/**
+ * 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
+ * an address is an offset into one block, 8 where it is a real pointer.
+ */
+export function abiHashFor(contract: string, addrBytes: 4 | 8): string {
+ const MASK = (1n << 64n) - 1n;
+ const mixed = (BigInt(contract.padStart(16, '0').replace(/^/, '0x'))
+ ^ ((0x9e3779b97f4a7c15n * BigInt(addrBytes)) & MASK)) & MASK;
+ return mixed.toString(16).padStart(16, '0');
+}
+
function fnv1a64(text: string): string {
const MASK = (1n << 64n) - 1n;
let h = 0xcbf29ce484222325n;
diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.ts
index 4f502385a..8cfd38c63 100644
--- a/compiler/src/codegen.ts
+++ b/compiler/src/codegen.ts
@@ -28,7 +28,7 @@
* than what JS computes, and more accurate is still different.
*/
import {
- CMD_DESPAWN, CMD_REMOVE, CMD_WORDS, QUERYROWS_WORDS,
+ CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS, CMD_DESPAWN, CMD_REMOVE,
abiHash, planFor,
type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,
} from './abi';
@@ -47,6 +47,9 @@ export const CFLAGS: readonly string[] = [
'-std=c11', '-O2', '-ffp-contract=off', '-fexcess-precision=standard',
];
+/** The odd constant the width is multiplied by before it is folded in. */
+export const ADDR_MIX = '0x9e3779b97f4a7c15';
+
export interface CModule {
/** `estella_abi.h` — the contract's C side, and the only thing the code calls. */
readonly header: string;
@@ -78,31 +81,71 @@ export const RUNTIME_H = `/* GENERATED by @estella/compiler — do not edit. */
/* A fused multiply-add is MORE accurate than the double rounding JS does, and
more accurate is still a different number. GCC does not implement this pragma
- and warns about it, so the flag in CFLAGS is the one that has to be there;
- this is belt and braces for the compiler that does honour it. */
+ and warns about it, so the flag in CFLAGS is the one that has to be there. */
#if defined(__clang__)
#pragma STDC FP_CONTRACT OFF
#endif
-/* An address in the ABI is a u32 offset into one linear memory. On wasm that
- memory starts at zero, so the offset already IS the pointer; natively the
- host owns a block and hands us its base. Same offsets either way — which is
- what lets one emitted source serve both back ends. */
-#if defined(__wasm__)
-#define ES_MEM ((unsigned char *)0)
-#else
+/* An address is a POINTER, and on wasm32 a pointer IS a 32-bit offset into
+ linear memory — which is why one emitted source serves both back ends. The
+ OFFSETS below are the contract; the address width is the machine, and it is
+ 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
+ harness. Same structs, same offsets, one word wider or narrower. */
+#if defined(ES_ADDR_BASE)
+typedef uint32_t es_addr_t;
extern unsigned char *es_memory;
-#define ES_MEM es_memory
+#define ES_PTR(a) (es_memory + (a))
+#else
+typedef uintptr_t es_addr_t;
+#define ES_PTR(a) ((unsigned char *)(a))
#endif
-/* memcpy, not a cast: the image is a byte block, and a u32 read through an
- aligned pointer is undefined if the host ever hands us an odd base. */
-static inline uint32_t es_u32(uint32_t a) { uint32_t v; memcpy(&v, ES_MEM + a, 4); return v; }
-static inline void es_set_u32(uint32_t a, uint32_t v) { memcpy(ES_MEM + a, &v, 4); }
-static inline double es_f32(uint32_t a) { float v; memcpy(&v, ES_MEM + a, 4); return (double)v; }
-static inline void es_set_f32(uint32_t a, double v) { float f = (float)v; memcpy(ES_MEM + a, &f, 4); }
-static inline double es_f64(uint32_t a) { double v; memcpy(&v, ES_MEM + a, 8); return v; }
-static inline void es_set_f64(uint32_t a, double v) { memcpy(ES_MEM + a, &v, 8); }
+/* §2.2 — 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. */
+typedef struct EsCmd {
+ uint32_t kind;
+ uint32_t a;
+ uint32_t b;
+ uint32_t c;
+} 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. */
+typedef struct EsSysCtx {
+ es_addr_t queries;
+ es_addr_t resources;
+ es_addr_t cmdBuf;
+ es_addr_t cmdCap;
+ es_addr_t cmdCount;
+ es_addr_t events;
+} EsSysCtx;
+
+/* §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
+ (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];
+typedef char es_check_rows[sizeof(EsQueryRows) == ${QUERYROWS_WORDS} * sizeof(es_addr_t) ? 1 : -1];
+typedef char es_check_cmd[sizeof(EsCmd) == ${CMD_WORDS} * 4 ? 1 : -1];
+
+/* memcpy, not a cast through a typed pointer: a component base is whatever the
+ host handed over, and a wider load through an under-aligned pointer is
+ undefined even where the hardware would have allowed it. */
+static inline double es_f32(const unsigned char *p) { float v; memcpy(&v, p, 4); return (double)v; }
+static inline void es_set_f32(unsigned char *p, double v) { float f = (float)v; memcpy(p, &f, 4); }
+static inline double es_f64(const unsigned char *p) { double v; memcpy(&v, p, 8); return v; }
+static inline void es_set_f64(unsigned char *p, double v) { memcpy(p, &v, 8); }
/* ---------------------------------------------------------------------------
Math. Only the operations ECMAScript specifies EXACTLY are in the subset, but
@@ -176,21 +219,29 @@ function offsetMacro(owner: string, path: readonly string[]): string {
return `ES_OFF_${owner}_${path.join('_')}`.replace(/[^A-Za-z0-9_]/g, '_');
}
+/** `double x` but `unsigned char *x` — the star binds to the name, not the type. */
+function decl(type: string, name: string): string {
+ return type.endsWith('*') ? `${type}${name}` : `${type} ${name}`;
+}
+
function cType(t: EirType): string {
switch (t.k) {
case 'f64': return 'double';
case 'bool': return 'int';
case 'entity': return 'uint32_t';
- case 'comp': case 'res': return 'uint32_t';
+ // A component or resource base: the byte address the host handed over,
+ // which every field access adds a constant EHT offset to.
+ case 'comp': case 'res': return 'unsigned char *';
default: throw new Error(`codegen: a ${t.k} is not a C value`);
}
}
-/** Three representations, so a coercion is a lookup rather than a case tree. */
-type Repr = 'double' | 'int' | 'uint32_t';
+/** How a value is held, so a coercion is a lookup rather than a case tree. A
+ * base address is in the list only to be rejected: it is never an operand. */
+type Repr = 'double' | 'int' | 'uint32_t' | 'address';
function repr(t: EirType): Repr {
- return cType(t) as Repr;
+ return t.k === 'comp' || t.k === 'res' ? 'address' : (cType(t) as Repr);
}
/** Convert `text` from one EIR type's representation to another's. */
@@ -198,6 +249,9 @@ function coerce(text: string, from: EirType, to: EirType): string {
const a = repr(from);
const b = repr(to);
if (a === b) return text;
+ if (a === 'address' || b === 'address') {
+ throw new Error('codegen: a component base is an address, not a value to convert');
+ }
if (b === 'double') return `((double)(${text}))`;
if (b === 'int') return a === 'double' ? `((${text}) != 0.0)` : `((${text}) != 0u)`;
return `((uint32_t)(${text}))`;
@@ -283,6 +337,7 @@ function zeroOf(t: EirType): string {
switch (repr(t)) {
case 'double': return '0.0';
case 'int': return '0';
+ case 'address': return '0';
default: return '0u';
}
}
@@ -428,14 +483,15 @@ class Emitter {
* contract's: §3 forbids writing past it, and the host is what sized it.
*/
private emitCommand(s: Stmt & { s: 'emit' }, indent: number): void {
- const kind = s.record === 'despawn' ? CMD_DESPAWN : CMD_REMOVE;
+ const kind = s.record === 'despawn' ? 'ES_CMD_DESPAWN' : 'ES_CMD_REMOVE';
+ const fields = ['a', 'b', 'c'];
this.line(indent, 'if (es_cmd_n < es_cmd_cap) {');
- this.line(indent + 1, `const uint32_t es_at = es_cmd_buf + es_cmd_n * ${CMD_WORDS * 4}u;`);
- this.line(indent + 1, `es_set_u32(es_at, ${kind}u); /* ${s.record} */`);
- for (let i = 1; i < CMD_WORDS; i++) {
- const a = s.args[i - 1];
+ this.line(indent + 1, 'EsCmd *es_at = &es_cmd_buf[es_cmd_n];');
+ this.line(indent + 1, `es_at->kind = ${kind}; /* ${s.record} */`);
+ for (let i = 0; i < CMD_WORDS - 1; i++) {
+ const a = s.args[i];
const v = a ? coerce(this.expr(a), a.type, { k: 'entity' }) : '0u';
- this.line(indent + 1, `es_set_u32(es_at + ${i * 4}u, ${v});`);
+ this.line(indent + 1, `es_at->${fields[i]} = ${v};`);
}
this.line(indent + 1, 'es_cmd_n += 1u;');
this.line(indent, '}');
@@ -453,16 +509,18 @@ class Emitter {
const q = this.plan!.queries[slot.slot]!;
const d = this.depth++;
const stride = 1 + q.length;
- const at = slot.slot * QUERYROWS_WORDS * 4;
+ const k = slot.slot;
const reads = new Set<number>();
readsOf(s.body, reads);
this.line(indent, '{');
- this.line(indent + 1, `const uint32_t es_rows${d} = es_u32(es_queries + ${at}u);`);
- this.line(indent + 1, `const uint32_t es_n${d} = es_u32(es_queries + ${at + 4}u);`);
- this.line(indent + 1, `for (uint32_t es_i${d} = 0u; es_i${d} < es_n${d}; ++es_i${d}) {`);
- this.line(indent + 2, `const uint32_t es_row${d} = es_rows${d} + es_i${d} * ${stride * 4}u;`);
+ this.line(indent + 1,
+ `const es_addr_t *es_rows${d} = (const es_addr_t *)ES_PTR(es_queries[${k}].rows);`);
+ this.line(indent + 1, `const es_addr_t es_n${d} = es_queries[${k}].count;`);
+ this.line(indent + 1, `for (es_addr_t es_i${d} = 0; es_i${d} < es_n${d}; ++es_i${d}) {`);
+ this.line(indent + 2, `const es_addr_t *es_row${d} = es_rows${d} + es_i${d} * ${stride}u;`);
if (s.entity !== null && reads.has(s.entity)) {
- this.line(indent + 2, `const uint32_t ${cName(this.local(s.entity))} = es_u32(es_row${d});`);
+ this.line(indent + 2,
+ `const uint32_t ${cName(this.local(s.entity))} = (uint32_t)es_row${d}[0];`);
}
s.binds.forEach((id, i) => {
// A bound component nobody reads is not loaded. The row is still
@@ -470,7 +528,7 @@ class Emitter {
// body's — dropping the load is free, dropping the column is not.
if (!reads.has(id)) return;
this.line(indent + 2,
- `const uint32_t ${cName(this.local(id))} = es_u32(es_row${d} + ${(i + 1) * 4}u);`);
+ `unsigned char *${cName(this.local(id))} = ES_PTR(es_row${d}[${i + 1}]);`);
});
this.stmts(s.body, indent + 2);
this.line(indent + 1, '}');
@@ -481,7 +539,7 @@ class Emitter {
/** A module-level pure function: numbers in, one number out, no world. */
fn(f: EirFn): void {
this.bind([...f.params, ...f.locals]);
- const params = f.params.map((p) => `${cType(p.type)} ${cName(p)}`).join(', ');
+ const params = f.params.map((p) => decl(cType(p.type), cName(p))).join(', ');
this.line(0, `static ${cType(f.ret)} ${cFn(f.name)}(${params || 'void'}) {`);
this.declare(f.locals, null, 1);
this.stmts(f.body, 1);
@@ -498,27 +556,33 @@ class Emitter {
const bound = new Set<number>();
loopBound(sys.body, bound);
- this.line(0, `void ${cSymbol(sys.name)}(uint32_t es_ctx) {`);
- if (plan.queries.length > 0) this.line(1, 'const uint32_t es_queries = es_u32(es_ctx);');
+ this.line(0, `void ${cSymbol(sys.name)}(es_addr_t es_ctx) {`);
+ this.line(1, 'const EsSysCtx *es_c = (const EsSysCtx *)ES_PTR(es_ctx);');
+ if (plan.queries.length > 0) {
+ this.line(1, 'const EsQueryRows *es_queries = (const EsQueryRows *)ES_PTR(es_c->queries);');
+ }
const usesRes = sys.params.some((p) => plan.slots.get(p.id)!.table === 'res' && reads.has(p.id));
- if (usesRes) this.line(1, 'const uint32_t es_resources = es_u32(es_ctx + 4u);');
+ if (usesRes) {
+ this.line(1, 'const es_addr_t *es_resources = (const es_addr_t *)ES_PTR(es_c->resources);');
+ }
const emits = hasEmit(sys.body);
if (emits) {
- this.line(1, 'const uint32_t es_cmd_buf = es_u32(es_ctx + 8u);');
- this.line(1, 'const uint32_t es_cmd_cap = es_u32(es_ctx + 12u);');
- this.line(1, 'const uint32_t es_cmd_at = es_u32(es_ctx + 16u);');
- this.line(1, 'uint32_t es_cmd_n = es_u32(es_cmd_at);');
+ this.line(1, 'EsCmd *es_cmd_buf = (EsCmd *)ES_PTR(es_c->cmdBuf);');
+ this.line(1, 'const uint32_t es_cmd_cap = (uint32_t)es_c->cmdCap;');
+ this.line(1, 'uint32_t *es_cmd_at = (uint32_t *)ES_PTR(es_c->cmdCount);');
+ this.line(1, 'uint32_t es_cmd_n = *es_cmd_at;');
}
+ if (plan.queries.length === 0 && !usesRes && !emits) this.line(1, '(void)es_c;');
// A resource base is one indirection, resolved once at entry rather than
// per row: the host already put the address in the table.
for (const p of sys.params) {
const slot = plan.slots.get(p.id)!;
if (slot.table !== 'res' || !reads.has(p.id)) continue;
- this.line(1, `const uint32_t ${cName(p)} = es_u32(es_resources + ${slot.slot * 4}u);`);
+ this.line(1, `unsigned char *${cName(p)} = ES_PTR(es_resources[${slot.slot}]);`);
}
this.declare(sys.locals.filter((l) => !bound.has(l.id)), reads, 1);
this.stmts(sys.body, 1);
- if (emits) this.line(1, 'es_set_u32(es_cmd_at, es_cmd_n);');
+ if (emits) this.line(1, '*es_cmd_at = es_cmd_n;');
this.line(0, '}');
this.line(0, '');
}
@@ -530,7 +594,7 @@ class Emitter {
*/
private declare(locals: readonly Local[], reads: ReadonlySet<number> | null, indent: number): void {
for (const l of locals) {
- this.line(indent, `${cType(l.type)} ${cName(l)} = ${zeroOf(l.type)};`);
+ this.line(indent, `${decl(cType(l.type), cName(l))} = ${zeroOf(l.type)};`);
if (reads && !reads.has(l.id)) this.line(indent, `(void)${cName(l)};`);
}
}
@@ -573,8 +637,13 @@ export function emitC(module: EirModule, layout: AbiLayout, systems: readonly Ei
'#include "estella_abi.h"',
'',
'/* §2.5: the loader compares this before it maps anything. A mismatch is',
- ' not a wrong answer, it is a read of a different field. */',
- `const uint64_t es_abi_hash = 0x${hash}ULL;`,
+ ' not a wrong answer, it is a read of a different field.',
+ ' The address width belongs to the MACHINE, not to the contract, so it',
+ ' mixes in here rather than in the compiler: one hash per (contract,',
+ ' width) pair, and a 32-bit artifact cannot load into a 64-bit host. */',
+ `#define ES_ABI_CONTRACT_HASH 0x${hash}ULL`,
+ 'const uint64_t es_abi_hash =',
+ ` ES_ABI_CONTRACT_HASH ^ (${ADDR_MIX}ULL * (uint64_t)sizeof(es_addr_t));`,
'',
'/* Component and resource field offsets, from EHT. */',
...macros,
diff --git a/compiler/src/index.ts b/compiler/src/index.ts
index 00964ac58..b9c0ce8f0 100644
--- a/compiler/src/index.ts
+++ b/compiler/src/index.ts
@@ -10,9 +10,9 @@ export { verifySystem, type VerifyError } from './verify';
export { runSystem, type EirWorld, type Fns, type Row } from './interp';
export { inlineModule, inlineSystem } from './inline';
export {
- AbiMemory, abiHash, abiHost, flushCommands, materialize, packLayout, planFor, runOnAbi,
+ AbiMemory, abiHash, abiHashFor, abiHost, flushCommands, materialize, packLayout, planFor, runOnAbi,
CMD_DESPAWN, CMD_REMOVE, CMD_WORDS, QUERYROWS_WORDS, SYSCTX_WORDS,
type AbiCall, type AbiLayout, type FieldOffsets, type Leaf, type SysPlan,
} from './abi';
-export { CFLAGS, RUNTIME_H, cSymbol, emitC, type CModule } from './codegen';
+export { ADDR_MIX, CFLAGS, RUNTIME_H, 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 80b7d3f8a..0bbd955a0 100644
--- a/compiler/tests/codegen.test.ts
+++ b/compiler/tests/codegen.test.ts
@@ -40,6 +40,7 @@ import { inlineSystem } from '../src/inline';
import { builtinShapes } from '../src/builtins';
import { AbiMemory, flushCommands, materialize, packLayout, planFor, runOnAbi } from '../src/abi';
import { CFLAGS, cSymbol, emitC, type CModule } from '../src/codegen';
+import { abiHashFor } from '../src/abi';
import type { AbiLayout } from '../src/abi';
import type { EirSystem } from '../src/eir';
import type { Row } from '../src/interp';
@@ -85,32 +86,97 @@ const MAIN_C = `/* Test scaffolding, not compiler output. */
#endif
#include "estella_abi.h"
+#if defined(ES_ADDR_BASE)
unsigned char *es_memory;
+#endif
+
+void ES_ENTRY(es_addr_t ctx);
-void ES_ENTRY(uint32_t ctx);
+static unsigned char *img;
+
+#if !defined(ES_ADDR_BASE)
+static uint32_t rd32(uint32_t off) { uint32_t v; memcpy(&v, img + off, 4); return v; }
+
+/*
+ * The other address model: the image carries a ctx of OFFSETS, and this rebuilds
+ * it out of real pointers. Every write the system makes still lands inside the
+ * image, which is what makes the two models comparable byte for byte.
+ */
+static es_addr_t at(uint32_t off) { return (es_addr_t)(uintptr_t)(img + off); }
+
+static es_addr_t relocate(uint32_t ctxOff, int nq, const int *comps, int nres) {
+ static EsSysCtx c;
+ EsQueryRows *qs = (EsQueryRows *)calloc((size_t)(nq > 0 ? nq : 1), sizeof(EsQueryRows));
+ es_addr_t *res = (es_addr_t *)calloc((size_t)(nres > 0 ? nres : 1), sizeof(es_addr_t));
+ uint32_t qOff = rd32(ctxOff);
+ uint32_t rOff = rd32(ctxOff + 4u);
+ int k, j;
+ for (k = 0; k < nq; ++k) {
+ uint32_t rowsOff = rd32(qOff + (uint32_t)(k * 2) * 4u);
+ uint32_t count = rd32(qOff + (uint32_t)(k * 2 + 1) * 4u);
+ uint32_t stride = (uint32_t)comps[k] + 1u;
+ uint32_t n = count * stride, i;
+ es_addr_t *rows = (es_addr_t *)calloc(n > 0 ? n : 1, sizeof(es_addr_t));
+ for (i = 0; i < n; ++i) {
+ uint32_t w = rd32(rowsOff + i * 4u);
+ /* Slot 0 of a row is an entity id, not an address. */
+ rows[i] = (i % stride == 0u) ? (es_addr_t)w : at(w);
+ }
+ qs[k].rows = (es_addr_t)(uintptr_t)rows;
+ qs[k].count = count;
+ }
+ for (j = 0; j < nres; ++j) res[j] = at(rd32(rOff + (uint32_t)j * 4u));
+ c.queries = (es_addr_t)(uintptr_t)qs;
+ c.resources = (es_addr_t)(uintptr_t)res;
+ c.cmdBuf = at(rd32(ctxOff + 8u));
+ c.cmdCap = rd32(ctxOff + 12u);
+ c.cmdCount = at(rd32(ctxOff + 16u));
+ c.events = 0;
+ return (es_addr_t)(uintptr_t)&c;
+}
+#endif
int main(int argc, char **argv) {
long n;
- uint32_t ctx;
- if (argc != 3) { fprintf(stderr, "usage: run <bytes> <ctx>\\n"); return 2; }
+ uint32_t ctxOff;
+ int nq, nres, i;
+ int comps[16];
+ if (argc < 5) { fprintf(stderr, "usage: run <bytes> <ctx> <nres> <nq> [comps...]\\n"); return 2; }
n = strtol(argv[1], NULL, 10);
- ctx = (uint32_t)strtoul(argv[2], NULL, 10);
- es_memory = (unsigned char *)malloc((size_t)n);
- if (!es_memory) return 3;
+ ctxOff = (uint32_t)strtoul(argv[2], NULL, 10);
+ nres = (int)strtol(argv[3], NULL, 10);
+ nq = (int)strtol(argv[4], NULL, 10);
+ if (nq > 16 || argc < 5 + nq) { fprintf(stderr, "too many queries\\n"); return 6; }
+ for (i = 0; i < nq; ++i) comps[i] = (int)strtol(argv[5 + i], NULL, 10);
+ img = (unsigned char *)malloc((size_t)n);
+ if (!img) return 3;
#if defined(_WIN32)
/* Text mode would insert a 0x0d before every 0x0a in the image. */
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
- if (fread(es_memory, 1, (size_t)n, stdin) != (size_t)n) return 4;
- ES_ENTRY(ctx);
- if (fwrite(es_memory, 1, (size_t)n, stdout) != (size_t)n) return 5;
+ if (fread(img, 1, (size_t)n, stdin) != (size_t)n) return 4;
+#if defined(ES_ADDR_BASE)
+ es_memory = img;
+ (void)nres; (void)nq; (void)comps;
+ ES_ENTRY((es_addr_t)ctxOff);
+#else
+ ES_ENTRY(relocate(ctxOff, nq, comps, nres));
+#endif
+ if (fwrite(img, 1, (size_t)n, stdout) != (size_t)n) return 5;
return 0;
}
`;
-/** Build one executable per system; the entry symbol is a -D, so main is shared. */
-function build(dir: string, cModule: CModule, symbol: string): string {
+/**
+ * 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++
+ * engine). Same generated source, compiled twice.
+ */
+type Addressing = 'offset' | 'pointer';
+
+function build(dir: string, cModule: CModule, symbol: string, how: Addressing = 'offset'): string {
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'estella_abi.h'), cModule.header);
writeFileSync(join(dir, 'systems.c'), cModule.source);
@@ -118,6 +184,7 @@ function build(dir: string, cModule: CModule, symbol: string): string {
const exe = join(dir, `${symbol}${process.platform === 'win32' ? '.exe' : ''}`);
const out = spawnSync(CC!, [
...CFLAGS, '-Wall', '-Wextra',
+ ...(how === 'offset' ? ['-DES_ADDR_BASE'] : []),
`-DES_ENTRY=${symbol}`,
'-o', exe,
join(dir, 'main.c'), join(dir, 'systems.c'),
@@ -132,9 +199,17 @@ function build(dir: string, cModule: CModule, symbol: string): string {
/** One call of the contract: materialise, run the compiled code, flush. */
function frameOfC(exe: string, mem: AbiMemory, sys: EirSystem): void {
- const call = materialize(mem, planFor(sys));
+ const plan = planFor(sys);
+ const call = materialize(mem, plan);
const image = Buffer.from(mem.buffer);
- const out = execFileSync(exe, [String(image.length), String(call.ctx)], {
+ // The shape of the ctx, which a pointer-addressing host needs in order to
+ // rebuild it. A real host knows this from the system it is calling.
+ const shape = [
+ String(plan.resources.length),
+ String(plan.queries.length),
+ ...plan.queries.map((q) => String(q.length)),
+ ];
+ const out = execFileSync(exe, [String(image.length), String(call.ctx), ...shape], {
input: image,
maxBuffer: image.length * 2 + (1 << 16),
});
@@ -340,6 +415,26 @@ describe('the emitted C says what the interpreter says', () => {
}
});
+ it('the same source addressed as pointers gives the same image', () => {
+ // Why the address is a machine property: the C++ engine hands over
+ // 64-bit component pointers, which no 32-bit offset can name. Compiling
+ // the SAME file both ways makes that claim checkable.
+ const move = systemOf(shipped, 'MoveSystem');
+ const layout = packLayout(shipped.module.comps);
+ const c = emitC(shipped.module, layout, [move]);
+ const byOffset = build(join(tmp, 'addr-off'), c, cSymbol('MoveSystem'), 'offset');
+ const byPointer = build(join(tmp, 'addr-ptr'), c, cSymbol('MoveSystem'), 'pointer');
+
+ const a = movedWorld(layout);
+ const b = movedWorld(layout);
+ for (let f = 0; f < FRAMES; f++) {
+ frameOfC(byOffset, a, move);
+ frameOfC(byPointer, b, move);
+ expect(same(a, b), `address models diverged at frame ${f}`).toBe(true);
+ }
+ expect(same(a, movedWorld(layout)), 'nothing moved, so agreeing proves nothing').toBe(false);
+ });
+
it('the object file has nothing to import but the memory it lives in', () => {
const layout = packLayout(shipped.module.comps);
const cModule = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);
@@ -365,6 +460,8 @@ describe('the emitted C says what the interpreter says', () => {
.filter((l) => /\s[Uu]\s/.test(l))
.map((l) => l.trim().split(/\s+/).pop()!)
.filter((s) => s !== 'es_memory');
+ // Compiled WITHOUT ES_ADDR_BASE, so there is not even a memory base to
+ // resolve: an address is a pointer and the object file is closed.
expect(undef, 'a compiled system may not call the engine').toEqual([]);
});
@@ -372,7 +469,7 @@ describe('the emitted C says what the interpreter says', () => {
const layout = packLayout(shipped.module.comps);
const move = systemOf(shipped, 'MoveSystem');
const a = emitC(shipped.module, layout, [move]);
- expect(a.source).toContain(`0x${a.hash}ULL`);
+ expect(a.source).toContain(`#define ES_ABI_CONTRACT_HASH 0x${a.hash}ULL`);
// The same system with its parameters swapped reads the ctx tables in
// the other order, so the loader has to refuse it. §2.5.
@@ -380,6 +477,43 @@ describe('the emitted C says what the interpreter says', () => {
expect(emitC(shipped.module, layout, [swapped]).hash).not.toBe(a.hash);
});
+ it('what the artifact exports is what a host computes, at both widths', () => {
+ // The C compiler folds it out of the contract hash and its own
+ // sizeof(es_addr_t), so ask one for both widths and compare against the
+ // TS side a loader would use.
+ const layout = packLayout(shipped.module.comps);
+ const c = emitC(shipped.module, layout, [systemOf(shipped, 'MoveSystem')]);
+ const dir = join(tmp, 'handshake');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'estella_abi.h'), c.header);
+ writeFileSync(join(dir, 'systems.c'), c.source);
+ writeFileSync(join(dir, 'main.c'), [
+ '#include <stdio.h>',
+ '#include "estella_abi.h"',
+ 'extern const uint64_t es_abi_hash;',
+ '#if defined(ES_ADDR_BASE)',
+ 'unsigned char *es_memory;',
+ '#endif',
+ 'int main(void) {',
+ ' printf("%016llx %d\\n", (unsigned long long)es_abi_hash, (int)sizeof(es_addr_t));',
+ ' return 0;',
+ '}',
+ ].join('\n'));
+
+ 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' });
+ expect(built.status, built.stderr).toBe(0);
+ expect(built.stderr.trim()).toBe('');
+ const [got, width] = execFileSync(exe, { encoding: 'utf8' }).trim().split(' ');
+ // 8 only where the platform's pointers are; a 32-bit host would say 4
+ // and the assertion below would then be about the width it really has.
+ expect(abiHashFor(c.hash, Number(width) as 4 | 8)).toBe(got);
+ if (flags.length > 0) expect(Number(width)).toBe(bytes);
+ }
+ });
+
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')]);