gdp-wired 0.55.1 → 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.
package/dist/core/cli.js CHANGED
@@ -7,6 +7,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
7
  }
8
8
  return path;
9
9
  };
10
+ import { cleanupCSafetySnapshots } from "./c/reader.js";
10
11
  import { fiberRun } from "./fiber-run.js";
11
12
  import { securityTemplates } from "./security.js";
12
13
  import { proveLeadsTo as rawLeadsTo, proveRule as rawRule, proveSteps as rawSteps } from "./dsl.js";
@@ -45,6 +46,8 @@ function args(argv) {
45
46
  o.propose = false;
46
47
  else if (a === '--security')
47
48
  o.security = true;
49
+ else if (a === '--safety')
50
+ o.safety = true;
48
51
  else if (a === '--require-review')
49
52
  o.requireReview = true;
50
53
  else if (a.startsWith('--')) {
@@ -307,6 +310,10 @@ const searchOf = (v) => v.stopped && v.termination && !(v.proven && v.checked) &
307
310
  ? { stopped: true, termination: v.termination, ...(v.context ? { context: v.context } : {}) } : {};
308
311
  const whyOf = (v, semantic) => searchOf(v).termination && v.translation !== 'unchecked' && v.translation !== 'error'
309
312
  ? terminationWhy(v.termination) : semantic;
313
+ function safetyReport(x, requested) {
314
+ const report = x.safety;
315
+ return report ?? (requested ? { why: 'the extractor did not provide a C safety model' } : undefined);
316
+ }
310
317
  function* expandInitializers(t, o, laws, rows) {
311
318
  if (!rows.some(r => r.x.initializers))
312
319
  return rows;
@@ -347,6 +354,98 @@ function* expandInitializers(t, o, laws, rows) {
347
354
  }
348
355
  return out;
349
356
  }
357
+ // Extract C comment bodies (`// ...` and `/* ... */`), applying C phase-2 line splicing (`\<newline>`)
358
+ // and skipping string literals, char literals, and C23 preprocessing numbers (`1'000`, `0xDE'AD`).
359
+ function cCommentTexts(rawSrc) {
360
+ const src = rawSrc.replace(/\\\r?\n/g, '');
361
+ const out = [];
362
+ const isIdent = (c) => !!c && /[A-Za-z0-9_$]/.test(c);
363
+ const isDigit = (c) => !!c && c >= '0' && c <= '9';
364
+ const isPpCont = (c) => !!c && /[0-9A-Za-z_.]/.test(c);
365
+ for (let i = 0; i < src.length; i++) {
366
+ const ch = src[i];
367
+ if ((isDigit(ch) && !isIdent(src[i - 1])) || (ch === '.' && isDigit(src[i + 1]))) {
368
+ let j = i + (ch === '.' ? 2 : 1);
369
+ while (j < src.length) {
370
+ const c = src[j];
371
+ if ((c === 'e' || c === 'E' || c === 'p' || c === 'P') && (src[j + 1] === '+' || src[j + 1] === '-')) {
372
+ j += 2;
373
+ continue;
374
+ }
375
+ if (c === "'" && /[0-9A-Za-z_]/.test(src[j + 1] ?? '')) {
376
+ j += 2;
377
+ continue;
378
+ }
379
+ if (isPpCont(c)) {
380
+ j++;
381
+ continue;
382
+ }
383
+ break;
384
+ }
385
+ i = j - 1;
386
+ }
387
+ else if (ch === '"' || ch === "'") {
388
+ const q = ch;
389
+ for (i++; i < src.length; i++) {
390
+ if (src[i] === '\\') {
391
+ i++;
392
+ continue;
393
+ }
394
+ if (src[i] === q || src[i] === '\n')
395
+ break;
396
+ }
397
+ }
398
+ else if (ch === '/' && src[i + 1] === '/') {
399
+ const start = i + 2;
400
+ while (i < src.length && src[i] !== '\n')
401
+ i++;
402
+ out.push(src.slice(start, i));
403
+ }
404
+ else if (ch === '/' && src[i + 1] === '*') {
405
+ const start = i + 2;
406
+ const end = src.indexOf('*/', start);
407
+ if (end < 0) {
408
+ out.push(src.slice(start));
409
+ break;
410
+ }
411
+ out.push(src.slice(start, end));
412
+ i = end + 1;
413
+ }
414
+ }
415
+ return out;
416
+ }
417
+ // Normalize Unicode whitespace (including NBSP and newlines), block-comment leading `*`, and
418
+ // fullwidth/compatibility colons so lookalike directives are never silently missed.
419
+ const normalizeSafetyText = (s) => s.replace(/[\uFF1A\uFE55\uFE13\u2236]/g, ':')
420
+ .replace(/\r?\n[ \t]*\*+[ \t]*/g, ' ')
421
+ .replace(/[\s\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000\uFEFF]+/g, ' ');
422
+ // Accept `// gdp: safety`, `/* gdp: safety */`, multiline `/* gdp:\n safety */`, backslash-continued
423
+ // `// ...\n gdp: safety`, case/punctuation variants, and trailing text, while rejecting assignments.
424
+ const SAFETY_TAG_RE = /\bgdp[ \t\r\n]*:[ \t\r\n]*safety\b(?![ \t]*=)/i;
425
+ const SAFETY_LOOKALIKE_RE = /\bgdp(?:\s*:\s*|\s+)safe\w*(?:\s*=\s*\S+)?/i;
426
+ const SAFETY_LOOKALIKE_NOTE_RE = /looks like a gdp: safety directive/;
427
+ const hasSafetyTag = (t) => t.lang === 'c' && t.files.some(f => cCommentTexts(fs.readFileSync(f, 'utf8')).some(c => SAFETY_TAG_RE.test(c)));
428
+ const safetyLookalikeNote = (t) => {
429
+ if (t.lang !== 'c' || hasSafetyTag(t))
430
+ return undefined;
431
+ for (const f of t.files) {
432
+ for (const c of cCommentTexts(fs.readFileSync(f, 'utf8'))) {
433
+ const m = SAFETY_LOOKALIKE_RE.exec(normalizeSafetyText(c));
434
+ if (m) {
435
+ const shown = /^gdp: safety$/i.test(m[0].trim()) ? c.trim().slice(0, 60) : m[0].trim();
436
+ return `${path.basename(f)}: comment looks like a gdp: safety directive (${JSON.stringify(shown)}) but did not match 'gdp: safety'; write '// gdp: safety' or pass --safety to enable C safety checking`;
437
+ }
438
+ }
439
+ }
440
+ return undefined;
441
+ };
442
+ const safetyDisabledBy = (cfg, entry) => cfg.all.safety === false || (!!entry && cfg.rules[entry]?.safety === false);
443
+ const safetyOverrideRefusal = (t) => ({
444
+ ok: false,
445
+ refusals: [{ where: t.at, what: 'gdp.toml disables safety (safety = false), conflicting with the in-source gdp: safety directive' }],
446
+ notes: [],
447
+ safety: { why: 'gdp.toml cannot silently override an in-source gdp: safety directive' },
448
+ });
350
449
  function* rulesOf(t, o, laws) {
351
450
  const got = yield* rulesOf0(t, o, laws);
352
451
  if (o.entry)
@@ -369,9 +468,15 @@ function* rulesOf(t, o, laws) {
369
468
  void _k;
370
469
  void _f;
371
470
  const keep = [...new Set(laws.flatMap(l => l.expr.match(/[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*/g) ?? []).flatMap(k => (k.includes('::') ? [k, ...k.split('::')] : [k])))];
471
+ const safetyTag = hasSafetyTag(t);
372
472
  const extra = [];
373
- for (const entry of more)
374
- extra.push({ entry, x: yield { target: t, options: { ...merge(merge({ ...shared, keep }, cfg.rules[entry] || {}), flags), entry } } });
473
+ for (const entry of more) {
474
+ if (safetyTag && safetyDisabledBy(cfg, entry)) {
475
+ extra.push({ entry, x: safetyOverrideRefusal(t) });
476
+ continue;
477
+ }
478
+ extra.push({ entry, x: yield { target: t, options: { ...merge(merge({ ...shared, keep }, cfg.rules[entry] || {}), flags), ...(safetyTag ? { safety: true } : {}), entry } } });
479
+ }
375
480
  // (the first rule, read with no entry named, kept only where it read something or nothing else was)
376
481
  return yield* expandInitializers(t, o, laws, [...got.filter(r => r.x.ok || r.entry || !extra.length), ...extra]);
377
482
  }
@@ -391,10 +496,15 @@ function* rulesOf0(t, o, laws) {
391
496
  void _k;
392
497
  // (the names the laws read, so an argument a law reads stays in the rule though the code ignores it)
393
498
  const keep = [...new Set(laws.flatMap(l => l.expr.match(/[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*/g) ?? []).flatMap(k => (k.includes('::') ? [k, ...k.split('::')] : [k])))];
394
- const optsFor = (entry) => merge(merge({ ...shared, keep }, (entry && cfg.rules[entry]) || {}), flags);
499
+ const safetyTag = hasSafetyTag(t);
500
+ const optsFor = (entry) => ({ ...merge(merge({ ...shared, keep }, (entry && cfg.rules[entry]) || {}), flags), ...(safetyTag ? { safety: true } : {}) });
395
501
  const one = function* (entry) {
502
+ if (safetyTag && safetyDisabledBy(cfg, entry))
503
+ return { entry, x: safetyOverrideRefusal(t) };
396
504
  const x = yield { target: t, options: { ...optsFor(entry), ...(entry ? { entry } : {}) } };
397
- const found = x.model?.name;
505
+ const found = x.model?.name ?? x.entry;
506
+ if (!entry && found && safetyTag && safetyDisabledBy(cfg, found))
507
+ return { entry: found, x: safetyOverrideRefusal(t) };
398
508
  return !entry && found && cfg.rules[found] ? { entry: found, x: yield { target: t, options: { ...optsFor(found), entry: found } } } : { entry, x };
399
509
  };
400
510
  const manyOf = function* (entries) { const rows = []; for (const entry of entries)
@@ -598,9 +708,17 @@ function* checkPipeline(t, o) {
598
708
  // Different initial states must never overwrite one another's certificates.
599
709
  const ctx = ctor !== undefined && baseCtx.cert ? { ...baseCtx, cert: path.join(baseCtx.cert, `initializer-${initializerIndex}`) } : baseCtx;
600
710
  let x = x0;
601
- const name = entry ?? (x.model?.name || undefined);
711
+ const name = entry ?? (x.model?.name || x.entry || undefined);
602
712
  // (a target that is the working directory, a crate's or a package's: `.`)
603
713
  const r = { file: path.relative(proc.cwd(), t.at) || '.', lang: LANG_NAME[t.lang], ...(name ? { entry: name } : {}), ...(ctor !== undefined ? { ctor } : {}), ok: x.ok, refusals: x.refusals, notes: x.notes, names: x.names ?? [], laws: [], proposed: [], ...(x.source ? { source: x.source } : {}) };
714
+ const safety = safetyReport(x, o.safety === true || hasSafetyTag(t));
715
+ if (safety)
716
+ r.safety = safety;
717
+ else if (o.safety !== true) {
718
+ const warn = safetyLookalikeNote(t);
719
+ if (warn && !r.notes.includes(warn))
720
+ r.notes.push(warn);
721
+ }
604
722
  outs.push(r);
605
723
  // (the laws of this rule: all where it is the file's one, else those in its class or on it or its methods, and those
606
724
  // outside every class and function)
@@ -1195,6 +1313,7 @@ export const proposedLaws = (x, lang, ms = 2000) => propose(x, lang, { ms, propo
1195
1313
  const ROLE = { state: 'state', param: 'made with', input: 'request', answer: 'answered', result: 'result', failed: 'failed', method: 'method', clock: 'clock', const: 'constant' };
1196
1314
  function printRule(r, o) {
1197
1315
  out(`${r.file}${r.entry ? `: ${r.entry}` : ''}${r.ctor !== undefined ? ` [ctor ${r.ctor}]` : ''} (${r.lang})`);
1316
+ const safetyWarnings = r.notes.filter(n => SAFETY_LOOKALIKE_NOTE_RE.test(n));
1198
1317
  if (!r.ok) {
1199
1318
  for (const f of r.refusals)
1200
1319
  out(` ${paint('yellow', `refused at ${f.where}:`)} ${f.what}`);
@@ -1215,6 +1334,8 @@ function printRule(r, o) {
1215
1334
  for (const n of r.names)
1216
1335
  out(` ${paint('dim', `${label(n).padEnd(w)} ${ROLE[n.role].padEnd(9)} ${n.rule}${n.none ? `${n.rule ? ', ' : ''}None: ${n.none}` : ''}${n.map ? ` (cells: ${n.map.fields.join(', ')}${n.map.tpl ? `; key ${JSON.stringify(n.map.tpl)}` : ''})` : ''}${n.role === 'const' ? String(n.value) : ''}`)}`);
1217
1336
  }
1337
+ for (const n of safetyWarnings)
1338
+ out(` ${paint('yellow', 'warning:')} ${n}`);
1218
1339
  const law = (l, proposed) => {
1219
1340
  out(` ${paint(VERDICT[l.verdict], l.verdict)}${' '.repeat(Math.max(0, 9 - l.verdict.length))}${l.name}${l.from ? ' (from any state)' : ''}${proposed ? '' : ` ${paint('dim', `(${l.where})`)}`}`);
1220
1341
  if (!proposed && l.verdict !== 'proven')
@@ -1256,6 +1377,45 @@ function printRule(r, o) {
1256
1377
  for (const l of r.laws)
1257
1378
  law(l, false);
1258
1379
  }
1380
+ if (r.safety) {
1381
+ out(' C safety (first-fault model; broken obligations replayed under ASan/UBSan):');
1382
+ if ('why' in r.safety)
1383
+ out(` ${paint('yellow', 'unchecked')}: ${r.safety.why}`);
1384
+ else {
1385
+ const color = (s) => s === 'proven' ? 'green' : s === 'broken' ? 'red' : 'yellow';
1386
+ const cov = r.safety.coveredFunctions.length ? r.safety.coveredFunctions.join(', ') : 'none';
1387
+ const helpers = r.safety.coveredHelpers?.length ? `; static helpers inlined: ${r.safety.coveredHelpers.join(', ')}` : '';
1388
+ out(` ${paint(color(r.safety.status), r.safety.status)} (covers: ${cov}${helpers})`);
1389
+ if (r.safety.macroConfig) {
1390
+ const mc = r.safety.macroConfig;
1391
+ const defs = mc.defines.length ? mc.defines.join(', ') : 'none';
1392
+ const incs = mc.includeDirs.length ? mc.includeDirs.join(', ') : 'none';
1393
+ const compiler = mc.compiler
1394
+ ? `; compiler: ${mc.compiler}${mc.compilerPath ? ` (${mc.compilerPath})` : ''}`
1395
+ : mc.compilerPath ? `; compiler: ${mc.compilerPath}` : '';
1396
+ const libc = mc.libc ? `; libc: ${mc.libc}` : '';
1397
+ const userF = mc.userFilesSha256
1398
+ ? `; user files: ${mc.userFiles?.length ?? 0} (sha256:${mc.userFilesSha256})`
1399
+ : '';
1400
+ const sysHdrs = mc.systemHeadersSha256
1401
+ ? `; system headers: ${mc.systemHeaders?.length ?? 0} (sha256:${mc.systemHeadersSha256})`
1402
+ : '';
1403
+ const envNote = mc.envScrubbed ? 'scrubbed' : 'inherited';
1404
+ out(` macro config: target: ${mc.target}${compiler}${libc}${userF}${sysHdrs}; std: ${mc.std} (__STDC_VERSION__=${mc.stdcVersion}); env: ${envNote}; -I flags: ${incs}; -D flags: ${defs}; NDEBUG=${mc.ndebugDefined ? 'defined' : 'undefined'}, __OPTIMIZE__=${mc.optimizeDefined ? 'defined' : 'undefined'}, DEBUG=${mc.debugDefined ? 'defined' : 'undefined'}`);
1405
+ }
1406
+ if (r.safety.uncheckedFunctions?.length)
1407
+ out(` ${paint('yellow', 'unchecked functions:')} ${r.safety.uncheckedFunctions.join(', ')}`);
1408
+ for (const s of r.safety.issues) {
1409
+ out(` ${paint(color(s.status), s.status)}: ${s.kind} at ${s.where}`);
1410
+ if (s.replay?.requests.length)
1411
+ out(` run: ${s.replay.requests.join(' -> ')}`);
1412
+ for (const line of s.replay?.reports ?? [])
1413
+ out(` sanitizer: ${line}`);
1414
+ }
1415
+ for (const a of r.safety.assumptions)
1416
+ out(` ${a}`);
1417
+ }
1418
+ }
1259
1419
  if (r.security) {
1260
1420
  out(' security candidates (NOT accepted policy; review the requirement and authentication boundary):');
1261
1421
  for (const l of r.security)
@@ -1269,7 +1429,7 @@ function printRule(r, o) {
1269
1429
  if (r.brokenProposed)
1270
1430
  out(` (${r.brokenProposed} more proposed and broken by a run: not shown)`);
1271
1431
  }
1272
- if (r.ok && !r.laws.length)
1432
+ if (r.ok && !r.safety && !r.laws.length)
1273
1433
  out(` no law stated: write one as \`${COMMENT[Object.keys(LANG_NAME).find(k => LANG_NAME[k] === r.lang)]} gdp: law <name>: <expr>\` over the names above`);
1274
1434
  void o;
1275
1435
  out();
@@ -1288,6 +1448,7 @@ the clause a law answers: \`gdp: cite <law name>: <clause>\` (drafted from the c
1288
1448
  --cert <dir> writes each proven law's certificate (its meta the citations); --from any (or from = "any" in gdp.toml, for every
1289
1449
  rule or one) proves every law from every state the laws allow, for code that steps the rule from states it is handed. Exit code: 1 when a stated law is broken, 2 when
1290
1450
  one couldn't be checked.
1451
+ --safety (or a C file's \`// gdp: safety\`) checks undefined-behavior obligations in the supported C subset and replays broken obligations under ASan/UBSan.
1291
1452
  --security proposes authorization, tenant-write isolation, workflow, quota and ledger candidates over the code's names.
1292
1453
  Candidates require policy review, show broken runs too, and do not affect the exit code. Arbitrary input identities are
1293
1454
  not authenticated identities. State the intended policy with gdp: law comments; use gdp: env for concurrent isolation.`;
@@ -1312,7 +1473,10 @@ export async function check(targets, given = {}, each) {
1312
1473
  }
1313
1474
  const stated = all.flatMap(r => r.laws);
1314
1475
  // A sampled source translation cannot turn an unknown proof into a successful check.
1315
- return { rules: all, exit: stated.some(l => l.verdict === 'unknown' || l.translation === 'unchecked' || l.translation === 'error') ? 2 : stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read') || o.security && all.some(r => !r.ok) ? 2 : 0 };
1476
+ const safetyLookalike = all.some(r => r.notes.some(n => SAFETY_LOOKALIKE_NOTE_RE.test(n)));
1477
+ const uncheckedSafety = safetyLookalike || all.some(r => r.safety && ('why' in r.safety || r.safety.status === 'unchecked' || r.safety.status === 'unproven'));
1478
+ const brokenSafety = all.some(r => r.safety && !('why' in r.safety) && r.safety.status === 'broken');
1479
+ return { rules: all, exit: uncheckedSafety || stated.some(l => l.verdict === 'unknown' || l.translation === 'unchecked' || l.translation === 'error') ? 2 : brokenSafety || stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read') || o.security && all.some(r => !r.ok) ? 2 : 0 };
1316
1480
  }
1317
1481
  // --- draft: laws from a clause, for a person to review ----------------------------------------------------------------
1318
1482
  // gdp-wired draft <file> --clause <text> | --clause-file <f> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]:
@@ -1396,5 +1560,16 @@ export async function main(argv) {
1396
1560
  return code;
1397
1561
  }
1398
1562
  if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$/.test(proc.argv[1] ?? '')) {
1563
+ let sigExiting = false;
1564
+ const onSignal = (code) => () => {
1565
+ if (sigExiting)
1566
+ return;
1567
+ sigExiting = true;
1568
+ cleanupCSafetySnapshots();
1569
+ proc.exit?.(code);
1570
+ };
1571
+ proc.on?.('SIGINT', onSignal(130));
1572
+ proc.on?.('SIGTERM', onSignal(143));
1573
+ proc.on?.('exit', () => { cleanupCSafetySnapshots(); });
1399
1574
  main(proc.argv.slice(2)).then(c => { proc.exitCode = c; }, e => { out(`gdp-wired: ${e.message}`); proc.exitCode = 2; });
1400
1575
  }
@@ -5,6 +5,8 @@ import type { Sorts } from './extract-print.js';
5
5
  import { type GoRead } from './extract-go.js';
6
6
  import { type GoCheckOptions, type GoEvidence, type GoLeaf } from './extract-go-check.js';
7
7
  import { type CRead } from './c/reader.js';
8
+ import { type CSafetyResult } from './c/safety.js';
9
+ export { cSafetyArtifactOf, verifyCSafetyProof, type CSafetyArtifact, type CSafetyIssue, type CSafetyKind, type CSafetyMacroConfig, type CSafetyProofBundle, type CSafetyReplay, type CSafetyResult, type CSafetyRun, type CSafetyStatus } from './c/safety.js';
8
10
  export { minimizeRun, minimizeRunDetailed, proveRule, proveSteps } from './dsl.js';
9
11
  export type COptions = {
10
12
  entry?: string;
@@ -24,6 +26,10 @@ export type COptions = {
24
26
  onError?: 'refuse' | 'discard';
25
27
  domains?: Record<string, 'nat' | 'int'>;
26
28
  check?: GoCheckOptions;
29
+ /** First-fault C safety analysis of the covered subset, with ASan/UBSan replay on broken obligations. */
30
+ safety?: boolean;
31
+ /** Optional prover search budget per safety obligation (ms, default 10000). */
32
+ safetySearchMs?: number;
27
33
  };
28
34
  export declare function readCFile(file: string, opts: COptions, cpp?: boolean): {
29
35
  c: CRead;
@@ -31,9 +37,11 @@ export declare function readCFile(file: string, opts: COptions, cpp?: boolean):
31
37
  };
32
38
  export declare function extractC(at: string | FileURL, given?: COptions, cpp?: boolean): Extraction & {
33
39
  leaves?: GoLeaf[];
40
+ safety?: CSafetyResult;
34
41
  };
35
42
  export declare const extractCpp: (at: string | FileURL, opts?: COptions) => Extraction & {
36
43
  leaves?: GoLeaf[];
44
+ safety?: CSafetyResult;
37
45
  };
38
46
  export declare function harnessC(file: string, c: CRead, read: GoRead, opts: COptions, cpp: boolean): string;
39
47
  export declare function checkC(file: string, flags: string[], c: CRead, read: GoRead, r: Rule, sorts: Sorts, opts: COptions, cpp: boolean): GoEvidence;
@@ -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; },