import assert from 'node:assert/strict'; import {writeFileSync} from 'node:fs'; import {basename, join, resolve} from 'node:path'; import {pathToFileURL} from 'node:url'; import {inspectDurationLedger} from './k2100-duration-window-proof.mjs'; const words = b => Array.from({length: b.length / 8}, (_, i) => b.readBigUInt64LE(i * 8)); const checksum = s => Buffer.from(s, 'latin1').reduce((a, b) => (a + b) & 255, 0).toString(16).padStart(2, '0'); // Run the exact frozen capture assertions on saved bytes. This has no QMP or // debugger connection and cannot create a new guest observation. export async function createProfileReplay({source, outputDirectory, readArtifact}) { const text = readArtifact(source).toString(); const headerEnd = text.indexOf('export async function captureProfile('); const start = text.indexOf(' const data={};for(const[name,size]of Object.entries(profileSymbols))'); const end = text.indexOf(' checkpoint.evidence=e;'); assert.ok(headerEnd > 0 && start > headerEnd && end > start); const path = join(outputDirectory, 'profile-replay.mjs'); writeFileSync(path, text.slice(0, headerEnd) + ` export async function replay({original, stage, cpuCount, memoryMiB, symbols, readArtifact}) { const checkpoint={stage}, consumed=[]; async function capture(name,val,size,symbol) { assert.ok(Number.isSafeInteger(val)&&Number.isSafeInteger(size)&&size>0); assert.ok(val>=0x40000000&&val+size<=0x40000000+memoryMiB*1048576); const request=original.captures[consumed.length];assert.ok(request); for(const[k,v]of Object.entries({name,val,size,symbol}))assert.equal(request[k],v); const bytes=readArtifact(original.dumps[name]);assert.equal(bytes.length,size); consumed.push(name);return bytes; } ` + text.slice(start, end) + ` assert.deepEqual(consumed,original.captures.map(r=>r.name)); assert.deepEqual(consumed,Object.keys(original.dumps)); return {physicalReads:consumed.length}; } `); return {path, replay: (await import(pathToFileURL(resolve(path)).href)).replay}; } export function inspectProfileClosure({physical, cpuCount, memoryMiB, symbols, image, readArtifact}) { const captures = physical.profileCheckpoints; assert.deepEqual(captures.map(c => c.stage), [1, 2, 3, 4, 5, 6, 7, 8, 9]); const data = captures.map(c => Object.fromEntries(Object.entries(c.dumps).map(([k, a]) => [k, readArtifact(a)]))); const evidence = data.map(d => words(d.OS_K2045_EVIDENCE)); const n = BigInt(cpuCount - 1), base = symbols._image_start.address; const layoutSymbol = symbols.OS_K1000_AUTHORITY_LAYOUT_EXPECTED; const layout = image.subarray(layoutSymbol.address - base, layoutSymbol.address - base + layoutSymbol.size); assert.equal(layout.length, 192); const ledgers = data.slice(0, 8).map(d => inspectDurationLedger(d.authority, layout, memoryMiB)); const initial = ledgers[0], returned = ledgers[7]; const equalInventory = (a, b) => { for (const key of ['owner', 'free', 'live', 'reserved', 'authorizedPages']) assert.deepEqual(a[key], b[key], key); }; for (const [i, d] of data.entries()) { assert.equal(captures[i].cpuCount, cpuCount); assert.deepEqual(evidence[i].slice(0, 2), [2100n, BigInt(i + 1)]); assert.equal(evidence[i][14], BigInt(cpuCount)); for (const key of Object.keys(d).filter(k => /_LAYOUT$/.test(k))) { const s = symbols[key]; assert.ok(s && s.size === d[key].length); assert.deepEqual(d[key], image.subarray(s.address - base, s.address - base + s.size), key); } const calls = words(d.OS_K2045_CALLS), call = index => calls.slice(index * 6, index * 6 + 6); assert.deepEqual(call(0), [0xc4000004n, 0n, 0n, 0n, 0n, 1n]); for (let cpu = 1; cpu < cpuCount; cpu++) { assert.deepEqual(call(cpu), [0xc4000004n, BigInt(cpu), 0n, 0n, 1n, 1n]); if (i >= 1) { assert.deepEqual(call(cpu + 3), [0xc4000003n, BigInt(cpu), evidence[i][11], evidence[i][29 + cpu], 0n, 1n]); assert.deepEqual(call(cpu + 6), [0xc4000004n, BigInt(cpu), 0n, 0n, 0n, 1n]); } if (i >= 5) { const off = call(cpu + 9); assert.deepEqual(off.slice(0, 5), [0xc4000004n, BigInt(cpu), 0n, 0n, 1n]); assert.ok(off[5] > 0n, 'fresh affinity query confirms firmware off'); assert.equal(words(d.OS_K2045_RECEIPTS)[(cpu - 1) * 64], 6n); } else assert.deepEqual(call(cpu + 9), Array(6).fill(0n)); } if (i < 8) { const ledger = ledgers[i]; assert.equal(ledger.owner, initial.owner); assert.equal(ledger.authorizedPages, initial.authorizedPages); assert.deepEqual(d.authority.subarray(0, Number(words(layout)[5])), data[0].authority.subarray(0, Number(words(layout)[5]))); if (i > 0) assert.ok(ledger.generation >= ledgers[i - 1].generation); if (i < 7) equalInventory(ledger, initial); } } assert.equal(initial.reservedPages, 32n * n); assert.equal(returned.reservedPages, 0n); assert.equal(returned.livePages, initial.livePages - n); assert.equal(returned.freePages, initial.freePages + 33n * n); assert.equal(returned.freePages, evidence[7][3]); const mailboxes = evidence[0].slice(30, 30 + Number(n)); assert.deepEqual(returned.live, initial.live.filter(r => !mailboxes.includes(r[1]))); for (let cpu = 0; cpu < Number(n); cpu++) { assert.equal(initial.live.filter(r => r[1] === mailboxes[cpu]).length, 1); const executive = evidence[0][33 + cpu]; assert.equal(initial.reserved.filter(r => r[1] === executive && r[2] === executive + 131072n).length, 1); for (const [a, b] of [[mailboxes[cpu], mailboxes[cpu] + 4096n], [executive, executive + 131072n]]) assert.ok(returned.free.some(r => r[0] <= a && r[1] >= b)); for (const stage of [6, 7]) for (const name of ['mailbox' + cpu, 'executive' + cpu]) assert.ok(data[stage][name].every(v => v === 0), 'zero bytes remain zero through release'); } const workers = physical.checkpoints[1], workerData = Object.fromEntries(Object.entries(workers.dumps).map(([k, a]) => [k, readArtifact(a)])); const workerLedger = inspectDurationLedger(workerData.authority, layout, memoryMiB); assert.equal(workerLedger.authorizedPages, initial.authorizedPages); assert.equal(workerLedger.livePages, initial.livePages + 5n * n); const records = words(workerData.OS_K2100_WORKER_RECORDS); for (let cpu = 1; cpu < cpuCount; cpu++) { const start = records[cpu * 32 + 5]; assert.ok(ledgers[3].free.some(r => r[0] <= start && r[1] >= start + 20480n), 'worker pages returned before quiescence'); } assert.ok(data[8].OS_K2045_PRIMARY_STACK.every(v => v === 0)); assert.equal(evidence[8][81], evidence[8][83]); assert.equal(evidence[8][85], evidence[8][86]); assert.equal(evidence[8][87], 1n); return {checkpoints: 9, configuredCpus: cpuCount, firmwareOff: Number(n), centralAuthorizedPages: Number(initial.authorizedPages), returnedWorkerPages: Number(5n * n), zeroedMailboxAndExecutivePages: Number(33n * n), primaryZeroBytes: 69632, primarySpRestored: true, primaryDescriptorRestored: true}; } // Bind the nine profile captures to QMP addresses, exact raw bytes, ordered // pauses and their sole one-byte acknowledgement writes. The separately proved // workload exchanges are the only other permitted operations in this interval. export function inspectProfileProvenance({physical, symbols, qmp, timeline, wholeRsp, readArtifact}) { const index = rows => { const map = new Map(); rows.forEach((r, i) => {const id = r.message ? r.message.id : r.id; if (id !== null && id !== undefined) {const key = r.direction + ':' + id; assert.ok(!map.has(key)); map.set(key, {row: r, index: i});}}); return map; }; const qi = index(qmp), ri = index(wholeRsp), qids = new Set(), rids = new Set(); let previousQmp = -1, previousRsp = -1, firstQmp, firstRsp, physicalReads = 0; for (const capture of physical.profileCheckpoints) { const steps = timeline.filter(r => r.stage === 21050 + capture.stage); const requests = steps.filter(r => r.kind === 'qmp'), exchanges = steps.filter(r => r.kind === 'rsp'); assert.deepEqual(requests.map(r => r.execute), ['stop', 'query-status', ...capture.captures.map(() => 'pmemsave'), 'cont', 'query-status']); assert.deepEqual(requests.slice(2, -2).map(r => r.id), capture.captures.map(r => r.requestId)); assert.deepEqual(steps, [...requests.slice(0, -2), ...exchanges, ...requests.slice(-2)]); for (const [i, request] of requests.entries()) { const tx = qi.get('tx:' + request.id), rx = qi.get('rx:' + request.id); assert.ok(tx && rx && tx.index > previousQmp && rx.index > tx.index); assert.equal(tx.row.message.execute, request.execute); assert.equal(rx.row.message.error, undefined); if (request.execute === 'query-status') assert.equal(rx.row.message.return.status, i === 1 ? 'paused' : 'running'); else assert.deepEqual(rx.row.message.return, {}); if (request.execute === 'pmemsave') { const c = capture.captures[i - 2], a = tx.row.message.arguments; assert.deepEqual(Object.keys(a).sort(), ['filename', 'size', 'val']); assert.equal(a.val, c.val); assert.equal(a.size, c.size); assert.equal(readArtifact(capture.dumps[c.name]).length, c.size); assert.equal(basename(a.filename), `profile-${capture.stage}-${c.name}.bin`); assert.equal(basename(capture.dumps[c.name].path), basename(a.filename)); physicalReads++; } else assert.equal(tx.row.message.arguments, undefined); qids.add(request.id); firstQmp ??= tx.index; previousQmp = rx.index; } assert.equal(capture.gateAddress, symbols.OS_K2045_CAPTURE_GATE.address); const address = capture.gateAddress.toString(16); const payloads = [`m${address},1`, '00', `M${address},1:01`, 'OK', `m${address},1`, '01']; assert.equal(exchanges.length, 6); assert.deepEqual(capture.rsp.filter(r => r.id !== null).map(r => r.payload), payloads); for (const [i, step] of exchanges.entries()) { const key = step.direction + ':' + step.id, item = ri.get(key); assert.ok(item && item.index > previousRsp); assert.equal(step.direction, i % 2 ? 'rx' : 'tx'); assert.equal(item.row.payload, payloads[i]); assert.equal(item.row.packet, '$' + payloads[i] + '#' + checksum(payloads[i])); assert.deepEqual(item.row, capture.rsp[i]); if (i % 2) assert.equal(step.id, exchanges[i - 1].id); rids.add(key); firstRsp ??= item.index; previousRsp = item.index; } } const workloadStages = new Set([21000, 21001, ...physical.windowCheckpoints.map((_, i) => 21101 + i)]); for (const step of timeline) if (workloadStages.has(step.stage)) { if (step.kind === 'qmp') qids.add(step.id); else if (step.kind === 'rsp') rids.add(step.direction + ':' + step.id); else assert.fail('unknown workload operation'); } for (const row of qmp.slice(firstQmp, previousQmp + 1)) if (row.direction === 'tx' && !qids.has(row.message.id)) { assert.equal(row.message.execute, 'query-status', 'no unreported host write'); assert.equal(qi.get('rx:' + row.message.id)?.row.message.return?.status, 'running'); } for (const row of wholeRsp.slice(firstRsp, previousRsp + 1)) if (row.id !== null) assert.ok(rids.has(row.direction + ':' + row.id), 'no unreported debugger operation'); return {profileCheckpoints: 9, physicalReads, permittedGateWrites: 9, resultWrites: 0, fullProfileIntervalRestricted: true}; }