About: how pages are checked

tests/sims/frame.test.ts

The automated tests for the /simulators/stack-frame simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.

  1. Local and spilled-argument offsets and the stack reservation match gcc -O0 on 600 random functions.
// /simulators/stack-frame: x86-64 System V stack frame layout, compared with what GCC actually emits.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { layout, parseDecls } from '../../src/lib/sims/frame.ts';
import { lcg } from './check.ts';

let gcc = true;
try { execFileSync('gcc', ['--version']); } catch { gcc = false; }

test('local and spilled-argument offsets and the stack reservation match gcc -O0 on 600 random functions', { skip: !gcc && 'gcc is not installed' }, () => {
	const r = lcg(17);
	const T = ['char', 'short', 'int', 'long', 'double', 'char *', 'float', 'long long'];
	const funcs: { params: string; locals: string; src: string }[] = [];
	for (let k = 0; k < 600; k++) {
		const np = Math.floor(r() * 15), nl = Math.floor(r() * 6);
		const ps = Array.from({ length: np }, (_, i) => `${T[Math.floor(r() * T.length)]} p${i}`);
		const ls = Array.from({ length: nl }, (_, i) => { const t = T[Math.floor(r() * T.length)]; return r() < 0.35 ? `${t} v${i}[${1 + Math.floor(r() * 24)}]` : `${t} v${i}`; });
		// taking every address forces each variable into memory, so gcc gives it a stack slot
		const body = [...ls.map((l, i) => `g((void*)${l.includes('[') ? '' : '&'}v${i});`), ...ps.map((_, i) => `g((void*)&p${i});`), 'g(0);'].join(' ');
		funcs.push({ params: ps.join(', '), locals: ls.join('; '), src: `void g(void*);\nvoid f${k}(${ps.join(', ') || 'void'}) { ${ls.map((l) => l + ';').join(' ')} ${body} }\n` });
	}
	const dir = mkdtempSync(join(tmpdir(), 'frame-'));
	writeFileSync(join(dir, 'r.c'), funcs.map((f) => f.src).join('\n'));
	const asm = execFileSync('gcc', ['-O0', '-fno-stack-protector', '-fno-asynchronous-unwind-tables', '-S', '-o', '-', join(dir, 'r.c')]).toString();
	const blocks = asm.split(/\n(?=f\d+:)/).filter((b) => /^f\d+:/.test(b));
	assert.equal(blocks.length, 600);
	const bad: string[] = [];
	for (const b of blocks) {
		const f = funcs[Number(b.match(/^f(\d+):/)![1])];
		const P = parseDecls(f.params).decls, L = parseDecls(f.locals).decls;
		const lay = layout(P, L, 'sysv64');
		const leas = [...b.matchAll(/leaq\t(-?\d+)\(%rbp\)/g)].map((m) => Number(m[1]));
		const sm = b.match(/subq\t\$(\d+), %rsp/), am = b.match(/addq\t\$-(\d+), %rsp/);
		const sub = Number(sm ? sm[1] : am ? am[1] : 0);
		const want = [
			...L.map((l) => lay.slots.find((s) => s.label === (l.count > 1 ? `${l.name}[${l.count}]` : l.name))!.offset),
			...P.map((p) => (lay.slots.find((s) => s.label === p.name && s.kind === 'spill') ?? lay.slots.find((s) => s.label === p.name))!.offset)
		];
		if (leas.join() !== want.join() || sub !== lay.sub) bad.push(`${f.src.trim()}\n  gcc ${leas.join()} sub ${sub}\n  sim ${want.join()} sub ${lay.sub}`);
	}
	assert.equal(bad.length, 0, `${bad.length} of 600 differ:\n${bad.slice(0, 3).join('\n')}`);
});

Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.

Published