gdp-wired 0.55.0 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,7 +29,9 @@ import { Refusal, pathOf } from "./extract-read.js";
29
29
  import { buildCheck, builtEvidence, compileLimit, stubbed } from "./extract-step.js";
30
30
  import { goNames, readGo, unsignedDomains } from "./extract-go.js";
31
31
  import { speak } from "./extract-go-check.js";
32
- import { clangDump, constantsOf, flagsFor, node, readC } from "./c/reader.js";
32
+ import { SafetyUncoveredRefusal, clangDump, constantsOf, flagsFor, node, readC, scrubbedClangEnv } from "./c/reader.js";
33
+ import { analyzeCSafety, replaySafety, uncheckedCSafety } from "./c/safety.js";
34
+ export { cSafetyArtifactOf, verifyCSafetyProof } from "./c/safety.js";
33
35
  export { minimizeRun, minimizeRunDetailed, proveRule, proveSteps } from "./dsl.js";
34
36
  // (C++ that includes little, embedded code's without the standard library: its whole dump is small, read whole; else
35
37
  // only the class's, its headers' being hundreds of MB)
@@ -38,7 +40,7 @@ function smallTU(file, flags, clang) {
38
40
  const k = `${clang} ${flags.join(' ')} ${file}`;
39
41
  if (!smallTUs.has(k)) {
40
42
  try {
41
- smallTUs.set(k, node('node:child_process').execFileSync(clang, ['-x', 'c++', ...flags, '-E', '-P', file], { encoding: 'utf8', maxBuffer: 1 << 26, stdio: ['ignore', 'pipe', 'ignore'] }).length < 400_000);
43
+ smallTUs.set(k, node('node:child_process').execFileSync(clang, ['-x', 'c++', ...flags, '-E', '-P', file], { encoding: 'utf8', maxBuffer: 1 << 26, stdio: ['ignore', 'pipe', 'ignore'], env: scrubbedClangEnv() }).length < 400_000);
42
44
  }
43
45
  catch {
44
46
  smallTUs.set(k, false);
@@ -73,7 +75,7 @@ export function readCFile(file, opts, cpp = false) {
73
75
  throw new Refusal(file, ok.length ? `several classes write their state (${ok.map(r => r.c.entry).join(', ')}): name one (entry)` : `no class whose methods write its state${why.length ? ` (${why.join('; ')})` : ''}: name the entry`);
74
76
  return ok[0];
75
77
  }
76
- const flags0 = [...flagsFor(file, opts.compileCommands), ...(opts.flags ?? [])], flags = cpp && !flags0.some(f => f.startsWith('-std=')) ? [...flags0, '-std=c++17'] : flags0, { tu, target } = clangDump(file, flags, opts.clang ?? (cpp ? 'clang++' : 'clang'), cpp, cpp && !smallTU(file, flags, opts.clang ?? 'clang++') ? opts.entry : undefined);
78
+ const flags0 = [...flagsFor(file, opts.compileCommands), ...(opts.flags ?? [])], flags = cpp && !flags0.some(f => f.startsWith('-std=')) ? [...flags0, '-std=c++17'] : flags0, { tu, target } = clangDump(file, flags, opts.clang ?? (cpp ? 'clang++' : 'clang'), cpp, cpp && !smallTU(file, flags, opts.clang ?? 'clang++') ? opts.entry : undefined, !!opts.safety, opts.root);
77
79
  // (C++, its dump filtered to the class: each variable outside it the class reads, a namespace's constant, dumped too)
78
80
  if (cpp && opts.entry && !smallTU(file, flags, opts.clang ?? 'clang++')) {
79
81
  const have = new Set(), want = new Map();
@@ -115,25 +117,42 @@ export function readCFile(file, opts, cpp = false) {
115
117
  if (!opts.entry) {
116
118
  // (each struct by its tag or a typedef's name, an unnamed one's typedef too, that a function of the file takes a
117
119
  // pointer to first)
118
- const firsts = new Set((tu.inner ?? []).filter(n => n.kind === 'FunctionDecl' && n.inner?.some(c => c.kind === 'CompoundStmt')).map(n => n.inner.find(c => c.kind === 'ParmVarDecl')?.type?.qualType.replace(/\b(const|volatile|struct)\b|\*/g, '').trim()).filter((t) => !!t));
120
+ const firsts = new Set((tu.inner ?? []).filter(n => n.kind === 'FunctionDecl' && n.inner?.some(c => c.kind === 'CompoundStmt')).flatMap(n => {
121
+ const p = n.inner.find(c => c.kind === 'ParmVarDecl');
122
+ const qs = [p?.type?.qualType, ...(opts.safety ? [p?.type?.desugaredQualType] : [])];
123
+ return qs.map(q => q?.replace(/\b(const|volatile|struct)\b|\*/g, '').trim()).filter((t) => !!t);
124
+ }));
119
125
  const typedefNames = (tu.inner ?? []).filter(n => n.kind === 'TypedefDecl' && (n.inner ?? []).some(c => /Record|Elaborated/.test(c.kind))).map(n => String(n.name));
120
126
  const names = [...new Set([...(tu.inner ?? []).filter(n => n.kind === 'RecordDecl' && n.name && n.completeDefinition).map(n => String(n.name)), ...typedefNames])].filter(n => firsts.has(n));
127
+ const safetyMethods = opts.safety ? ((opts.functions ?? opts.methods)?.map(f => f.split('/')[0]) ?? []) : [];
128
+ let firstRefusal;
121
129
  const ok = names.filter(n => { try {
122
- const c = readC(file, n, tu, target, cpp, opts.root);
123
- readGo(c.pkg, { methods: c.methods });
130
+ const c = readC(file, n, tu, target, cpp, opts.root, {}, safetyMethods, [], [], opts.safety);
131
+ if (!opts.safety)
132
+ readGo(c.pkg, { methods: c.methods });
124
133
  return true;
125
134
  }
126
135
  catch (e) {
127
- if (e instanceof Refusal)
136
+ if (e instanceof Refusal) {
137
+ firstRefusal ??= e;
128
138
  return false;
139
+ }
129
140
  throw e;
130
141
  } });
142
+ const finishRead = (entryName) => {
143
+ const methods = (opts.functions ?? opts.methods)?.map(f => f.split('/')[0]);
144
+ const c = readC(file, entryName, tu, target, cpp, opts.root, Object.fromEntries((opts.functions ?? []).filter(f => f.includes('/')).map(f => [f.split('/')[0], Number(f.split('/')[1])])), methods ?? [], opts.leave ?? [], [...Object.keys(opts.answers ?? {}), ...(opts.cut ?? [])], opts.safety);
145
+ return { c, flags };
146
+ };
131
147
  // (none: the file's globals, where its functions keep the state there)
132
148
  if (!ok.length && !cpp) {
149
+ if (opts.safety && firstRefusal)
150
+ throw firstRefusal;
133
151
  const stem = file.replace(/^.*\//, '').replace(/\.[^.]*$/, '');
134
152
  try {
135
- const r = readCFile(file, { ...opts, entry: stem }, cpp);
136
- readGo(r.c.pkg, { methods: r.c.methods, ...(opts.onError ? { onError: opts.onError } : {}) });
153
+ const r = opts.safety ? finishRead(stem) : readCFile(file, { ...opts, entry: stem }, cpp);
154
+ if (!opts.safety)
155
+ readGo(r.c.pkg, { methods: r.c.methods, ...(opts.onError ? { onError: opts.onError } : {}) });
137
156
  return r;
138
157
  }
139
158
  catch (e) {
@@ -146,12 +165,16 @@ export function readCFile(file, opts, cpp = false) {
146
165
  }
147
166
  if (ok.length !== 1)
148
167
  throw new Refusal(file, ok.length ? `several structs written by the file's functions (${ok.join(', ')}): name one (entry)` : 'no struct the file\'s functions write: name the entry');
149
- return readCFile(file, { ...opts, entry: ok[0] }, cpp);
168
+ return opts.safety ? finishRead(ok[0]) : readCFile(file, { ...opts, entry: ok[0] }, cpp);
150
169
  }
151
- return { c: readC(file, opts.entry, tu, target, cpp, opts.root, Object.fromEntries((opts.functions ?? []).filter(f => f.includes('/')).map(f => [f.split('/')[0], Number(f.split('/')[1])])), (opts.functions ?? opts.methods ?? []).map(f => f.split('/')[0]), opts.leave ?? [], [...Object.keys(opts.answers ?? {}), ...(opts.cut ?? [])]), flags };
170
+ const methods = (opts.functions ?? opts.methods)?.map(f => f.split('/')[0]);
171
+ const c = readC(file, opts.entry, tu, target, cpp, opts.root, Object.fromEntries((opts.functions ?? []).filter(f => f.includes('/')).map(f => [f.split('/')[0], Number(f.split('/')[1])])), methods ?? [], opts.leave ?? [], [...Object.keys(opts.answers ?? {}), ...(opts.cut ?? [])], opts.safety);
172
+ return { c, flags };
152
173
  }
153
174
  export function extractC(at, given = {}, cpp = false) {
154
175
  const notes = [], file = pathOf(at), fns = given.methods ?? given.functions, opts = { ...given, ...(fns ? { functions: fns } : {}) };
176
+ if (opts.safety)
177
+ return extractCSafety(file, opts, cpp);
155
178
  let read, c, flags;
156
179
  try {
157
180
  ;
@@ -177,6 +200,65 @@ export function extractC(at, given = {}, cpp = false) {
177
200
  const x = fromModel(read.model, `${c.entry}.${cpp ? 'cpp' : 'c'}`, { ...unsignedDomains(read), ...signedDomains(c.pkg, read), ...opts.domains }, notes, (rule, sorts) => checkC(file, flags, c, read, rule, sorts, opts, cpp));
178
201
  return { ...x, leaves: read.leaves, names: goNames(read), ...(Object.keys(consts).length ? { consts } : {}) };
179
202
  }
203
+ function extractCSafety(file, opts, cpp) {
204
+ const notes = ['C safety: first-fault model over the covered C subset; proven obligations are verified by checkLaws, broken obligations are replayed under ASan/UBSan.'];
205
+ const unchecked = (where, what, safety = uncheckedCSafety()) => ({ ok: false, refusals: [{ where, what }], notes, safety });
206
+ if (cpp)
207
+ return unchecked(file, 'C safety does not cover C++');
208
+ if (opts.skip?.length || opts.leave?.length || opts.cut?.length || Object.keys(opts.answers ?? {}).length || Object.keys(opts.domains ?? {}).length || opts.onError === 'discard')
209
+ return unchecked(file, 'C safety does not accept skipped code, inferred/overridden inputs, narrowed domains, or discarded normal failures');
210
+ if ((opts.methods !== undefined && !opts.methods.length) || (opts.functions !== undefined && !opts.functions.length))
211
+ return unchecked(file, 'C safety does not accept an empty methods list');
212
+ if (opts.clang !== undefined)
213
+ return unchecked(file, 'C safety does not accept a custom compiler (clang option)');
214
+ if (opts.compileCommands || opts.flags?.some(f => f === '-I-' || f.startsWith('-I=') || !/^(?:-std=(?:c|gnu)(?:99|11|17|23)|-I.+|-D[A-Za-z_]\w*(?:=.*)?)$/.test(f)))
215
+ return unchecked(file, 'C safety does not cover custom compiler flags (except -std=c99/c11/c17/c23 or GNU modes, -I, and -D)');
216
+ try {
217
+ const path = node('node:path');
218
+ const absFile = path.resolve(file);
219
+ const { c, flags } = readCFile(file, opts);
220
+ c.pkg.dir = absFile.replace(/\/[^/]*$/, '');
221
+ const read = readGo(c.pkg, { entry: c.entry, methods: opts.functions?.map(f => f.split('/')[0]) ?? c.methods, strict: true, safety: true, ...(opts.fails ? { fails: opts.fails } : {}) });
222
+ const coverage = { coveredFunctions: read.methods.map(m => m.name), ...(c.helpers?.length ? { coveredHelpers: c.helpers } : {}), ...(c.macroConfig ? { macroConfig: c.macroConfig } : {}) };
223
+ if (!read.safety)
224
+ return unchecked(file, 'the C safety backend did not provide defined-prefix coverage', uncheckedCSafety([], coverage));
225
+ if (!read.safety.sites.length)
226
+ return unchecked(file, 'the C safety backend reported no covered sites', uncheckedCSafety([], coverage));
227
+ const clang = c.macroConfig?.compilerPath ?? 'clang';
228
+ let cachedHarness;
229
+ const replay = (run, site) => {
230
+ cachedHarness ??= harnessC(absFile, c, read, opts, false);
231
+ return replaySafety({
232
+ flags, harness: cachedHarness, clang, strictFlex: strictFlex(clang),
233
+ methods: read.methods, choices: read.methods.map(m => m.name),
234
+ ctor: (read.ctor ?? []).map(p => p.name), ttab: c.pkg.ttab,
235
+ }, run, site);
236
+ };
237
+ const safety = analyzeCSafety(read, c, read.safety.sites, { ...unsignedDomains(read), ...signedDomains(c.pkg, read) }, { replay, ...(opts.safetySearchMs !== undefined ? { searchMs: opts.safetySearchMs } : {}) });
238
+ c.verifySnapshotUnchanged?.();
239
+ if (safety.status === 'unchecked')
240
+ return unchecked(file, 'the C safety model could not be checked', safety);
241
+ const refusals = safety.issues.filter(site => site.status !== 'proven').map(site => ({
242
+ where: site.where,
243
+ what: site.status === 'broken'
244
+ ? `C ${site.kind} fault confirmed by ASan/UBSan: ${site.replay?.reports[0] ?? 'sanitizer diagnostic'}`
245
+ : `absence of a first C ${site.kind} fault was not proved${site.why ? ` (${site.why})` : ''}`,
246
+ }));
247
+ return { ok: safety.status === 'proven', safety, entry: c.entry, refusals, notes };
248
+ }
249
+ catch (e) {
250
+ if (e instanceof SafetyUncoveredRefusal) {
251
+ return unchecked(e.where, e.what, uncheckedCSafety([], {
252
+ coveredFunctions: e.coveredFunctions,
253
+ uncheckedFunctions: e.uncheckedFunctions,
254
+ ...(e.macroConfig ? { macroConfig: e.macroConfig } : {}),
255
+ }));
256
+ }
257
+ if (e instanceof Refusal)
258
+ return unchecked(e.where, e.what);
259
+ return unchecked(file, 'the C safety reader or prover could not complete');
260
+ }
261
+ }
180
262
  // A signed field (and a signed result) is an integer, never inferred a natural: its range law reads below 0.
181
263
  function signedDomains(pkg, read) {
182
264
  const out = {};
@@ -335,10 +417,17 @@ ${read.answers?.length ? `// The stub point of an answered call, by the callee's
335
417
  // request's input for it, 0 where it is none.
336
418
  #include <stdlib.h>
337
419
  static const char *gdp_answers;
420
+ static unsigned long long gdp_invocation, gdp_answer_values[${read.answers.length}];
421
+ static unsigned char gdp_answer_seen[${read.answers.length}], gdp_answer_signed[${read.answers.length}];
422
+ static unsigned long long gdp_note_answer(unsigned index, unsigned long long value, int is_signed) {
423
+ gdp_answer_seen[index] = 1; gdp_answer_values[index] = value; gdp_answer_signed[index] = is_signed;
424
+ return value;
425
+ }
338
426
  static const char *gdp_key(const char *p, const char *k);
339
427
  static long long gdp_answer(const char *name) {
340
428
  const char *a = gdp_answers ? gdp_key(gdp_answers, name) : 0, *v = a ? gdp_key(a, "in") : 0;
341
429
  if (!v) return 0;
430
+ if (*v == 't') return 1;
342
431
  if (*v == '"') v++;
343
432
  return strtoll(v, 0, 10);
344
433
  }
@@ -446,6 +535,15 @@ static const char *gdp_frame(gdp_T *o) {
446
535
  static const char *gdp_extern;
447
536
  ${cpp ? 'extern "C" ' : ''}void gdp_extern_called(const char *n) { gdp_extern = n; if (gdp_armed) { gdp_armed = 0; siglongjmp(gdp_jb, SIGUSR1); } abort(); }
448
537
  static const char *gdp_after(gdp_T *o) {
538
+ ${read.answers?.length ? `${emit(',"nativeObservations":{"invocation":')} gdp_putf("%llu", gdp_invocation); ${emit(',"calls":{')}
539
+ int seen = 0;
540
+ ${read.answers.map((a, i) => {
541
+ const bool = /^bool\b/.test(a.sort);
542
+ if (!bool && !a.range)
543
+ return '';
544
+ return `if (gdp_answer_seen[${i}]) { if (seen++) gdp_putf(","); ${emit(`${q(a.key)}:{"kind":"returned","value":`)} ${bool ? `gdp_putf("%s", gdp_answer_values[${i}] ? "true" : "false");` : `if (gdp_answer_signed[${i}]) gdp_putf("%lld", (long long)gdp_answer_values[${i}]); else gdp_putf("%llu", gdp_answer_values[${i}]);`} gdp_putf("}"); }`;
545
+ }).join('\n ')}
546
+ gdp_putf("}}");` : ''}
449
547
  const char *f = gdp_frame(o);
450
548
  if (f) { gdp_putf(",\\"frame\\":\\"%s\\"", f); }
451
549
  if (gdp_sig) gdp_putf(",\\"panic\\":\\"%s\\"", gdp_sig == SIGABRT ? "SIGABRT (abort, or an assertion failing)" : gdp_sig == SIGTRAP || gdp_sig == SIGILL ? "undefined behavior (the sanitizer's trap)" : gdp_sig == SIGUSR1 ? "another file's function called" : gdp_sig == SIGUSR2 ? "an exception thrown" : gdp_sig == SIGALRM ? "the code didn't return (an endless loop)" : "a signal");
@@ -459,6 +557,7 @@ ${make}
459
557
  static const char *gdp_call(gdp_T *o, const char *m, const char *a) {
460
558
  const char *v; (void)v; (void)a;
461
559
  gdp_sig = gdp_err = gdp_has = gdp_outu = gdp_isb = gdp_rec = 0; gdp_outv = 0; gdp_native_bad = 0;
560
+ ${read.answers?.length ? '++gdp_invocation; memset(gdp_answer_seen, 0, sizeof gdp_answer_seen);' : ''}
462
561
  ${calls.join('\n ')}
463
562
  return "no such function";
464
563
  }
@@ -480,7 +579,7 @@ int main(int argc, char **argv) {
480
579
  const char *op = gdp_key(line, "op"), *id = gdp_key(line, "id");
481
580
  long long k = 0; unsigned long long ku; if (id) gdp_int(id, 64, 1, &k, &ku);
482
581
  gdp_n = 0;
483
- if (op && !strncmp(op + 1, "hello", 5) && op[6] == '"') { ${emit('{"nativeSnapshot":1,"nativeBindings":1,"nativeEquality":"scalar"}')} }
582
+ if (op && !strncmp(op + 1, "hello", 5) && op[6] == '"') { ${emit(JSON.stringify({ nativeSnapshot: 1, nativeBindings: 1, nativeEquality: 'scalar', ...(read.answers?.length ? { nativeObservations: 1 } : {}) }))} }
484
583
  else if (op && !strncmp(op + 1, "native", 6) && op[7] == '"') { gdp_native(objs[k - 1]); }
485
584
  else if (op && !strncmp(op, "\\"new\\"", 5)) { const char *bad = 0; gdp_T *o = gdp_make(line, &bad); if (!o) gdp_putf("{\\"bad\\":\\"%s\\"}", bad); else { objs = (gdp_T **)realloc(objs, ++nobj * sizeof *objs); objs[nobj - 1] = o; gdp_putf("{\\"id\\":%zu}", nobj); } }
486
585
  else if (op && !strncmp(op, "\\"at\\"", 4)) {
@@ -510,7 +609,7 @@ const flexOK = new Map();
510
609
  function strictFlex(clang) {
511
610
  if (!flexOK.has(clang)) {
512
611
  try {
513
- node('node:child_process').execFileSync(clang, ['-fstrict-flex-arrays=3', '-x', 'c', '-fsyntax-only', '/dev/null'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
612
+ node('node:child_process').execFileSync(clang, ['-fstrict-flex-arrays=3', '-x', 'c', '-fsyntax-only', '/dev/null'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: scrubbedClangEnv() });
514
613
  flexOK.set(clang, true);
515
614
  }
516
615
  catch {
@@ -552,7 +651,7 @@ export function checkC(file, flags, c, read, r, sorts, opts, cpp) {
552
651
  const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), path = node('node:path');
553
652
  const work = fs.mkdtempSync(`${os.tmpdir()}/gdp-ccheck-`), b0 = performance.now();
554
653
  // (each answered call rewritten to the harness's answer in a copy of the file, its own includes found beside it)
555
- const copy = stubbed(read, f => fs.readFileSync(`${path.resolve(file).replace(/[^/]*$/, '')}${f}`, 'utf8'), a => `((${a.ty})gdp_answer(${JSON.stringify(a.key)}))`);
654
+ const copy = stubbed(read, f => fs.readFileSync(`${path.resolve(file).replace(/[^/]*$/, '')}${f}`, 'utf8'), (a, i) => `((${a.ty})gdp_note_answer(${i}, (unsigned long long)((${a.ty})gdp_answer(${JSON.stringify(a.key)})), (${a.ty})-1 < (${a.ty})0))`);
556
655
  for (const [f, t] of copy)
557
656
  fs.writeFileSync(`${work}/${f}`, t);
558
657
  const code = harnessC(copy.size ? `${work}/${path.resolve(file).split('/').pop()}` : path.resolve(file), c, read, opts, cpp);
@@ -571,7 +670,7 @@ export function checkC(file, flags, c, read, r, sorts, opts, cpp) {
571
670
  // code's failure where the rule took the step, a difference), but those left out (skip, stated or inferred: they
572
671
  // change nothing the rule keeps, and nothing reads their value), which do nothing.
573
672
  const clang = opts.clang ?? (cpp ? 'clang++' : 'clang'), stubs = `${work}/gdp_stubs.c`;
574
- const run = (cc, args) => cp.execFileSync(cc, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: compileLimit(), killSignal: 'SIGKILL' });
673
+ const run = (cc, args) => cp.execFileSync(cc, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 26, timeout: compileLimit(), killSignal: 'SIGKILL', env: scrubbedClangEnv() });
575
674
  // (the stubs are C, compiled apart: the project's flags, a C++ -std among them, are the harness's)
576
675
  const link = (more) => { for (const m of more)
577
676
  run(clang.replace(/\+\+$/, ''), ['-w', '-c', '-x', 'c', m, '-o', `${m}.o`]); return run(clang, [...(cpp ? ['-x', 'c++'] : []), ...flags, '-w', '-O0', '-fsanitize=undefined', '-fsanitize-trap=undefined', '-fno-sanitize=vptr,function', ...strictFlex(clang), h, ...(more.length ? ['-x', 'none', ...more.map(m => `${m}.o`)] : []), '-o', `${work}/harness`]); };
@@ -2,6 +2,7 @@ import { Outside, constantsOf, draw, drive, evalTerm } from "./extract-check.js"
2
2
  import { buildCheck, builtEvidence, compileLimit, openHarness, stopped, stubbed } from "./extract-step.js";
3
3
  import { node } from "./extract-go.js";
4
4
  import { nativeWireDecoder, snapshotNativeBindings } from "./native-wire.js";
5
+ import { nativeObservationSequence } from "./native-observations.js";
5
6
  // --- the harness ------------------------------------------------------------------------------------------------------
6
7
  // Go source beside the package: a state set from JSON and read back as JSON, leaf by leaf; each method called with its
7
8
  // arguments made from JSON; a panic recovered; the left-out fields compared before and after.
@@ -549,6 +550,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
549
550
  const capabilities = ask({ op: 'hello' });
550
551
  const decode = capabilities.nativeSnapshot === 1 || capabilities.nativeBindings === 1 ? nativeWireDecoder() : undefined;
551
552
  let bindings;
553
+ const acceptObservation = capabilities.nativeObservations === 1 ? nativeObservationSequence(new Set(read.answers?.map(a => a.key))) : undefined;
554
+ let observations, observedCache;
552
555
  // A state from the harness as a snapshot (a number past the safe integers: the code leaves the rule's numbers).
553
556
  const toSnap = (s) => {
554
557
  const leaves = {}, maps = {}, lists = {};
@@ -630,6 +633,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
630
633
  }
631
634
  const res = ask({ op: 'call', id: self, m: e.call, now, a: args, ...(answers ? { answers } : {}) });
632
635
  bindings = res.nativeBindings;
636
+ observations = res.nativeObservations;
637
+ observedCache = undefined;
633
638
  if (res.frame)
634
639
  throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
635
640
  if (res.bad)
@@ -649,6 +654,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
649
654
  throw new Error(`native parameter capture: ${bindings.error}`);
650
655
  return bindings?.snapshot ? snapshotNativeBindings(decode, bindings.snapshot) : undefined;
651
656
  } } : {}),
657
+ ...(acceptObservation ? { nativeObservations: () => (observedCache ??= acceptObservation(observations)) } : {}),
652
658
  args: (inputs, e) => e.args.map(a => argJson(a, inputs)),
653
659
  setNow: n => { if (!Number.isSafeInteger(n))
654
660
  throw new Outside('Go clock outside the exact integer range'); now = n; },
@@ -1,7 +1,7 @@
1
1
  import type { B } from './extract-ir.js';
2
2
  import { type Arg, type Model, type FileURL } from './extract-read.js';
3
3
  import { type Extraction, type Name } from './extract.js';
4
- import { type Answer } from './extract-step.js';
4
+ import { type Answer, type SafetySite } from './extract-step.js';
5
5
  import { type GoCheckOptions, type GoLeaf } from './extract-go-check.js';
6
6
  export { minimizeRun, minimizeRunDetailed, proveRule, proveSteps } from './dsl.js';
7
7
  export type TT = {
@@ -87,6 +87,12 @@ export type GX = {
87
87
  }[];
88
88
  i?: GX;
89
89
  end?: string;
90
+ site?: SafetySite;
91
+ sites?: SafetySite[];
92
+ checkedType?: number;
93
+ dims?: number[];
94
+ vals?: number[];
95
+ indices?: GX[];
90
96
  };
91
97
  export type GS = {
92
98
  s: string;
@@ -145,10 +151,12 @@ export type GoFunc = {
145
151
  params: GoParam[];
146
152
  results: GoParam[];
147
153
  body?: GS[];
154
+ safetySites?: SafetySite[];
148
155
  };
149
156
  export type GoPkg = {
150
157
  dir?: string;
151
158
  lang?: string;
159
+ safety?: true;
152
160
  ctor?: GoFunc;
153
161
  package: string;
154
162
  files: {
@@ -189,6 +197,7 @@ export type GoOptions = {
189
197
  check?: GoCheckOptions;
190
198
  fails?: Record<string, string>;
191
199
  strict?: boolean;
200
+ safety?: boolean;
192
201
  answers?: Record<string, string>;
193
202
  skip?: string[];
194
203
  };
@@ -198,6 +207,11 @@ export type GoClock = {
198
207
  callee: string;
199
208
  };
200
209
  export type GoRead = {
210
+ safety?: {
211
+ sites: (SafetySite & {
212
+ condition: B;
213
+ })[];
214
+ };
201
215
  clocks?: GoClock[];
202
216
  answers?: (Answer & {
203
217
  range?: [number, number];
@@ -55,6 +55,8 @@ class Go {
55
55
  this.opts = opts;
56
56
  const mod = { lang: pkg.lang ?? 'go', file: pkg.files[0]?.name ?? 'go', path: pkg.dir ? `${pkg.dir}/${pkg.files[0]?.name ?? ''}` : '', module: pkg.package, root: pkg.dir ?? '', entries: [], recs: {}, funcs: this.funcs, split: false };
57
57
  this.g = new Stepper(mod, { entry: opts.entry, ...(opts.onError ? { onError: opts.onError } : {}), ...(opts.answers ? { answers: opts.answers } : {}), ...(opts.skip ? { skip: opts.skip } : {}) }, inf);
58
+ if (opts.safety)
59
+ this.g.safety = new Map();
58
60
  for (const f of pkg.funcs)
59
61
  this.funcs[`${f.recv?.type ?? ''}.${f.name}`] = this.fn(f);
60
62
  }
@@ -121,7 +123,10 @@ class Go {
121
123
  const k = this.T(x.t).k, it = this.intTy(x.t), ret = it ? { k: 'int', bits: it.bits, signed: it.signed } : k === 'bool' ? { k: 'bool' } : k === 'string' ? { k: 'str' } : undefined;
122
124
  return this.no(x, why, { ext: name, args: (x.a ?? []).map(y => this.x(y)), kw: [], ...(recv ? { recv: this.x(recv) } : {}), ...(ret ? { ret, ty: this.tname(x.t) } : {}), ...(x.end ? { end: x.end } : {}) });
123
125
  }
124
- at(x) { return { p: x.p, text: x.text }; }
126
+ at(x) {
127
+ const ity = this.opts.safety && x.checkedType !== undefined ? this.intTy(x.checkedType) ?? refuse(x, 'missing integer operation type in C safety source') : undefined;
128
+ return { p: x.p, text: x.text, ...(this.opts.safety && x.site ? { site: x.site } : {}), ...(ity ? { ity } : {}) };
129
+ }
125
130
  // A value as the type it is assigned to: an untyped constant takes the type; an integer stays itself.
126
131
  as(v, t) {
127
132
  const ty = this.intTy(t), k = this.T(t).k;
@@ -208,6 +213,7 @@ class Go {
208
213
  return { e: 'lidx', ...at, s: this.x(x.x), i: this.x(x.i), ty: this.intTy(xt.elem) };
209
214
  return this.no(x, `${x.text}: an index into a ${this.tname(x.x.t)}`, { pre: [this.x(x.x), this.x(x.i)] });
210
215
  }
216
+ case 'table': return { e: 'table', ...at, sites: x.sites, dims: x.dims, vals: x.vals, indices: (x.indices ?? []).map(y => this.x(y)), ity: this.intTy(x.t), isBool: this.T(x.t).k === 'bool' };
211
217
  case 'slice': {
212
218
  // s[:len(s)-1] of a slice of the state: its last item taken off (put back in s's own place).
213
219
  const h = x.hi, ok = !x.lo && !x.three && h?.e === 'bin' && h.op === '-' && h.y?.c?.int === '1' && h.x?.e === 'call' && h.x.builtin === 'len' && h.x.a?.[0]?.text === x.x.text;
@@ -685,6 +691,18 @@ class Go {
685
691
  // Read with the boundary inferred unless strict (core/extract-step.ts's readStep: each refused run adds what the next
686
692
  // infers): Go's check can't stub a call, so a call of another package is left out where nothing reads its value.
687
693
  export function readGo(pkg, opts) {
694
+ if (opts.safety) {
695
+ const at = pkg.files[0]?.name ?? '?';
696
+ if (!pkg.safety || pkg.lang !== 'c')
697
+ refuse(at, 'C safety requires the checked source reader');
698
+ if (Object.keys(opts.answers ?? {}).length || opts.skip?.length || Object.keys(opts.domains ?? {}).length)
699
+ refuse(at, 'safety does not allow inferred boundaries or custom domains');
700
+ if (opts.onError === 'discard')
701
+ refuse(at, 'C safety does not allow discarding state writes on failure');
702
+ return readGo1(pkg, { ...opts, onError: 'refuse' }, new Go(pkg, { ...opts, onError: 'refuse' }));
703
+ }
704
+ if (pkg.safety)
705
+ refuse(pkg.files[0]?.name ?? '?', 'checked C source requires safety lowering');
688
706
  if (!opts.entry && !opts.strict) {
689
707
  // No entry: the package's one struct whose exported methods write it (core/extract-step.ts's writesState).
690
708
  const g = new Go(pkg, opts).g, writing = (t) => pkg.funcs.filter(f => f.recv?.type === t && f.body && (pkg.lang === 'c' || pkg.lang === 'cpp' || /^[A-Z]/.test(f.name)) && g.writesState(`${t}.${f.name}`, new Set([g.mod.funcs[`${t}.${f.name}`]?.recv ?? ''])));
@@ -756,7 +774,30 @@ function readGo1(pkg, o, go) {
756
774
  p = g.bindLocal(pa.id, it ? { t: 'num', e: I.nvar(v.name), ty: it } : { t: 'bool', e: I.bvar(v.name) }, fn, p);
757
775
  }
758
776
  p = g.bindLocal('this', { t: 'ptr', to: { k: 'obj', id: 'this', path: [] } }, fn, p);
777
+ const ctorCut = g.safety ? new Set() : undefined, ctorDead = g.safety ? new Set() : undefined;
778
+ if (g.safety) {
779
+ if (fn.safetySites === undefined)
780
+ refuse(fn, 'missing pre-lowering C safety site inventory on initializer');
781
+ g.safetyCutSites = ctorCut;
782
+ g.safetyDeadSites = ctorDead;
783
+ }
759
784
  const flow = g.block(go.fn(fn).body, p), ends = [...flow.rets.map(([q]) => q), ...(flow.live ? [flow.live] : [])];
785
+ if (g.safety) {
786
+ const expected = new Set((fn.safetySites ?? []).map(s => `${s.kind}:${s.where}`));
787
+ for (const s of fn.safetySites ?? []) {
788
+ const key = `${s.kind}:${s.where}`;
789
+ if (!ctorCut.has(key) && !ctorDead.has(key))
790
+ refuse(fn, `unaccounted C safety initializer site (${s.kind} at ${s.where})`);
791
+ }
792
+ for (const k of ctorCut)
793
+ if (!expected.has(k))
794
+ refuse(fn, `uninventoried C safety initializer cut (${k})`);
795
+ if ([...g.safety.values()].some(s => !(s.condition.op === 'const' && !s.condition.v)))
796
+ refuse(fn, 'a constructor with a possible C safety fault');
797
+ g.safety.clear();
798
+ g.safetyCutSites = undefined;
799
+ g.safetyDeadSites = undefined;
800
+ }
760
801
  if (g.refusals.length > n0 || !ends.length)
761
802
  refuse(fn, 'a constructor that can fail (the rule\'s start is where it leaves the object)');
762
803
  const m = materialize(go, g.join(ends, fn), fn);
@@ -780,6 +821,7 @@ function readGo1(pkg, o, go) {
780
821
  g.method = fn.name;
781
822
  const sel = I.is(evL, fn.name);
782
823
  let p = { pc: [sel], locals: new Map(), heap: new Map(heap), called: [], locks: [], defers: [] };
824
+ const beforeInput = g.refusals.length;
783
825
  const bound = go.bindParams(fn, sel, p), args = bound.args, params = bound.params;
784
826
  p = bound.p;
785
827
  // (an out-parameter a path leaves as the caller gave it: what the caller gave, an input, read at the start)
@@ -788,6 +830,8 @@ function readGo1(pkg, o, go) {
788
830
  if (pt.k === 'ptr' && go.T(pt.elem).box && (go.T(pt.elem).fields ?? []).length === 1 && boxKept(lowered0(fn), pa.id))
789
831
  g.lazyFieldIn(`in:${fn.name}_${pa.name ?? 'arg'}`, 'value', p, fn);
790
832
  }
833
+ if (g.safety)
834
+ p = g.assume(p, I.not(I.or(...g.refusals.slice(beforeInput))));
791
835
  // The receiver.
792
836
  if (fn.recv?.id)
793
837
  p = g.bindLocal(fn.recv.id, fn.recv.ptr ? { t: 'ptr', to: { k: 'obj', id: 'this', path: [] } } : { t: 'struct', ty: String(td.t), f: fields }, fn, p);
@@ -797,13 +841,45 @@ function readGo1(pkg, o, go) {
797
841
  refuse(fn, `${fn.name} returns ${kept.length} values (a result kept is one value)`);
798
842
  const lowered = lowered0(fn);
799
843
  g.spans.set(`${opts.entry}.${fn.name}`, [fn.p.split(':')[0], fn.span[0], fn.span[1]]);
844
+ const methodCut = g.safety ? new Set() : undefined, methodDead = g.safety ? new Set() : undefined;
845
+ if (g.safety) {
846
+ if (fn.safetySites === undefined)
847
+ refuse(fn, 'missing pre-lowering C safety site inventory');
848
+ g.safetyCutSites = methodCut;
849
+ g.safetyDeadSites = methodDead;
850
+ }
851
+ const beforeBody = g.refusals.length;
800
852
  const flow = g.block(lowered.body, p);
853
+ if (g.safety) {
854
+ g.safetyCutSites = undefined;
855
+ g.safetyDeadSites = undefined;
856
+ const expected = new Set(fn.safetySites.map(s => `${s.kind}:${s.where}`));
857
+ for (const s of fn.safetySites) {
858
+ const key = `${s.kind}:${s.where}`;
859
+ if (!methodCut.has(key) && !methodDead.has(key))
860
+ refuse(fn, `unaccounted C safety source site (${s.kind} at ${s.where})`);
861
+ g.registerSafety(s);
862
+ }
863
+ for (const k of methodCut)
864
+ if (!expected.has(k))
865
+ refuse(fn, `uninventoried C safety cut (${k})`);
866
+ }
867
+ if (g.safety && g.refusals.length !== beforeBody)
868
+ refuse(fn, 'an untracked refusal on a C safety source path');
869
+ if (g.safety && flow.live && fn.results.length) {
870
+ const c = g.cond(flow.live);
871
+ if (!(c.op === 'const' && !c.v))
872
+ refuse(fn, 'a non-void C method with a reachable fallthrough');
873
+ }
801
874
  if (flow.brk?.length)
802
875
  refuse(fn, 'a break outside a switch');
803
876
  const rets = [...flow.rets.map(([q, v]) => [q, v.xs]), ...(flow.live ? [[flow.live, []]] : [])];
804
877
  // An error returned: a refusal (where it isn't nil), the state as it was there.
805
878
  const ok = [];
806
879
  for (const [q0, vs] of rets) {
880
+ const prefix = g.cond(q0);
881
+ if (g.safety && prefix.op === 'const' && !prefix.v)
882
+ continue;
807
883
  const q = { ...q0, locks: q0.locks.filter(k => !q0.defers.includes(k)) };
808
884
  if (q.locks.length)
809
885
  refuse(fn, `${fn.name} returns with a mutex locked`);
@@ -812,6 +888,8 @@ function readGo1(pkg, o, go) {
812
888
  // A result the caller states is the failure where it compares so: a refusal there, as an error is.
813
889
  const m = /^\s*(==|!=|<=|>=|<|>)\s*(-?\d+|true|false)\s*$/.exec(fails) ?? refuse(fn, `fails: ${JSON.stringify(fails)} (a comparison with a constant: '< 0', '!= 0', '== false')`);
814
890
  const r = vs[0] ?? refuse(fn, `${fn.name} returns nothing to compare (fails: ${fails})`);
891
+ if (g.safety && !['true', 'false'].includes(m[2]) && !Number.isSafeInteger(Number(m[2])))
892
+ refuse(fn, 'an inexact configured failure constant');
815
893
  const k = m[2] === 'true' || m[2] === 'false' ? { t: 'bool', e: m[2] === 'true' ? I.T : I.F } : { t: 'num', e: I.num(Number(m[2])) };
816
894
  // (no failure where the result's bounds and the path's facts exclude it: an item of a uint8_t is never < 0)
817
895
  const kv = Number(m[2]), e = r.t === 'num' ? r.e : undefined, op = m[1];
@@ -832,8 +910,25 @@ function readGo1(pkg, o, go) {
832
910
  else
833
911
  ok.push([q, vs]);
834
912
  }
835
- if (!ok.length)
836
- refuse(fn, `${fn.name} always fails`);
913
+ if (!ok.length) {
914
+ if (!g.safety)
915
+ refuse(fn, `${fn.name} always fails`);
916
+ // This method still exists as an event: a fault can be its only exit.
917
+ // Its normal slot values are immaterial on faults (the monitor stutters).
918
+ const vs = fn.results.map(r => go.T(r.t).k === 'bool' ? { t: 'bool', e: I.F } : { t: 'num', e: I.num(0), ty: go.intTy(r.t) });
919
+ const dummy = g.assume(p, I.F);
920
+ for (const pa of params) {
921
+ const pt = go.T(pa.t);
922
+ if (pt.k !== 'ptr' || !go.T(pt.elem).box)
923
+ continue;
924
+ const id = `in:${fn.name}_${pa.name}`, obj = dummy.heap.get(id);
925
+ if (obj?.k === 'rec' && !obj.f.has('value')) {
926
+ const et = go.T(pt.elem).fields[0].t;
927
+ dummy.heap.set(id, { ...obj, f: new Map(obj.f).set('value', go.T(et).k === 'bool' ? { t: 'bool', e: I.F } : { t: 'num', e: I.num(0), ty: go.intTy(et) }) });
928
+ }
929
+ }
930
+ ok.push([dummy, vs]);
931
+ }
837
932
  // The kept result: by the path that returned it (a local the join merges).
838
933
  const ri = fn.results.findIndex((_, i) => i !== errAt);
839
934
  const final = g.join(ok.map(([q, vs]) => (kept.length ? { ...q, locals: new Map(q.locals).set('$ret', vs[ri]) } : q)), fn), acc = final.locals.get('$ret');
@@ -955,6 +1050,9 @@ function readGo1(pkg, o, go) {
955
1050
  }
956
1051
  const refuseB = I.or(...g.refusals);
957
1052
  mention(refuseB);
1053
+ const safety = g.safety ? { sites: [...g.safety.values()] } : undefined;
1054
+ for (const s of safety?.sites ?? [])
1055
+ mention(s.condition);
958
1056
  for (const n of Object.keys(writes))
959
1057
  used.add(n);
960
1058
  // A map's nil flag and a big.Int's go with their value.
@@ -1012,7 +1110,7 @@ function readGo1(pkg, o, go) {
1012
1110
  // Unsigned inputs are naturals (the input's kind); a state variable's sort is the printer's to decide (a natural where
1013
1111
  // every write is proven one: a wrap by cases may not be, though it stays within the type, which its law says).
1014
1112
  const unsigned = [...g.ints].filter(([n, ty]) => { const [lo, hi] = rangeOf(ty); return lo === 0 && hi > 0 && (g.inputs.some(v => v.name === n) || cparams.some(v => v.name === n)); }).map(([n]) => n);
1015
- return { ...(g.now ? { clocks: [...go.clocks.values()] } : {}), ...(pkg.ctor ? { ctor: ctorArgs } : {}), ...(g.leftOut.size ? { leftOut: [...g.leftOut] } : {}), model, edges: g.edges, unsigned, leaves: go.leaves.filter(l => l.kind === 'frame' || state.some(v => v.name === l.name) || maps.some(d => d.name === l.name) || lists.some(d => d.name === l.name)), spans: [...g.spans.values()], entry: opts.entry, methods, ...(answers.length ? { answers } : {}) };
1113
+ return { ...(safety ? { safety } : {}), ...(g.now ? { clocks: [...go.clocks.values()] } : {}), ...(pkg.ctor ? { ctor: ctorArgs } : {}), ...(g.leftOut.size ? { leftOut: [...g.leftOut] } : {}), model, edges: g.edges, unsigned, leaves: go.leaves.filter(l => l.kind === 'frame' || state.some(v => v.name === l.name) || maps.some(d => d.name === l.name) || lists.some(d => d.name === l.name)), spans: [...g.spans.values()], entry: opts.entry, methods, ...(answers.length ? { answers } : {}) };
1016
1114
  }
1017
1115
  function termOf(v, at) {
1018
1116
  // (none: a path that ends without the value, which a reader of malformed source may join in)
@@ -370,7 +370,8 @@ function pn(e, P, ctx, mode, recv = false) {
370
370
  const prod = `${f(e.a, true)}.mul(${f(e.b, false)})`;
371
371
  return nat ? prod : `Int.of(${prod})`;
372
372
  }
373
- return `${pn(e.a, P, ctx, 'nat', true)}.mul(${pn(e.b, P, ctx, 'nat')})`;
373
+ const prod = `${pn(e.a, P, ctx, 'nat', true)}.mul(${pn(e.b, P, ctx, 'nat')})`;
374
+ return !nat && recv ? `Int.of(${prod})` : prod;
374
375
  case 'min': return nat ? `min(${A(e.a)}, ${A(e.b)})` : `${R(e.a)}.min(${A(e.b)})`;
375
376
  case 'max':
376
377
  if (nat) {
@@ -389,7 +390,8 @@ function pn(e, P, ctx, mode, recv = false) {
389
390
  // where the dividend is at least 0.
390
391
  if (!natOK(e.a, ctx) && !nonneg(e.a, ctx))
391
392
  throw new Refusal(P.m.file, 'x % k where x may be negative (JavaScript\'s remainder takes the sign of x)');
392
- return `${pn(e.a, P, ctx, natOK(e.a, ctx) ? 'nat' : 'int', true)}.modBy(${e.k})`;
393
+ const rem = `${pn(e.a, P, ctx, natOK(e.a, ctx) ? 'nat' : 'int', true)}.modBy(${e.k})`;
394
+ return !nat && recv ? `Int.of(${rem})` : rem;
393
395
  case 'ite': {
394
396
  const d = decided(e.c, ctx);
395
397
  if (d !== undefined)
@@ -246,6 +246,7 @@ type V = {
246
246
  cmp?: [N, N];
247
247
  slen?: K;
248
248
  bits?: Bits;
249
+ range?: [number, number];
249
250
  } | {
250
251
  t: 'bool';
251
252
  e: B;
@@ -614,6 +615,10 @@ type Pend = Bound & {
614
615
  at: string;
615
616
  end?: string;
616
617
  };
618
+ export type SafetySite = {
619
+ where: string;
620
+ kind: 'bounds' | 'overflow' | 'division';
621
+ };
617
622
  export declare class Stepper {
618
623
  readonly mod: SModule;
619
624
  readonly opts: StepOptions;
@@ -623,6 +628,16 @@ export declare class Stepper {
623
628
  readonly params: Var[];
624
629
  readonly notes: Set<string>;
625
630
  readonly refusals: B[];
631
+ safety?: Map<string, SafetySite & {
632
+ condition: B;
633
+ }>;
634
+ safetyCutSites?: Set<string>;
635
+ safetyDeadSites?: Set<string>;
636
+ registerSafety(site: SafetySite): (SafetySite & {
637
+ condition: B;
638
+ }) | undefined;
639
+ markSafetyDead(node: unknown, seenFns?: Set<string>): void;
640
+ safetyCut(p: Path, at: SX, kind: SafetySite['kind'], bad: B): Path;
626
641
  fails: B[];
627
642
  failPaths: Path[];
628
643
  readonly maps: MapDecl[];
@@ -1074,6 +1089,13 @@ export declare class Stepper {
1074
1089
  eq(a: V, b: V, x: {
1075
1090
  p: string;
1076
1091
  }, p?: Path): B;
1092
+ safetyRange(ty: IntTy | undefined, at: SX): [number, number];
1093
+ safetyBounds(v: Extract<V, {
1094
+ t: 'num';
1095
+ }>, at: SX): [number, number];
1096
+ safetyModulo(e: N, m: number, lo?: number): N;
1097
+ safetyWrapUnsigned(e: N, lo: bigint, hi: bigint, mod: number): N;
1098
+ safetyArith(op: string, a: V, b: V, at: SX, p: Path): [V, Path];
1077
1099
  arith(op: string, a: V, b: V, x: {
1078
1100
  p: string;
1079
1101
  }, p: Path): V;