gdp-wired 0.55.1 → 0.56.1
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/README.md +48 -0
- package/dist/core/agent-consult/cli.js +11 -0
- package/dist/core/agent-consult/worker.js +9 -0
- package/dist/core/c/reader.d.ts +74 -2
- package/dist/core/c/reader.js +3144 -121
- package/dist/core/c/safety.d.ts +98 -0
- package/dist/core/c/safety.js +642 -0
- package/dist/core/cli.d.ts +9 -0
- package/dist/core/cli.js +215 -8
- package/dist/core/extract-c.d.ts +8 -0
- package/dist/core/extract-c.js +114 -15
- package/dist/core/extract-check.js +124 -12
- package/dist/core/extract-go-check.js +6 -0
- package/dist/core/extract-go.d.ts +15 -1
- package/dist/core/extract-go.js +102 -4
- package/dist/core/extract-print.js +4 -2
- package/dist/core/extract-step.d.ts +22 -0
- package/dist/core/extract-step.js +261 -9
- package/dist/core/extract.d.ts +10 -0
- package/dist/core/extract.js +37 -3
- package/dist/core/law-answer.d.ts +1 -0
- package/dist/core/law-answer.js +23 -0
- package/dist/core/laws.js +3 -16
- package/dist/core/native-law.js +11 -3
- package/dist/interchange/cli.js +13 -0
- package/package.json +1 -1
package/dist/core/cli.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import type { Extraction, Name } from './extract.js';
|
|
3
|
+
import type { CSafetyResult } from './c/safety.js';
|
|
3
4
|
import { type SecurityCandidate } from './security.js';
|
|
4
5
|
import { type Verdict } from './dsl.js';
|
|
5
6
|
import type { TranslationFields } from './source-check.js';
|
|
@@ -88,7 +89,11 @@ export type RuleOut = {
|
|
|
88
89
|
brokenProposed?: number;
|
|
89
90
|
source?: string;
|
|
90
91
|
security?: (LawOut & Pick<SecurityCandidate, 'securityKind' | 'review'>)[];
|
|
92
|
+
safety?: SafetyReport;
|
|
91
93
|
};
|
|
94
|
+
type SafetyReport = {
|
|
95
|
+
why: string;
|
|
96
|
+
} | CSafetyResult;
|
|
92
97
|
type Scoped = LawText & {
|
|
93
98
|
cls?: string;
|
|
94
99
|
fn?: string;
|
|
@@ -106,4 +111,8 @@ export declare function check(targets: string[], given?: Partial<Opts>, each?: (
|
|
|
106
111
|
exit: number;
|
|
107
112
|
}>;
|
|
108
113
|
export declare function main(argv: string[]): Promise<number>;
|
|
114
|
+
export declare function runCli(argv?: string[], opts?: {
|
|
115
|
+
label?: string;
|
|
116
|
+
run?: (argv: string[]) => Promise<number>;
|
|
117
|
+
}): void;
|
|
109
118
|
export {};
|
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";
|
|
@@ -27,6 +28,7 @@ import { contend, envOf, inEnv, shrinkRun } from "./system.js";
|
|
|
27
28
|
const proc = globalThis.process;
|
|
28
29
|
const fs = proc.getBuiltinModule('node:fs'), path = proc.getBuiltinModule('node:path');
|
|
29
30
|
const out = (s = '') => proc.stdout.write(`${s}\n`);
|
|
31
|
+
const err = (s) => (proc.stderr ?? proc.stdout).write(`${s}\n`);
|
|
30
32
|
// Color, plain ANSI: only on a terminal, never with --json, NO_COLOR (any value) or TERM=dumb; FORCE_COLOR turns it on.
|
|
31
33
|
// Uncolored, the text is the same byte for byte.
|
|
32
34
|
export const colors = (env, tty, json = false) => !json && (env.FORCE_COLOR !== undefined && !['0', 'false'].includes(env.FORCE_COLOR) ? true : env.NO_COLOR === undefined && env.TERM !== 'dumb' && tty);
|
|
@@ -45,6 +47,8 @@ function args(argv) {
|
|
|
45
47
|
o.propose = false;
|
|
46
48
|
else if (a === '--security')
|
|
47
49
|
o.security = true;
|
|
50
|
+
else if (a === '--safety')
|
|
51
|
+
o.safety = true;
|
|
48
52
|
else if (a === '--require-review')
|
|
49
53
|
o.requireReview = true;
|
|
50
54
|
else if (a.startsWith('--')) {
|
|
@@ -307,6 +311,10 @@ const searchOf = (v) => v.stopped && v.termination && !(v.proven && v.checked) &
|
|
|
307
311
|
? { stopped: true, termination: v.termination, ...(v.context ? { context: v.context } : {}) } : {};
|
|
308
312
|
const whyOf = (v, semantic) => searchOf(v).termination && v.translation !== 'unchecked' && v.translation !== 'error'
|
|
309
313
|
? terminationWhy(v.termination) : semantic;
|
|
314
|
+
function safetyReport(x, requested) {
|
|
315
|
+
const report = x.safety;
|
|
316
|
+
return report ?? (requested ? { why: 'the extractor did not provide a C safety model' } : undefined);
|
|
317
|
+
}
|
|
310
318
|
function* expandInitializers(t, o, laws, rows) {
|
|
311
319
|
if (!rows.some(r => r.x.initializers))
|
|
312
320
|
return rows;
|
|
@@ -347,6 +355,98 @@ function* expandInitializers(t, o, laws, rows) {
|
|
|
347
355
|
}
|
|
348
356
|
return out;
|
|
349
357
|
}
|
|
358
|
+
// Extract C comment bodies (`// ...` and `/* ... */`), applying C phase-2 line splicing (`\<newline>`)
|
|
359
|
+
// and skipping string literals, char literals, and C23 preprocessing numbers (`1'000`, `0xDE'AD`).
|
|
360
|
+
function cCommentTexts(rawSrc) {
|
|
361
|
+
const src = rawSrc.replace(/\\\r?\n/g, '');
|
|
362
|
+
const out = [];
|
|
363
|
+
const isIdent = (c) => !!c && /[A-Za-z0-9_$]/.test(c);
|
|
364
|
+
const isDigit = (c) => !!c && c >= '0' && c <= '9';
|
|
365
|
+
const isPpCont = (c) => !!c && /[0-9A-Za-z_.]/.test(c);
|
|
366
|
+
for (let i = 0; i < src.length; i++) {
|
|
367
|
+
const ch = src[i];
|
|
368
|
+
if ((isDigit(ch) && !isIdent(src[i - 1])) || (ch === '.' && isDigit(src[i + 1]))) {
|
|
369
|
+
let j = i + (ch === '.' ? 2 : 1);
|
|
370
|
+
while (j < src.length) {
|
|
371
|
+
const c = src[j];
|
|
372
|
+
if ((c === 'e' || c === 'E' || c === 'p' || c === 'P') && (src[j + 1] === '+' || src[j + 1] === '-')) {
|
|
373
|
+
j += 2;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (c === "'" && /[0-9A-Za-z_]/.test(src[j + 1] ?? '')) {
|
|
377
|
+
j += 2;
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
if (isPpCont(c)) {
|
|
381
|
+
j++;
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
i = j - 1;
|
|
387
|
+
}
|
|
388
|
+
else if (ch === '"' || ch === "'") {
|
|
389
|
+
const q = ch;
|
|
390
|
+
for (i++; i < src.length; i++) {
|
|
391
|
+
if (src[i] === '\\') {
|
|
392
|
+
i++;
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
if (src[i] === q || src[i] === '\n')
|
|
396
|
+
break;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
else if (ch === '/' && src[i + 1] === '/') {
|
|
400
|
+
const start = i + 2;
|
|
401
|
+
while (i < src.length && src[i] !== '\n')
|
|
402
|
+
i++;
|
|
403
|
+
out.push(src.slice(start, i));
|
|
404
|
+
}
|
|
405
|
+
else if (ch === '/' && src[i + 1] === '*') {
|
|
406
|
+
const start = i + 2;
|
|
407
|
+
const end = src.indexOf('*/', start);
|
|
408
|
+
if (end < 0) {
|
|
409
|
+
out.push(src.slice(start));
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
out.push(src.slice(start, end));
|
|
413
|
+
i = end + 1;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
// Normalize Unicode whitespace (including NBSP and newlines), block-comment leading `*`, and
|
|
419
|
+
// fullwidth/compatibility colons so lookalike directives are never silently missed.
|
|
420
|
+
const normalizeSafetyText = (s) => s.replace(/[\uFF1A\uFE55\uFE13\u2236]/g, ':')
|
|
421
|
+
.replace(/\r?\n[ \t]*\*+[ \t]*/g, ' ')
|
|
422
|
+
.replace(/[\s\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000\uFEFF]+/g, ' ');
|
|
423
|
+
// Accept `// gdp: safety`, `/* gdp: safety */`, multiline `/* gdp:\n safety */`, backslash-continued
|
|
424
|
+
// `// ...\n gdp: safety`, case/punctuation variants, and trailing text, while rejecting assignments.
|
|
425
|
+
const SAFETY_TAG_RE = /\bgdp[ \t\r\n]*:[ \t\r\n]*safety\b(?![ \t]*=)/i;
|
|
426
|
+
const SAFETY_LOOKALIKE_RE = /\bgdp(?:\s*:\s*|\s+)safe\w*(?:\s*=\s*\S+)?/i;
|
|
427
|
+
const SAFETY_LOOKALIKE_NOTE_RE = /looks like a gdp: safety directive/;
|
|
428
|
+
const hasSafetyTag = (t) => t.lang === 'c' && t.files.some(f => cCommentTexts(fs.readFileSync(f, 'utf8')).some(c => SAFETY_TAG_RE.test(c)));
|
|
429
|
+
const safetyLookalikeNote = (t) => {
|
|
430
|
+
if (t.lang !== 'c' || hasSafetyTag(t))
|
|
431
|
+
return undefined;
|
|
432
|
+
for (const f of t.files) {
|
|
433
|
+
for (const c of cCommentTexts(fs.readFileSync(f, 'utf8'))) {
|
|
434
|
+
const m = SAFETY_LOOKALIKE_RE.exec(normalizeSafetyText(c));
|
|
435
|
+
if (m) {
|
|
436
|
+
const shown = /^gdp: safety$/i.test(m[0].trim()) ? c.trim().slice(0, 60) : m[0].trim();
|
|
437
|
+
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`;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return undefined;
|
|
442
|
+
};
|
|
443
|
+
const safetyDisabledBy = (cfg, entry) => cfg.all.safety === false || (!!entry && cfg.rules[entry]?.safety === false);
|
|
444
|
+
const safetyOverrideRefusal = (t) => ({
|
|
445
|
+
ok: false,
|
|
446
|
+
refusals: [{ where: t.at, what: 'gdp.toml disables safety (safety = false), conflicting with the in-source gdp: safety directive' }],
|
|
447
|
+
notes: [],
|
|
448
|
+
safety: { why: 'gdp.toml cannot silently override an in-source gdp: safety directive' },
|
|
449
|
+
});
|
|
350
450
|
function* rulesOf(t, o, laws) {
|
|
351
451
|
const got = yield* rulesOf0(t, o, laws);
|
|
352
452
|
if (o.entry)
|
|
@@ -369,9 +469,15 @@ function* rulesOf(t, o, laws) {
|
|
|
369
469
|
void _k;
|
|
370
470
|
void _f;
|
|
371
471
|
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])))];
|
|
472
|
+
const safetyTag = hasSafetyTag(t);
|
|
372
473
|
const extra = [];
|
|
373
|
-
for (const entry of more)
|
|
374
|
-
|
|
474
|
+
for (const entry of more) {
|
|
475
|
+
if (safetyTag && safetyDisabledBy(cfg, entry)) {
|
|
476
|
+
extra.push({ entry, x: safetyOverrideRefusal(t) });
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
extra.push({ entry, x: yield { target: t, options: { ...merge(merge({ ...shared, keep }, cfg.rules[entry] || {}), flags), ...(safetyTag ? { safety: true } : {}), entry } } });
|
|
480
|
+
}
|
|
375
481
|
// (the first rule, read with no entry named, kept only where it read something or nothing else was)
|
|
376
482
|
return yield* expandInitializers(t, o, laws, [...got.filter(r => r.x.ok || r.entry || !extra.length), ...extra]);
|
|
377
483
|
}
|
|
@@ -391,10 +497,15 @@ function* rulesOf0(t, o, laws) {
|
|
|
391
497
|
void _k;
|
|
392
498
|
// (the names the laws read, so an argument a law reads stays in the rule though the code ignores it)
|
|
393
499
|
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
|
|
500
|
+
const safetyTag = hasSafetyTag(t);
|
|
501
|
+
const optsFor = (entry) => ({ ...merge(merge({ ...shared, keep }, (entry && cfg.rules[entry]) || {}), flags), ...(safetyTag ? { safety: true } : {}) });
|
|
395
502
|
const one = function* (entry) {
|
|
503
|
+
if (safetyTag && safetyDisabledBy(cfg, entry))
|
|
504
|
+
return { entry, x: safetyOverrideRefusal(t) };
|
|
396
505
|
const x = yield { target: t, options: { ...optsFor(entry), ...(entry ? { entry } : {}) } };
|
|
397
|
-
const found = x.model?.name;
|
|
506
|
+
const found = x.model?.name ?? x.entry;
|
|
507
|
+
if (!entry && found && safetyTag && safetyDisabledBy(cfg, found))
|
|
508
|
+
return { entry: found, x: safetyOverrideRefusal(t) };
|
|
398
509
|
return !entry && found && cfg.rules[found] ? { entry: found, x: yield { target: t, options: { ...optsFor(found), entry: found } } } : { entry, x };
|
|
399
510
|
};
|
|
400
511
|
const manyOf = function* (entries) { const rows = []; for (const entry of entries)
|
|
@@ -598,9 +709,17 @@ function* checkPipeline(t, o) {
|
|
|
598
709
|
// Different initial states must never overwrite one another's certificates.
|
|
599
710
|
const ctx = ctor !== undefined && baseCtx.cert ? { ...baseCtx, cert: path.join(baseCtx.cert, `initializer-${initializerIndex}`) } : baseCtx;
|
|
600
711
|
let x = x0;
|
|
601
|
-
const name = entry ?? (x.model?.name || undefined);
|
|
712
|
+
const name = entry ?? (x.model?.name || x.entry || undefined);
|
|
602
713
|
// (a target that is the working directory, a crate's or a package's: `.`)
|
|
603
714
|
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 } : {}) };
|
|
715
|
+
const safety = safetyReport(x, o.safety === true || hasSafetyTag(t));
|
|
716
|
+
if (safety)
|
|
717
|
+
r.safety = safety;
|
|
718
|
+
else if (o.safety !== true) {
|
|
719
|
+
const warn = safetyLookalikeNote(t);
|
|
720
|
+
if (warn && !r.notes.includes(warn))
|
|
721
|
+
r.notes.push(warn);
|
|
722
|
+
}
|
|
604
723
|
outs.push(r);
|
|
605
724
|
// (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
725
|
// outside every class and function)
|
|
@@ -1195,6 +1314,7 @@ export const proposedLaws = (x, lang, ms = 2000) => propose(x, lang, { ms, propo
|
|
|
1195
1314
|
const ROLE = { state: 'state', param: 'made with', input: 'request', answer: 'answered', result: 'result', failed: 'failed', method: 'method', clock: 'clock', const: 'constant' };
|
|
1196
1315
|
function printRule(r, o) {
|
|
1197
1316
|
out(`${r.file}${r.entry ? `: ${r.entry}` : ''}${r.ctor !== undefined ? ` [ctor ${r.ctor}]` : ''} (${r.lang})`);
|
|
1317
|
+
const safetyWarnings = r.notes.filter(n => SAFETY_LOOKALIKE_NOTE_RE.test(n));
|
|
1198
1318
|
if (!r.ok) {
|
|
1199
1319
|
for (const f of r.refusals)
|
|
1200
1320
|
out(` ${paint('yellow', `refused at ${f.where}:`)} ${f.what}`);
|
|
@@ -1215,6 +1335,8 @@ function printRule(r, o) {
|
|
|
1215
1335
|
for (const n of r.names)
|
|
1216
1336
|
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
1337
|
}
|
|
1338
|
+
for (const n of safetyWarnings)
|
|
1339
|
+
out(` ${paint('yellow', 'warning:')} ${n}`);
|
|
1218
1340
|
const law = (l, proposed) => {
|
|
1219
1341
|
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
1342
|
if (!proposed && l.verdict !== 'proven')
|
|
@@ -1256,6 +1378,45 @@ function printRule(r, o) {
|
|
|
1256
1378
|
for (const l of r.laws)
|
|
1257
1379
|
law(l, false);
|
|
1258
1380
|
}
|
|
1381
|
+
if (r.safety) {
|
|
1382
|
+
out(' C safety (first-fault model; broken obligations replayed under ASan/UBSan):');
|
|
1383
|
+
if ('why' in r.safety)
|
|
1384
|
+
out(` ${paint('yellow', 'unchecked')}: ${r.safety.why}`);
|
|
1385
|
+
else {
|
|
1386
|
+
const color = (s) => s === 'proven' ? 'green' : s === 'broken' ? 'red' : 'yellow';
|
|
1387
|
+
const cov = r.safety.coveredFunctions.length ? r.safety.coveredFunctions.join(', ') : 'none';
|
|
1388
|
+
const helpers = r.safety.coveredHelpers?.length ? `; static helpers inlined: ${r.safety.coveredHelpers.join(', ')}` : '';
|
|
1389
|
+
out(` ${paint(color(r.safety.status), r.safety.status)} (covers: ${cov}${helpers})`);
|
|
1390
|
+
if (r.safety.macroConfig) {
|
|
1391
|
+
const mc = r.safety.macroConfig;
|
|
1392
|
+
const defs = mc.defines.length ? mc.defines.join(', ') : 'none';
|
|
1393
|
+
const incs = mc.includeDirs.length ? mc.includeDirs.join(', ') : 'none';
|
|
1394
|
+
const compiler = mc.compiler
|
|
1395
|
+
? `; compiler: ${mc.compiler}${mc.compilerPath ? ` (${mc.compilerPath})` : ''}`
|
|
1396
|
+
: mc.compilerPath ? `; compiler: ${mc.compilerPath}` : '';
|
|
1397
|
+
const libc = mc.libc ? `; libc: ${mc.libc}` : '';
|
|
1398
|
+
const userF = mc.userFilesSha256
|
|
1399
|
+
? `; user files: ${mc.userFiles?.length ?? 0} (sha256:${mc.userFilesSha256})`
|
|
1400
|
+
: '';
|
|
1401
|
+
const sysHdrs = mc.systemHeadersSha256
|
|
1402
|
+
? `; system headers: ${mc.systemHeaders?.length ?? 0} (sha256:${mc.systemHeadersSha256})`
|
|
1403
|
+
: '';
|
|
1404
|
+
const envNote = mc.envScrubbed ? 'scrubbed' : 'inherited';
|
|
1405
|
+
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'}`);
|
|
1406
|
+
}
|
|
1407
|
+
if (r.safety.uncheckedFunctions?.length)
|
|
1408
|
+
out(` ${paint('yellow', 'unchecked functions:')} ${r.safety.uncheckedFunctions.join(', ')}`);
|
|
1409
|
+
for (const s of r.safety.issues) {
|
|
1410
|
+
out(` ${paint(color(s.status), s.status)}: ${s.kind} at ${s.where}`);
|
|
1411
|
+
if (s.replay?.requests.length)
|
|
1412
|
+
out(` run: ${s.replay.requests.join(' -> ')}`);
|
|
1413
|
+
for (const line of s.replay?.reports ?? [])
|
|
1414
|
+
out(` sanitizer: ${line}`);
|
|
1415
|
+
}
|
|
1416
|
+
for (const a of r.safety.assumptions)
|
|
1417
|
+
out(` ${a}`);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1259
1420
|
if (r.security) {
|
|
1260
1421
|
out(' security candidates (NOT accepted policy; review the requirement and authentication boundary):');
|
|
1261
1422
|
for (const l of r.security)
|
|
@@ -1269,7 +1430,7 @@ function printRule(r, o) {
|
|
|
1269
1430
|
if (r.brokenProposed)
|
|
1270
1431
|
out(` (${r.brokenProposed} more proposed and broken by a run: not shown)`);
|
|
1271
1432
|
}
|
|
1272
|
-
if (r.ok && !r.laws.length)
|
|
1433
|
+
if (r.ok && !r.safety && !r.laws.length)
|
|
1273
1434
|
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
1435
|
void o;
|
|
1275
1436
|
out();
|
|
@@ -1288,6 +1449,7 @@ the clause a law answers: \`gdp: cite <law name>: <clause>\` (drafted from the c
|
|
|
1288
1449
|
--cert <dir> writes each proven law's certificate (its meta the citations); --from any (or from = "any" in gdp.toml, for every
|
|
1289
1450
|
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
1451
|
one couldn't be checked.
|
|
1452
|
+
--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
1453
|
--security proposes authorization, tenant-write isolation, workflow, quota and ledger candidates over the code's names.
|
|
1292
1454
|
Candidates require policy review, show broken runs too, and do not affect the exit code. Arbitrary input identities are
|
|
1293
1455
|
not authenticated identities. State the intended policy with gdp: law comments; use gdp: env for concurrent isolation.`;
|
|
@@ -1312,7 +1474,10 @@ export async function check(targets, given = {}, each) {
|
|
|
1312
1474
|
}
|
|
1313
1475
|
const stated = all.flatMap(r => r.laws);
|
|
1314
1476
|
// A sampled source translation cannot turn an unknown proof into a successful check.
|
|
1315
|
-
|
|
1477
|
+
const safetyLookalike = all.some(r => r.notes.some(n => SAFETY_LOOKALIKE_NOTE_RE.test(n)));
|
|
1478
|
+
const uncheckedSafety = safetyLookalike || all.some(r => r.safety && ('why' in r.safety || r.safety.status === 'unchecked' || r.safety.status === 'unproven'));
|
|
1479
|
+
const brokenSafety = all.some(r => r.safety && !('why' in r.safety) && r.safety.status === 'broken');
|
|
1480
|
+
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' || l.verdict !== 'proven') || o.security && all.some(r => !r.ok) ? 2 : 0 };
|
|
1316
1481
|
}
|
|
1317
1482
|
// --- draft: laws from a clause, for a person to review ----------------------------------------------------------------
|
|
1318
1483
|
// gdp-wired draft <file> --clause <text> | --clause-file <f> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]:
|
|
@@ -1395,6 +1560,48 @@ export async function main(argv) {
|
|
|
1395
1560
|
}
|
|
1396
1561
|
return code;
|
|
1397
1562
|
}
|
|
1563
|
+
export function runCli(argv = proc.argv.slice(2), opts = {}) {
|
|
1564
|
+
const label = opts.label ?? 'gdp-wired', run = opts.run ?? main;
|
|
1565
|
+
let settled = false, reported = false, sigExiting = false;
|
|
1566
|
+
// Fail-safe: never exit 0 unless main() resolves and authorizes the final code.
|
|
1567
|
+
proc.exitCode = 2;
|
|
1568
|
+
const onUnsettled = (why) => {
|
|
1569
|
+
if (settled || sigExiting || reported)
|
|
1570
|
+
return;
|
|
1571
|
+
reported = true;
|
|
1572
|
+
proc.exitCode = 2;
|
|
1573
|
+
err(`gdp-wired: the check did not complete (${why})`);
|
|
1574
|
+
};
|
|
1575
|
+
const onSignal = (code) => () => {
|
|
1576
|
+
if (sigExiting)
|
|
1577
|
+
return;
|
|
1578
|
+
sigExiting = true;
|
|
1579
|
+
cleanupCSafetySnapshots();
|
|
1580
|
+
proc.exit?.(code);
|
|
1581
|
+
};
|
|
1582
|
+
proc.on?.('SIGINT', onSignal(130));
|
|
1583
|
+
proc.on?.('SIGTERM', onSignal(143));
|
|
1584
|
+
proc.on?.('beforeExit', () => { onUnsettled('main did not settle before process exit'); });
|
|
1585
|
+
proc.on?.('exit', () => { cleanupCSafetySnapshots(); onUnsettled('process exited before main settled'); });
|
|
1586
|
+
let pending;
|
|
1587
|
+
try {
|
|
1588
|
+
pending = run(argv);
|
|
1589
|
+
}
|
|
1590
|
+
catch (e) {
|
|
1591
|
+
settled = true;
|
|
1592
|
+
out(`${label}: ${e instanceof Error ? e.message : String(e)}`);
|
|
1593
|
+
proc.exitCode = 2;
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
pending.then(c => {
|
|
1597
|
+
settled = true;
|
|
1598
|
+
proc.exitCode = typeof c === 'number' && Number.isInteger(c) ? c : 2;
|
|
1599
|
+
}, e => {
|
|
1600
|
+
settled = true;
|
|
1601
|
+
out(`${label}: ${e instanceof Error ? e.message : String(e)}`);
|
|
1602
|
+
proc.exitCode = 2;
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1398
1605
|
if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$/.test(proc.argv[1] ?? '')) {
|
|
1399
|
-
|
|
1606
|
+
runCli(proc.argv.slice(2));
|
|
1400
1607
|
}
|
package/dist/core/extract-c.d.ts
CHANGED
|
@@ -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;
|
package/dist/core/extract-c.js
CHANGED
|
@@ -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')).
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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`]); };
|