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.
@@ -1,4 +1,25 @@
1
1
  import { Refusal, readerRun, statedRefusal } from "../extract-read.js";
2
+ export class SafetyUncoveredRefusal extends Refusal {
3
+ coveredFunctions;
4
+ uncheckedFunctions;
5
+ macroConfig;
6
+ constructor(where, what, coveredFunctions, uncheckedFunctions, macroConfig) {
7
+ super(where, what);
8
+ this.coveredFunctions = coveredFunctions;
9
+ this.uncheckedFunctions = uncheckedFunctions;
10
+ this.macroConfig = macroConfig;
11
+ }
12
+ }
13
+ const CLANG_TIMEOUT_MS = 30_000;
14
+ function clangRunOpts(extra) {
15
+ const rr = readerRun();
16
+ const timeout = typeof rr.timeout === 'number' && rr.timeout > 0 ? Math.min(rr.timeout, CLANG_TIMEOUT_MS) : CLANG_TIMEOUT_MS;
17
+ return { ...rr, timeout, killSignal: 'SIGKILL', ...(extra ?? {}) };
18
+ }
19
+ const isTimeoutErr = (err, signal) => err?.code === 'ETIMEDOUT' || signal === 'SIGKILL' || signal === 'SIGTERM';
20
+ // Reject /proc, /dev, and /sys paths case-insensitively so case-insensitive filesystems
21
+ // (e.g. macOS APFS/HFS+ where /Dev/stdin or /PROC/... alias /dev and /proc) cannot bypass checks.
22
+ export const isSpecialVirtualPath = (p) => /^\/(?:proc|dev|sys)(?:\/|$)/i.test(p);
2
23
  // (consecutive JSON values in one string, each with where it ends)
3
24
  class JSONDecoder {
4
25
  decode(s, i) {
@@ -24,33 +45,2055 @@ class JSONDecoder {
24
45
  const proc = globalThis.process;
25
46
  export const node = (id) => { const m = proc?.getBuiltinModule?.(id); if (!m)
26
47
  throw new Error(`the C front end runs clang through ${id} (Node 20.16 or later, or Bun)`); return m; };
48
+ // Fixed safe PATH directories for resolving and invoking Clang (closed-world allowlist).
49
+ // Never inherits caller PATH, CPATH, C_INCLUDE_PATH, CCC_OVERRIDE_OPTIONS, CLANG_CONFIG_*,
50
+ // LD_PRELOAD, HOME, SDKROOT, or any other environment variable that could alter driver behavior.
51
+ export const SAFE_CLANG_DIRS = [
52
+ '/usr/bin',
53
+ '/bin',
54
+ '/usr/local/bin',
55
+ '/opt/swift/usr/bin',
56
+ '/opt/homebrew/bin',
57
+ '/Library/Developer/CommandLineTools/usr/bin',
58
+ ];
59
+ export const SAFE_CLANG_PATH = SAFE_CLANG_DIRS.join(':');
60
+ export function scrubbedClangEnv(extra) {
61
+ const os = node('node:os');
62
+ return {
63
+ PATH: SAFE_CLANG_PATH,
64
+ LC_ALL: 'C',
65
+ TMPDIR: os.tmpdir(),
66
+ ...(extra ?? {}),
67
+ };
68
+ }
69
+ const isNativeExecutable = (fs, p) => {
70
+ try {
71
+ const fd = fs.openSync(p, 'r');
72
+ try {
73
+ const buf = new Uint8Array(4);
74
+ if (fs.readSync(fd, buf, 0, 4, 0) < 4)
75
+ return false;
76
+ const b0 = buf[0], b1 = buf[1], b2 = buf[2], b3 = buf[3];
77
+ // ELF (\x7fELF)
78
+ if (b0 === 0x7f && b1 === 0x45 && b2 === 0x4c && b3 === 0x46)
79
+ return true;
80
+ // Mach-O 32/64/universal (both endiannesses)
81
+ const u32 = ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) >>> 0;
82
+ return u32 === 0xfeedface || u32 === 0xcefaedfe || u32 === 0xfeedfacf || u32 === 0xcffaedfe || u32 === 0xcafebabe || u32 === 0xbebafeca;
83
+ }
84
+ finally {
85
+ fs.closeSync(fd);
86
+ }
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ };
92
+ const parseSearchDirs = (stderr, realPath) => {
93
+ const dirs = [];
94
+ let inAngle = false;
95
+ for (const rawLine of stderr.split('\n')) {
96
+ const line = rawLine.replace(/\r$/, '');
97
+ if (/^#include <\.\.\.> search starts here:\s*$/.test(line)) {
98
+ inAngle = true;
99
+ continue;
100
+ }
101
+ if (inAngle) {
102
+ if (/^End of search list\.\s*$/.test(line))
103
+ break;
104
+ const trimmed = line.trim();
105
+ const framework = /\s+\(framework directory\)$/.test(trimmed);
106
+ const dir = trimmed.replace(/\s+\(framework directory\)$/, '');
107
+ if (dir)
108
+ dirs.push({ raw: dir, real: realPath(dir), framework });
109
+ }
110
+ }
111
+ return dirs;
112
+ };
113
+ // Verify a candidate Clang binary is a real native executable (never a shell/script wrapper)
114
+ // that loads no external configuration file, injects no non-builtin include/macro flags into
115
+ // `-cc1`, and produces identical predefines (`-dM -E`) and search list (`-E -v`) to invoking
116
+ // its underlying `-cc1` binary directly with no wrapper arguments.
117
+ export function verifyClangBinary(clangPath, file) {
118
+ const cp = node('node:child_process');
119
+ const fs = node('node:fs');
120
+ const path = node('node:path');
121
+ const realPath = (p) => { try {
122
+ return fs.realpathSync(p);
123
+ }
124
+ catch {
125
+ return path.resolve(p);
126
+ } };
127
+ let resolved;
128
+ try {
129
+ resolved = fs.realpathSync(clangPath);
130
+ }
131
+ catch {
132
+ throw new Refusal(file, `compiler ${clangPath} could not be resolved`);
133
+ }
134
+ if (!path.isAbsolute(resolved))
135
+ throw new Refusal(file, `compiler ${clangPath} did not resolve to an absolute path`);
136
+ if (!isNativeExecutable(fs, resolved))
137
+ throw new Refusal(file, `compiler ${resolved} is not a native executable (scripts and wrappers are refused in C safety mode)`);
138
+ const clangEnv = scrubbedClangEnv();
139
+ const runCheck = (bin, args) => {
140
+ const r = cp.spawnSync(bin, args, clangRunOpts({ encoding: 'utf8', maxBuffer: 1 << 26, stdio: ['ignore', 'pipe', 'pipe'], env: clangEnv }));
141
+ if (r.error || r.signal) {
142
+ const stated = r.error ? statedRefusal(r.error) : undefined;
143
+ if (stated)
144
+ throw new Refusal(file, stated);
145
+ if (isTimeoutErr(r.error, r.signal))
146
+ throw new Refusal(file, `compiler ${bin} timed out during verification`);
147
+ throw new Refusal(file, `failed to run compiler ${bin}: ${r.error?.message ?? r.signal}`);
148
+ }
149
+ if (r.status !== 0)
150
+ throw new Refusal(file, `compiler ${bin} failed verification (${String(r.stderr ?? '').split('\n').slice(0, 2).join(' | ')})`);
151
+ return { stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
152
+ };
153
+ const drv = runCheck(resolved, ['-###', '-x', 'c', '-E', '/dev/null']);
154
+ if (/^Configuration file:/m.test(drv.stderr))
155
+ throw new Refusal(file, `compiler ${resolved} loaded an external configuration file (outside the C safety subset)`);
156
+ const cc1Line = drv.stderr.split('\n').find(l => /^\s*"[^"]+"\s+"-cc1"(?:\s|$)/.test(l));
157
+ if (!cc1Line)
158
+ throw new Refusal(file, `compiler ${resolved} did not invoke clang -cc1 directly`);
159
+ const cc1Args = [...cc1Line.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(m => m[1].replace(/\\(["\\])/g, '$1'));
160
+ const cc1Path = cc1Args[0];
161
+ if (!cc1Path)
162
+ throw new Refusal(file, `compiler ${resolved} did not report a -cc1 binary path`);
163
+ const forbiddenCc1Flags = new Set(['-isystem', '-I', '-iquote', '-include', '-imacros', '-U']);
164
+ for (const a of cc1Args.slice(1)) {
165
+ if (forbiddenCc1Flags.has(a))
166
+ throw new Refusal(file, `compiler ${resolved} injects non-builtin driver flag ${a} (wrappers and config overrides are refused in C safety mode)`);
167
+ }
168
+ let cc1Real;
169
+ try {
170
+ cc1Real = fs.realpathSync(cc1Path);
171
+ }
172
+ catch {
173
+ throw new Refusal(file, `compiler -cc1 binary ${cc1Path} could not be resolved`);
174
+ }
175
+ if (!isNativeExecutable(fs, cc1Real))
176
+ throw new Refusal(file, `compiler -cc1 binary ${cc1Real} is not a native executable`);
177
+ if (cc1Real !== resolved) {
178
+ const defsA = runCheck(resolved, ['-x', 'c', '-dM', '-E', '/dev/null']).stdout;
179
+ const probeVA = runCheck(resolved, ['-x', 'c', '-E', '-v', '-o', '/dev/null', '/dev/null']).stderr;
180
+ if (/^Configuration file:/m.test(probeVA))
181
+ throw new Refusal(file, `compiler ${resolved} loaded an external configuration file (outside the C safety subset)`);
182
+ const searchA = parseSearchDirs(probeVA, realPath).map(d => d.real).join('\n');
183
+ const defsB = runCheck(cc1Real, ['-x', 'c', '-dM', '-E', '/dev/null']).stdout;
184
+ const probeVB = runCheck(cc1Real, ['-x', 'c', '-E', '-v', '-o', '/dev/null', '/dev/null']).stderr;
185
+ const searchB = parseSearchDirs(probeVB, realPath).map(d => d.real).join('\n');
186
+ if (defsA !== defsB || searchA !== searchB)
187
+ throw new Refusal(file, `compiler ${resolved} predefines or search list differ from direct ${cc1Real} (wrappers are refused in C safety mode)`);
188
+ }
189
+ return { bin: cc1Real, cc1Real };
190
+ }
191
+ export function resolveSafetyClang(requestedClang, file) {
192
+ if (requestedClang !== 'clang')
193
+ throw new Refusal(file, 'C safety does not accept a custom compiler (clang option)');
194
+ const fs = node('node:fs');
195
+ const path = node('node:path');
196
+ for (const dir of SAFE_CLANG_DIRS) {
197
+ const cand = path.join(dir, 'clang');
198
+ try {
199
+ if (!fs.statSync(cand).isFile())
200
+ continue;
201
+ fs.accessSync(cand, fs.constants.X_OK);
202
+ return verifyClangBinary(cand, file);
203
+ }
204
+ catch (e) {
205
+ if (e instanceof Refusal)
206
+ throw e;
207
+ }
208
+ }
209
+ throw new Refusal(file, `no verified system clang found in safe PATH (${SAFE_CLANG_PATH})`);
210
+ }
211
+ // Predefined macros whose expansion depends on invocation path, clock, or counter rather than the
212
+ // source itself. Refused unconditionally anywhere in user files in C safety mode.
213
+ const INVOCATION_DEPENDENT_MACROS = new Set([
214
+ '__FILE__',
215
+ '__BASE_FILE__',
216
+ '__FILE_NAME__',
217
+ '__TIMESTAMP__',
218
+ '__DATE__',
219
+ '__TIME__',
220
+ '__COUNTER__',
221
+ '__LINE__',
222
+ '__INCLUDE_LEVEL__',
223
+ ]);
224
+ const PREPROC_OPERATORS = new Set([
225
+ '__has_builtin',
226
+ '__has_feature',
227
+ '__has_extension',
228
+ '__has_attribute',
229
+ '__has_c_attribute',
230
+ '__has_cpp_attribute',
231
+ '__has_declspec_attribute',
232
+ '__has_include',
233
+ '__has_include_next',
234
+ '__has_warning',
235
+ '__has_embed',
236
+ '__is_identifier',
237
+ '__building_module',
238
+ '_Pragma',
239
+ ]);
240
+ // Closed-world compiler builtin allowlist for C safety mode: C safety lowers no `__builtin_*`
241
+ // calls, so every `__builtin_*` identifier in user code (including `__builtin_FILE`,
242
+ // `__builtin_FILE_NAME`, `__builtin_strlen`, etc.) is refused outright.
243
+ const ALLOWED_BUILTINS = new Set([]);
244
+ // All 9 C trigraph sequences. Refused outright anywhere in user files (and -D values) so
245
+ // trigraph-mode differences between standards (e.g. gnu17 vs c11) can never hide code or macros.
246
+ const TRIGRAPH_RE = /\?\?[=/'()!<>-]/;
247
+ // Obtain the exact raw token stream directly from Clang's own lexer (`-Xclang -dump-raw-tokens`)
248
+ // under the active C standard flags, never re-lexing in TypeScript. Enforces strict byte
249
+ // contiguity from byte 0 (or byte 3 after a UTF-8 BOM) through EOF: every token must start at
250
+ // `expectedByte`, match `rawBuf` byte-for-byte, validate any `[UnClean='...']` splice against
251
+ // its cleaned text, and reach `rawBuf.length` with zero gaps or overlaps (closing forged token
252
+ // records inside comments or string literals).
253
+ function dumpClangRawTokens(activeClang, stdFlags, targetFile, rawBuf, clangEnv, reportFile) {
254
+ const cp = node('node:child_process');
255
+ const r = cp.spawnSync(activeClang, ['-x', 'c', '-w', ...stdFlags, '-Xclang', '-dump-raw-tokens', '-fsyntax-only', targetFile], clangRunOpts({
256
+ encoding: 'utf8',
257
+ maxBuffer: 1 << 28,
258
+ stdio: ['ignore', 'pipe', 'pipe'],
259
+ env: clangEnv,
260
+ }));
261
+ if (r.error || r.signal || r.status !== 0) {
262
+ const stated = r.error ? statedRefusal(r.error) : undefined;
263
+ if (stated)
264
+ throw new Refusal(reportFile, stated);
265
+ if (isTimeoutErr(r.error, r.signal))
266
+ throw new Refusal(reportFile, `clang raw token dump timed out for ${reportFile} (outside the C safety subset)`);
267
+ throw new Refusal(reportFile, `clang raw token dump failed for ${reportFile} (${String(r.stderr ?? r.error?.message ?? '').split('\n').slice(0, 2).join(' | ')})`);
268
+ }
269
+ const out = r.stderr ?? '';
270
+ // Compute 0-based UTF-8 byte offsets of each 1-based source line in rawBuf (matching Clang's
271
+ // handling of LF, CRLF, and lone CR line endings).
272
+ const lineByteOffsets = [0];
273
+ for (let i = 0; i < rawBuf.length; i++) {
274
+ const b = rawBuf[i];
275
+ if (b === 0x0a)
276
+ lineByteOffsets.push(i + 1);
277
+ else if (b === 0x0d && rawBuf[i + 1] !== 0x0a)
278
+ lineByteOffsets.push(i + 1);
279
+ }
280
+ const encoder = new TextEncoder();
281
+ const matchesRawBytesAt = (start, expBytes) => {
282
+ if (start < 0 || start + expBytes.length > rawBuf.length)
283
+ return false;
284
+ for (let i = 0; i < expBytes.length; i++)
285
+ if (rawBuf[start + i] !== expBytes[i])
286
+ return false;
287
+ return true;
288
+ };
289
+ const locPrefix = `\tLoc=<${targetFile}:`;
290
+ const tokens = [];
291
+ let pos = 0;
292
+ let expectedByte = rawBuf.length >= 3 && rawBuf[0] === 0xef && rawBuf[1] === 0xbb && rawBuf[2] === 0xbf ? 3 : 0;
293
+ while (pos < out.length) {
294
+ const head = /^([A-Za-z_][A-Za-z_0-9]*) '/.exec(out.slice(pos, pos + 64));
295
+ if (!head)
296
+ throw new Refusal(reportFile, `unexpected clang -dump-raw-tokens output near offset ${pos}`);
297
+ const kind = head[1];
298
+ const textStart = pos + head[0].length;
299
+ let searchFrom = textStart;
300
+ let parsed;
301
+ while (searchFrom < out.length) {
302
+ const locIdx = out.indexOf(locPrefix, searchFrom);
303
+ if (locIdx < 0)
304
+ break;
305
+ const locEnd = out.indexOf('>\n', locIdx + locPrefix.length);
306
+ if (locEnd < 0)
307
+ break;
308
+ const lc = /^(\d+):(\d+)$/.exec(out.slice(locIdx + locPrefix.length, locEnd));
309
+ const afterPos = locEnd + 2;
310
+ if (lc && (afterPos === out.length || /^[A-Za-z_][A-Za-z_0-9]* '/.test(out.slice(afterPos, afterPos + 64)))) {
311
+ const line = Number(lc[1]);
312
+ const col = Number(lc[2]);
313
+ const lineOff = lineByteOffsets[line - 1];
314
+ const tokByte = lineOff === undefined ? -1 : lineOff + (col - 1);
315
+ const expectedAt = kind === 'eof' ? rawBuf.length : expectedByte;
316
+ if (tokByte === expectedAt) {
317
+ const mid = out.slice(textStart, locIdx);
318
+ // Split `mid` at the `'\t` before Clang's `[Flag]` / `[UnClean='...']` annotations.
319
+ for (let q = mid.indexOf("'\t"); q >= 0; q = mid.indexOf("'\t", q + 1)) {
320
+ const flagStr = mid.slice(q + 2);
321
+ if (/^(?: \[(?:[A-Za-z_][A-Za-z0-9_]*|UnClean='[\s\S]*?')\])*$/.test(flagStr)) {
322
+ const candText = mid.slice(0, q);
323
+ const uncleanM = /\[UnClean='([\s\S]*?)'\]$/.exec(flagStr);
324
+ if (uncleanM) {
325
+ const rawStr = uncleanM[1];
326
+ if (!/\\[ \t]*(?:\r?\n|\r)/.test(rawStr) || rawStr.replace(/\\[ \t]*(?:\r?\n|\r)/g, '') !== candText)
327
+ continue;
328
+ }
329
+ const rawMatch = uncleanM ? uncleanM[1] : candText;
330
+ const rawBytes = kind === 'eof' ? new Uint8Array(0) : encoder.encode(rawMatch);
331
+ if (kind === 'eof' || matchesRawBytesAt(expectedByte, rawBytes)) {
332
+ parsed = { text: candText, flags: flagStr, line, col, nextPos: afterPos, rawLen: rawBytes.length };
333
+ break;
334
+ }
335
+ }
336
+ }
337
+ if (parsed)
338
+ break;
339
+ }
340
+ }
341
+ searchFrom = locIdx + 1;
342
+ }
343
+ if (!parsed)
344
+ throw new Refusal(reportFile, `failed to parse clang -dump-raw-tokens token (${kind}) contiguously at byte ${expectedByte} (outside the C safety subset)`);
345
+ tokens.push({
346
+ kind,
347
+ text: parsed.text,
348
+ startOfLine: parsed.flags.includes('[StartOfLine]'),
349
+ line: parsed.line,
350
+ col: parsed.col,
351
+ hadSpaceBefore: false,
352
+ });
353
+ expectedByte += parsed.rawLen;
354
+ pos = parsed.nextPos;
355
+ }
356
+ if (expectedByte !== rawBuf.length)
357
+ throw new Refusal(reportFile, `clang -dump-raw-tokens byte coverage mismatch (${expectedByte} != ${rawBuf.length} bytes; outside the C safety subset)`);
358
+ return tokens;
359
+ }
360
+ function parseClangHeaderLines(stderr) {
361
+ const out = [];
362
+ for (const rawLine of stderr.split('\n')) {
363
+ const hm = /^(\.+) (.+)$/.exec(rawLine.replace(/\r$/, ''));
364
+ if (hm)
365
+ out.push({ depth: hm[1], raw: hm[2] });
366
+ }
367
+ return out;
368
+ }
369
+ // Obtain the preprocessed user-code token stream directly from Clang's own `-Xclang -dump-tokens`
370
+ // (never re-lexing preprocessed C in TypeScript), with `-H` include-list reporting whenever
371
+ // `verifyHeaders` or `onHeaders` is provided. When `userFiles` is provided, also enforces:
372
+ // (a) `<scratch space>` rejection (invocation-dependent macros / token pasting) and
373
+ // (b) closed-world `__builtin_*` allowlist on every token expanded in user files.
374
+ function dumpUserExpandedTokens(o) {
375
+ const cp = node('node:child_process');
376
+ const wantHeaders = !!(o.verifyHeaders || o.onHeaders);
377
+ const r = cp.spawnSync(o.activeClang, [...o.lang, '-w', ...o.flags, ...(wantHeaders ? ['-H'] : []), '-Xclang', '-dump-tokens', '-fsyntax-only', o.targetFile], clangRunOpts({
378
+ encoding: 'utf8',
379
+ maxBuffer: 1 << 28,
380
+ stdio: ['ignore', 'pipe', 'pipe'],
381
+ env: o.clangEnv,
382
+ ...(o.cwd ? { cwd: o.cwd } : {}),
383
+ }));
384
+ if (r.error || r.signal || r.status !== 0) {
385
+ const stated = r.error ? statedRefusal(r.error) : undefined;
386
+ if (stated)
387
+ throw new Refusal(o.reportFile, stated);
388
+ if (isTimeoutErr(r.error, r.signal))
389
+ throw new Refusal(o.reportFile, 'clang -dump-tokens audit timed out (possible non-regular file/FIFO or runaway preprocessing; outside the C safety subset)');
390
+ throw new Refusal(o.reportFile, o.failMessage ?? `clang -dump-tokens audit failed (${String(r.stderr ?? r.error?.message ?? '').split('\n').slice(0, 2).join(' | ')})`);
391
+ }
392
+ const userToks = [];
393
+ const headers = [];
394
+ for (const rawLine of (r.stderr ?? '').split('\n')) {
395
+ if (!rawLine)
396
+ continue;
397
+ if (wantHeaders) {
398
+ const hdrM = /^(\.+) (.+)$/.exec(rawLine.replace(/\r$/, ''));
399
+ if (hdrM) {
400
+ headers.push({ depth: hdrM[1], raw: hdrM[2] });
401
+ continue;
402
+ }
403
+ }
404
+ const locIdx = rawLine.lastIndexOf('\tLoc=<');
405
+ if (locIdx < 0 || !rawLine.endsWith('>'))
406
+ throw new Refusal(o.reportFile, `unexpected clang -dump-tokens output line: ${rawLine.slice(0, 80)}`);
407
+ const prefix = rawLine.slice(0, locIdx);
408
+ const head = /^([A-Za-z_][A-Za-z_0-9]*) '/.exec(prefix);
409
+ const q = prefix.lastIndexOf("'\t");
410
+ if (!head || q < head[0].length)
411
+ throw new Refusal(o.reportFile, `unexpected clang -dump-tokens token format: ${rawLine.slice(0, 80)}`);
412
+ const flagStr = prefix.slice(q + 2);
413
+ if (!/^(?: \[[A-Za-z_][A-Za-z0-9_]*\])*$/.test(flagStr))
414
+ throw new Refusal(o.reportFile, `unexpected clang -dump-tokens flag annotation: ${rawLine.slice(0, 80)}`);
415
+ const kind = head[1];
416
+ const text = prefix.slice(head[0].length, q);
417
+ const loc = rawLine.slice(locIdx + 6, -1);
418
+ if (kind === 'eof' && loc === '<invalid loc>')
419
+ continue;
420
+ // Split off any trailing ` <Spelling=...>` / ` <...>` annotations, then parse `<path>:<line>:<col>`
421
+ // greedily from the right so paths containing colons (e.g. `c:olon/ring.c`) parse faithfully;
422
+ // fail closed on any unparseable location instead of silently skipping tokens.
423
+ const expPart = loc.includes(' <') ? loc.slice(0, loc.indexOf(' <')) : loc;
424
+ const hm = /^(.+):(\d+):(\d+)$/.exec(expPart);
425
+ if (!hm)
426
+ throw new Refusal(o.reportFile, `unexpected clang -dump-tokens location format: ${loc.slice(0, 120)}`);
427
+ const expFile = hm[1];
428
+ const expLine = hm[2];
429
+ const expCol = hm[3];
430
+ if (o.userFiles && o.basename && !expFile.startsWith('<')) {
431
+ const expReal = o.mapFile ? o.mapFile(expFile) : (o.realPath ? o.realPath(expFile) : expFile);
432
+ if (o.userFiles.has(expReal)) {
433
+ if (loc.includes('<Spelling=<scratch space>:')) {
434
+ throw new Refusal(`${o.basename(expReal)}:${expLine}:${expCol}`, 'invocation-dependent or synthesized macro expansion (<scratch space>) in user code is outside the C safety subset');
435
+ }
436
+ if (text.startsWith('__builtin_') && !ALLOWED_BUILTINS.has(text)) {
437
+ throw new Refusal(`${o.basename(expReal)}:${expLine}:${expCol}`, `compiler builtin ${text} in user code is outside the C safety subset`);
438
+ }
439
+ }
440
+ }
441
+ if (kind !== 'eof' && !o.isSystemExpFile(expFile))
442
+ userToks.push(`${kind}\0${text}`);
443
+ }
444
+ if (o.onHeaders)
445
+ o.onHeaders(headers);
446
+ if (o.verifyHeaders)
447
+ o.verifyHeaders(headers);
448
+ return userToks.join('\u001f');
449
+ }
450
+ // Canonical semantic AST-fact fingerprint for non-system declarations (array extents, constant
451
+ // values, types, field layouts, initializers, enum values), normalized only for Clang's
452
+ // anonymous-tag location strings (`(unnamed struct at <file>:<line>:<col>)`).
453
+ function astFactsOf(tu, isSystemFile) {
454
+ locate(tu);
455
+ const normAnon = (s) => s.replace(/\((unnamed|anonymous)([^()]*?) at [^()]+\)/g, '($1$2 at <loc>)');
456
+ const project = (n) => {
457
+ const out = { kind: n.kind };
458
+ if (n.name !== undefined)
459
+ out.name = n.name;
460
+ if (n.type) {
461
+ out.type = {
462
+ qualType: normAnon(n.type.qualType),
463
+ ...(n.type.desugaredQualType !== undefined ? { desugaredQualType: normAnon(n.type.desugaredQualType) } : {}),
464
+ };
465
+ }
466
+ const argType = n.argType;
467
+ if (argType && typeof argType.qualType === 'string') {
468
+ out.argType = {
469
+ qualType: normAnon(argType.qualType),
470
+ ...(argType.desugaredQualType !== undefined ? { desugaredQualType: normAnon(argType.desugaredQualType) } : {}),
471
+ };
472
+ }
473
+ if (n.value !== undefined)
474
+ out.value = n.value;
475
+ if (n.opcode !== undefined)
476
+ out.opcode = n.opcode;
477
+ if (n.castKind !== undefined)
478
+ out.castKind = n.castKind;
479
+ if (n.isPostfix !== undefined)
480
+ out.isPostfix = n.isPostfix;
481
+ if (n.isBitfield !== undefined)
482
+ out.isBitfield = n.isBitfield;
483
+ if (n.storageClass !== undefined)
484
+ out.storageClass = n.storageClass;
485
+ if (n.inline !== undefined)
486
+ out.inline = n.inline;
487
+ if (n.tagUsed !== undefined)
488
+ out.tagUsed = n.tagUsed;
489
+ if (n.completeDefinition !== undefined)
490
+ out.completeDefinition = n.completeDefinition;
491
+ if (n.referencedDecl) {
492
+ out.referencedDecl = {
493
+ kind: n.referencedDecl.kind,
494
+ name: n.referencedDecl.name,
495
+ ...(n.referencedDecl.type ? { type: normAnon(n.referencedDecl.type.qualType) } : {}),
496
+ };
497
+ }
498
+ if (n.array_filler) {
499
+ out.array_filler = Array.isArray(n.array_filler) ? n.array_filler.map(project) : project(n.array_filler);
500
+ }
501
+ if (n.inner?.length)
502
+ out.inner = n.inner.map(project);
503
+ return out;
504
+ };
505
+ const decls = [];
506
+ for (const d of tu.inner ?? []) {
507
+ const f = d.$at?.file;
508
+ if (!f)
509
+ continue;
510
+ const sys = isSystemFile(f) && (!d.$files || [...d.$files].every(sf => isSystemFile(sf)));
511
+ if (!sys)
512
+ decls.push(project(d));
513
+ }
514
+ return JSON.stringify(decls);
515
+ }
516
+ const ALLOWED_SAFETY_STDS = /^(?:(?:c|gnu)(?:89|90|99|11|17|18|23|2x)|iso9899:(?:1990|199409|1999|2011|2017|2018|2024))$/;
517
+ // Closed-world compiler flag allowlist for C safety mode: normalizes two-argument forms
518
+ // (`-I dir`, `-D X=1`, `-U X`), refuses newlines/control chars inside flags, and refuses any flag
519
+ // outside `-I`, `-D`, `-U`, `-std=<C-std>`, `-O*`, and `-W*`/`-w`/`-pedantic*`.
520
+ function validateSafetyFlags(flags, file) {
521
+ const hasCtrl = (s) => s.includes('\n') || s.includes('\r') || s.includes('\0');
522
+ const out = [];
523
+ for (let i = 0; i < flags.length; i++) {
524
+ const f = flags[i];
525
+ if (hasCtrl(f))
526
+ throw new Refusal(file, 'compiler flag containing newline or control character is outside the C safety subset');
527
+ if (f === '-I') {
528
+ const v = flags[++i];
529
+ if (!v || hasCtrl(v) || v.startsWith('=') || v === '-')
530
+ throw new Refusal(file, `missing or invalid argument to -I flag (${v ?? '(missing)'}) in C safety mode`);
531
+ out.push(`-I${v}`);
532
+ }
533
+ else if (f.startsWith('-I') && f.length > 2) {
534
+ const v = f.slice(2);
535
+ if (v.startsWith('=') || v === '-')
536
+ throw new Refusal(file, `sysroot/split include flag ${f} is outside the C safety subset`);
537
+ out.push(f);
538
+ }
539
+ else if (f === '-D') {
540
+ const v = flags[++i];
541
+ if (!v || hasCtrl(v) || !/^[A-Za-z_]\w*(?:=[\s\S]*)?$/.test(v))
542
+ throw new Refusal(file, `malformed -D flag argument ${v ?? '(missing)'} in C safety mode`);
543
+ out.push(`-D${v}`);
544
+ }
545
+ else if (f.startsWith('-D') && f.length > 2) {
546
+ const v = f.slice(2);
547
+ if (!/^[A-Za-z_]\w*(?:=[\s\S]*)?$/.test(v))
548
+ throw new Refusal(file, `malformed -D flag ${f} in C safety mode`);
549
+ out.push(f);
550
+ }
551
+ else if (f === '-U') {
552
+ const v = flags[++i];
553
+ if (!v || hasCtrl(v) || !/^[A-Za-z_]\w*$/.test(v))
554
+ throw new Refusal(file, `malformed -U flag argument ${v ?? '(missing)'} in C safety mode`);
555
+ out.push(`-U${v}`);
556
+ }
557
+ else if (f.startsWith('-U') && f.length > 2) {
558
+ const v = f.slice(2);
559
+ if (!/^[A-Za-z_]\w*$/.test(v))
560
+ throw new Refusal(file, `malformed -U flag ${f} in C safety mode`);
561
+ out.push(f);
562
+ }
563
+ else if (f.startsWith('-std=')) {
564
+ const std = f.slice(5);
565
+ if (!ALLOWED_SAFETY_STDS.test(std))
566
+ throw new Refusal(file, `compiler flag ${f} is outside the C safety subset`);
567
+ out.push(f);
568
+ }
569
+ else if (/^-O[0123sgz]?$/.test(f) || f === '-w' || /^-W[A-Za-z0-9_=-]*$/.test(f) || f === '-pedantic' || f === '-pedantic-errors') {
570
+ out.push(f);
571
+ }
572
+ else {
573
+ throw new Refusal(file, `compiler flag ${f} is outside the C safety subset (only -I, -D, -U, -std=, -O*, and -W* flags are allowed)`);
574
+ }
575
+ }
576
+ return out;
577
+ }
578
+ function detectLibc(activeClang, lang, stdFlags, targetTriple, clangEnv) {
579
+ const cp = node('node:child_process');
580
+ const r = cp.spawnSync(activeClang, [...lang, ...stdFlags, '-dM', '-E', '-'], clangRunOpts({
581
+ encoding: 'utf8',
582
+ input: '#include <stdint.h>\n#include <limits.h>\n',
583
+ maxBuffer: 1 << 24,
584
+ stdio: ['pipe', 'pipe', 'pipe'],
585
+ env: clangEnv,
586
+ }));
587
+ const out = r.status === 0 ? (r.stdout ?? '') : '';
588
+ const get = (k) => new RegExp(`^#define\\s+${k}\\s+(\\S+)`, 'm').exec(out)?.[1];
589
+ const glibc = get('__GLIBC__');
590
+ if (glibc) {
591
+ const minor = get('__GLIBC_MINOR__');
592
+ return minor ? `glibc ${glibc}.${minor}` : `glibc ${glibc}`;
593
+ }
594
+ const uclibc = get('__UCLIBC_MAJOR__');
595
+ if (uclibc) {
596
+ const minor = get('__UCLIBC_MINOR__');
597
+ return minor ? `uClibc ${uclibc}.${minor}` : `uClibc ${uclibc}`;
598
+ }
599
+ if (/^#define\s+__BIONIC__\b/m.test(out))
600
+ return 'bionic';
601
+ const newlib = get('__NEWLIB__');
602
+ if (newlib) {
603
+ const minor = get('__NEWLIB_MINOR__');
604
+ return minor ? `newlib ${newlib}.${minor}` : `newlib ${newlib}`;
605
+ }
606
+ if (/^#define\s+__APPLE__\b/m.test(out)) {
607
+ const mac = get('__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__');
608
+ return mac ? `apple-libc (macOS ${mac})` : 'apple-libc';
609
+ }
610
+ const fbsd = get('__FreeBSD__');
611
+ if (fbsd)
612
+ return `freebsd-libc ${fbsd}`;
613
+ if (/musl/i.test(targetTriple))
614
+ return 'musl';
615
+ return 'unknown';
616
+ }
617
+ // Closed-world preprocessor and macro audit driven directly by Clang's own raw token stream
618
+ // (`-Xclang -dump-raw-tokens`) — never re-lexing in TypeScript:
619
+ // - Refuses lexer-mode-dependent source outright: any of the 9 C trigraph sequences anywhere,
620
+ // and `'` after a digit unless the effective standard is c23/gnu23.
621
+ // - Refuses invocation-dependent macros (__FILE__, __BASE_FILE__, __FILE_NAME__, __TIMESTAMP__,
622
+ // __DATE__, __TIME__, __COUNTER__, __LINE__, __INCLUDE_LEVEL__), __has_* / _Pragma operators,
623
+ // compiler-predefined macros (from bare `clang -dM -E /dev/null`), and token pasting (## / %:%:)
624
+ // anywhere in user files or -D values.
625
+ // - Restricts directives to a closed allowlist (#include literal, #define, #undef, #if/#elif/
626
+ // #ifdef/#ifndef/#elifdef/#elifndef/#else/#endif, #pragma once only, #error/#warning, empty #).
627
+ // - Restricts every #if/#elif/#ifdef/#ifndef/#elifdef/#elifndef/defined() to reference ONLY macros
628
+ // defined earlier in user files (active per `-E -dD`) or listed in `-D` flags (including
629
+ // transitive macro-body expansion); any predefined or undefined-elsewhere macro is refused with
630
+ // its exact name and line.
631
+ function auditUserPreprocessor(o) {
632
+ const fs = node('node:fs');
633
+ const os = node('node:os');
634
+ const path = node('node:path');
635
+ const isC23 = o.effectiveStd === 'c23' || o.effectiveStd === 'gnu23';
636
+ const predefinedMacros = new Set();
637
+ for (const m of o.bareDefs.matchAll(/^#define\s+([A-Za-z_]\w*)/gm))
638
+ predefinedMacros.add(m[1]);
639
+ const isOp = (name) => PREPROC_OPERATORS.has(name) || name.startsWith('__has_');
640
+ const checkForbiddenName = (name, where, ctx) => {
641
+ if (INVOCATION_DEPENDENT_MACROS.has(name))
642
+ throw new Refusal(where, `invocation-dependent predefined macro ${name} ${ctx}is outside the C safety subset`);
643
+ if (isOp(name))
644
+ throw new Refusal(where, `preprocessor operator ${name} ${ctx}is outside the C safety subset`);
645
+ if (name.startsWith('__builtin_') && !ALLOWED_BUILTINS.has(name))
646
+ throw new Refusal(where, `compiler builtin ${name} ${ctx}is outside the C safety subset`);
647
+ if (predefinedMacros.has(name))
648
+ throw new Refusal(where, `predefined macro ${name} ${ctx}is outside the C safety subset (only macros defined in user files or listed in -D flags are allowed)`);
649
+ };
650
+ const checkRawTrigraphs = (rawText, fileLabel) => {
651
+ const hit = TRIGRAPH_RE.exec(rawText);
652
+ if (hit) {
653
+ const lineNo = rawText.slice(0, hit.index).split('\n').length;
654
+ throw new Refusal(`${fileLabel}:${lineNo}:1`, `trigraph sequence ${hit[0]} in user file is outside the C safety subset`);
655
+ }
656
+ };
657
+ const toLogicalLines = (rawToks, fileLabel) => {
658
+ const lines = [];
659
+ let cur = [];
660
+ let prevRaw;
661
+ let hadSpace = true;
662
+ for (const tok of rawToks) {
663
+ if (tok.kind === 'eof')
664
+ break;
665
+ if (!isC23) {
666
+ if (tok.kind === 'numeric_constant' && tok.text.includes("'"))
667
+ throw new Refusal(`${fileLabel}:${tok.line}:${tok.col}`, "digit separator (') outside C23 mode is outside the C safety subset");
668
+ if (prevRaw?.kind === 'numeric_constant' && tok.text.startsWith("'"))
669
+ throw new Refusal(`${fileLabel}:${tok.line}:${tok.col}`, "digit followed by quote (') outside C23 mode is outside the C safety subset");
670
+ }
671
+ prevRaw = tok;
672
+ if (tok.kind === 'comment') {
673
+ hadSpace = true;
674
+ continue;
675
+ }
676
+ if (tok.kind === 'unknown' && /^[ \t\r\n\f\v]+$/.test(tok.text)) {
677
+ if (tok.text.includes('\n') || tok.text.includes('\r')) {
678
+ if (cur.length) {
679
+ lines.push(cur);
680
+ cur = [];
681
+ }
682
+ }
683
+ hadSpace = true;
684
+ continue;
685
+ }
686
+ if (tok.kind === 'hashhash')
687
+ throw new Refusal(`${fileLabel}:${tok.line}:${tok.col}`, `preprocessor token pasting (${tok.text}) in user file is outside the C safety subset`);
688
+ cur.push({ ...tok, hadSpaceBefore: hadSpace });
689
+ hadSpace = false;
690
+ }
691
+ if (cur.length)
692
+ lines.push(cur);
693
+ return lines;
694
+ };
695
+ // Audit every -D/-U flag using Clang's own raw lexer (never re-lexing in TypeScript);
696
+ // each valued -D is lexed in its own isolated temp file so one flag cannot shift another's lines.
697
+ const cliDefines = new Set();
698
+ const cliMacroBodies = new Map();
699
+ const cliDefSpecs = [];
700
+ for (const f of o.flags) {
701
+ const um = /^-U([A-Za-z_]\w*)$/.exec(f);
702
+ if (um) {
703
+ checkForbiddenName(um[1], '<command line>', 'in -U flag ');
704
+ continue;
705
+ }
706
+ const dm = /^-D([A-Za-z_]\w*)(?:=([\s\S]*))?$/.exec(f);
707
+ if (!dm)
708
+ continue;
709
+ const name = dm[1], val = dm[2];
710
+ checkForbiddenName(name, '<command line>', 'in -D flag ');
711
+ if (val !== undefined)
712
+ checkRawTrigraphs(val, '<command line>');
713
+ cliDefSpecs.push({ name, ...(val !== undefined ? { val } : {}) });
714
+ cliDefines.add(name);
715
+ }
716
+ const valuedDefs = cliDefSpecs.filter(d => d.val !== undefined);
717
+ if (valuedDefs.length) {
718
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gdp-c-safety-defs-'));
719
+ try {
720
+ valuedDefs.forEach((d, idx) => {
721
+ const defFile = path.join(tmpDir, `cli_def_${idx}.c`);
722
+ const content = `${d.val}\n`;
723
+ fs.writeFileSync(defFile, content);
724
+ const rawToks = dumpClangRawTokens(o.activeClang, o.stdFlags, defFile, new TextEncoder().encode(content), o.clangEnv, '<command line>');
725
+ const toks = toLogicalLines(rawToks, '<command line>').flat();
726
+ for (const tok of toks) {
727
+ if (tok.kind === 'raw_identifier')
728
+ checkForbiddenName(tok.text, '<command line>', `in -D${d.name} value `);
729
+ }
730
+ cliMacroBodies.set(d.name, { params: new Set(), tokens: toks });
731
+ });
732
+ }
733
+ finally {
734
+ try {
735
+ fs.rmSync(tmpDir, { recursive: true, force: true });
736
+ }
737
+ catch { /* gone */ }
738
+ }
739
+ }
740
+ const userDefined = new Set();
741
+ const userMacroBodies = new Map();
742
+ const isAllowed = (name) => (userDefined.has(name) || cliDefines.has(name)) && !INVOCATION_DEPENDENT_MACROS.has(name) && !isOp(name) && !predefinedMacros.has(name);
743
+ const checkCondTokens = (tokens, where, params, via) => {
744
+ for (let i = 0; i < tokens.length; i++) {
745
+ const tok = tokens[i];
746
+ if (tok.kind !== 'raw_identifier')
747
+ continue;
748
+ if (tok.text === 'defined') {
749
+ let j = i + 1;
750
+ let hasParen = false;
751
+ if (tokens[j]?.kind === 'l_paren') {
752
+ hasParen = true;
753
+ j++;
754
+ }
755
+ const target = tokens[j];
756
+ if (!target || target.kind !== 'raw_identifier')
757
+ throw new Refusal(where, 'malformed defined(...) in preprocessor conditional (outside the C safety subset)');
758
+ const mname = target.text;
759
+ if (!params.has(mname)) {
760
+ checkForbiddenName(mname, where, 'in preprocessor conditional ');
761
+ if (!isAllowed(mname))
762
+ throw new Refusal(where, `preprocessor conditional references macro ${mname} not defined in user files or -D flags (only macros defined in user files or listed in -D flags are allowed in C safety mode)`);
763
+ }
764
+ i = j;
765
+ if (hasParen && tokens[i + 1]?.kind === 'r_paren')
766
+ i++;
767
+ continue;
768
+ }
769
+ const id = tok.text;
770
+ if (params.has(id))
771
+ continue;
772
+ checkForbiddenName(id, where, 'in preprocessor conditional ');
773
+ if (!isAllowed(id))
774
+ throw new Refusal(where, `preprocessor conditional references macro ${id} not defined in user files or -D flags (only macros defined in user files or listed in -D flags are allowed in C safety mode)`);
775
+ if (!via.has(id)) {
776
+ const body = userMacroBodies.get(id) ?? cliMacroBodies.get(id);
777
+ if (body) {
778
+ const nextVia = new Set(via);
779
+ nextVia.add(id);
780
+ checkCondTokens(body.tokens, where, body.params, nextVia);
781
+ }
782
+ }
783
+ }
784
+ };
785
+ const rawLinesCache = new Map();
786
+ const visited = new Set();
787
+ const walkFile = (uf, depth) => {
788
+ if (depth > 64)
789
+ return;
790
+ visited.add(uf);
791
+ const label = o.basename(uf);
792
+ let logicalLines = rawLinesCache.get(uf);
793
+ if (!logicalLines) {
794
+ const rawBuf = o.readBytes(uf);
795
+ if (rawBuf.includes(0))
796
+ throw new Refusal(`${label}:1:1`, 'NUL byte (0x00) in user file is outside the C safety subset');
797
+ const rawText = new TextDecoder().decode(rawBuf);
798
+ checkRawTrigraphs(rawText, label);
799
+ const rawToks = dumpClangRawTokens(o.activeClang, o.stdFlags, o.diskPath ? o.diskPath(uf) : uf, rawBuf, o.clangEnv, uf);
800
+ logicalLines = toLogicalLines(rawToks, label);
801
+ rawLinesCache.set(uf, logicalLines);
802
+ }
803
+ const incMap = o.includesBeforeLine.get(uf);
804
+ const incLines = incMap ? [...incMap.keys()].sort((a, b) => a - b) : [];
805
+ let incIdx = 0;
806
+ const flushIncludesUpTo = (lineNo) => {
807
+ while (incIdx < incLines.length && incLines[incIdx] <= lineNo) {
808
+ for (const child of incMap.get(incLines[incIdx]) ?? []) {
809
+ if (o.userFiles.has(child))
810
+ walkFile(child, depth + 1);
811
+ }
812
+ incIdx++;
813
+ }
814
+ };
815
+ for (const lineToks of logicalLines) {
816
+ const first = lineToks[0];
817
+ flushIncludesUpTo(first.line);
818
+ if (first.kind === 'hash') {
819
+ if (lineToks.length === 1)
820
+ continue;
821
+ const dirTok = lineToks[1];
822
+ const where = `${label}:${dirTok.line}:${dirTok.col}`;
823
+ if (dirTok.kind !== 'raw_identifier')
824
+ throw new Refusal(where, `#${dirTok.text} directive in user file is outside the C safety subset`);
825
+ const dir = dirTok.text;
826
+ const rest = lineToks.slice(2);
827
+ if (dir === 'include') {
828
+ const isQuoted = rest.length === 1 && rest[0].kind === 'string_literal';
829
+ const isAngled = rest.length >= 3 && rest[0].kind === 'less' && rest[rest.length - 1].kind === 'greater';
830
+ if (!isQuoted && !isAngled)
831
+ throw new Refusal(where, 'computed or non-literal #include directive is outside the C safety subset');
832
+ const rawTarget = isQuoted ? rest[0].text.slice(1, -1) : rest.slice(1, -1).map(t => t.text).join('');
833
+ if (isSpecialVirtualPath(rawTarget) || isSpecialVirtualPath(path.resolve(path.dirname(uf), rawTarget)))
834
+ throw new Refusal(where, `#include ${rest.map(t => t.text).join('')} under /proc, /dev, or /sys is outside the C safety subset`);
835
+ }
836
+ else if (dir === 'pragma') {
837
+ if (!(rest.length === 1 && rest[0].kind === 'raw_identifier' && rest[0].text === 'once')) {
838
+ const fmtRest = rest.map((t, i) => (i > 0 && t.hadSpaceBefore ? ' ' : '') + t.text).join('');
839
+ throw new Refusal(where, `#pragma ${fmtRest || '(empty)'} in user file is outside the C safety subset (only #pragma once is allowed)`);
840
+ }
841
+ }
842
+ else if (dir === 'define') {
843
+ const nameTok = rest[0];
844
+ if (!nameTok || nameTok.kind !== 'raw_identifier')
845
+ throw new Refusal(where, 'malformed #define directive in user file');
846
+ const mname = nameTok.text;
847
+ checkForbiddenName(mname, where, 'in #define ');
848
+ const params = new Set();
849
+ let bodyIdx = 1;
850
+ if (rest[1]?.kind === 'l_paren' && !rest[1].hadSpaceBefore) {
851
+ let j = 2;
852
+ while (j < rest.length && rest[j].kind !== 'r_paren') {
853
+ if (rest[j].kind === 'raw_identifier')
854
+ params.add(rest[j].text);
855
+ else if (rest[j].kind === 'ellipsis')
856
+ params.add('__VA_ARGS__');
857
+ j++;
858
+ }
859
+ if (j >= rest.length)
860
+ throw new Refusal(where, `malformed function-like #define ${mname}`);
861
+ bodyIdx = j + 1;
862
+ }
863
+ const bodyToks = rest.slice(bodyIdx);
864
+ for (const tok of bodyToks) {
865
+ if (tok.kind === 'raw_identifier' && !params.has(tok.text))
866
+ checkForbiddenName(tok.text, `${label}:${tok.line}:${tok.col}`, `in #define ${mname} `);
867
+ }
868
+ if (o.activeUserDefines.has(`${uf}:${first.line}:${mname}`) || o.activeUserDefines.has(`${uf}:${dirTok.line}:${mname}`)) {
869
+ userDefined.add(mname);
870
+ userMacroBodies.set(mname, { params, tokens: bodyToks });
871
+ }
872
+ }
873
+ else if (dir === 'undef') {
874
+ const nameTok = rest[0];
875
+ if (rest.length !== 1 || !nameTok || nameTok.kind !== 'raw_identifier')
876
+ throw new Refusal(where, 'malformed #undef directive in user file');
877
+ const mname = nameTok.text;
878
+ checkForbiddenName(mname, where, 'in #undef ');
879
+ if (o.activeUserUndefs.has(`${uf}:${first.line}:${mname}`) || o.activeUserUndefs.has(`${uf}:${dirTok.line}:${mname}`)) {
880
+ userDefined.delete(mname);
881
+ cliDefines.delete(mname);
882
+ userMacroBodies.delete(mname);
883
+ cliMacroBodies.delete(mname);
884
+ }
885
+ }
886
+ else if (dir === 'ifdef' || dir === 'ifndef' || dir === 'elifdef' || dir === 'elifndef') {
887
+ const nameTok = rest[0];
888
+ if (rest.length !== 1 || !nameTok || nameTok.kind !== 'raw_identifier')
889
+ throw new Refusal(where, `malformed #${dir} directive in user file`);
890
+ const mname = nameTok.text;
891
+ checkForbiddenName(mname, where, `in #${dir} `);
892
+ if (!isAllowed(mname))
893
+ throw new Refusal(where, `preprocessor conditional #${dir} references macro ${mname} not defined in user files or -D flags (only macros defined in user files or listed in -D flags are allowed in C safety mode)`);
894
+ }
895
+ else if (dir === 'if' || dir === 'elif') {
896
+ checkCondTokens(rest, where, new Set(), new Set());
897
+ }
898
+ else if (dir === 'else' || dir === 'endif' || dir === 'error' || dir === 'warning') {
899
+ // Allowed standard directives (inactive #error/#warning are inert; active #error already failed clang).
900
+ }
901
+ else {
902
+ throw new Refusal(where, `#${dir} directive in user file is outside the C safety subset`);
903
+ }
904
+ }
905
+ else {
906
+ for (const tok of lineToks) {
907
+ if (tok.kind !== 'raw_identifier')
908
+ continue;
909
+ checkForbiddenName(tok.text, `${label}:${tok.line}:${tok.col}`, 'in user code ');
910
+ }
911
+ }
912
+ }
913
+ flushIncludesUpTo(Number.POSITIVE_INFINITY);
914
+ };
915
+ walkFile(o.mainReal, 0);
916
+ for (const uf of o.userFiles) {
917
+ if (!visited.has(uf))
918
+ walkFile(uf, 0);
919
+ }
920
+ }
921
+ const activeSnapshotRoots = new Set();
922
+ function unlockAndRemoveSnapshotRoot(rootDir) {
923
+ const fs = node('node:fs');
924
+ const path = node('node:path');
925
+ const walk = (dir) => {
926
+ try {
927
+ fs.chmodSync(dir, 0o700);
928
+ }
929
+ catch { /* gone */ }
930
+ let names;
931
+ try {
932
+ names = fs.readdirSync(dir);
933
+ }
934
+ catch {
935
+ return;
936
+ }
937
+ for (const name of names) {
938
+ const full = path.join(dir, name);
939
+ let lst;
940
+ try {
941
+ lst = fs.lstatSync(full);
942
+ }
943
+ catch {
944
+ continue;
945
+ }
946
+ if (lst.isSymbolicLink())
947
+ continue;
948
+ if (lst.isDirectory())
949
+ walk(full);
950
+ else
951
+ try {
952
+ fs.chmodSync(full, 0o600);
953
+ }
954
+ catch { /* gone */ }
955
+ }
956
+ };
957
+ walk(rootDir);
958
+ try {
959
+ fs.rmSync(rootDir, { recursive: true, force: true });
960
+ }
961
+ catch { /* gone */ }
962
+ }
963
+ // Unlock (chmod u+w) and remove every active read-only C safety snapshot tree (e.g. on SIGINT/SIGTERM).
964
+ export function cleanupCSafetySnapshots() {
965
+ for (const rootDir of [...activeSnapshotRoots]) {
966
+ activeSnapshotRoots.delete(rootDir);
967
+ unlockAndRemoveSnapshotRoot(rootDir);
968
+ }
969
+ }
27
970
  // --- running clang ------------------------------------------------------------------------------------------------------
28
971
  // (C++: only the declarations named after the class, `-ast-dump-filter`: its standard headers' are hundreds of MB;
29
972
  // clang writes them one after another, its locations' state going on from one to the next)
30
- export function clangDump(file, flags, clang = 'clang', cpp = false, filter) {
31
- const cp = node('node:child_process'), lang = cpp ? ['-x', 'c++'] : ['-x', 'c'];
973
+ export function clangDump(file, flags, clang = 'clang', cpp = false, filter, safety = false, root) {
974
+ const cp = node('node:child_process');
975
+ const fs = node('node:fs');
976
+ const path = node('node:path');
977
+ const lang = cpp ? ['-x', 'c++'] : ['-x', 'c'];
978
+ const realPath = (p) => { try {
979
+ return fs.realpathSync(p);
980
+ }
981
+ catch {
982
+ return path.resolve(p);
983
+ } };
984
+ const clangEnv = scrubbedClangEnv();
985
+ const verifiedClang = safety && !cpp ? resolveSafetyClang(clang, file) : undefined;
986
+ const activeClang = verifiedClang?.bin ?? clang;
987
+ const activeFlags = safety && !cpp ? validateSafetyFlags(flags, file) : flags;
988
+ let sanitizeErr = (s) => s;
32
989
  const run = (args) => {
33
990
  try {
34
- return cp.execFileSync(clang, args, { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() });
991
+ return cp.execFileSync(activeClang, args, clangRunOpts({ encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], env: clangEnv }));
35
992
  }
36
993
  catch (e) {
37
994
  const x = e;
38
995
  const stated = statedRefusal(e);
39
996
  if (stated)
40
997
  throw new Refusal(file, stated);
41
- throw new Refusal(file, x.code === 'ENOENT' ? `no ${clang} to run: clang is needed to extract ${cpp ? 'C++' : 'C'}` : `clang doesn't compile it (${String(x.stderr ?? x.message).split('\n').filter(l => /error/.test(l)).slice(0, 3).join(' | ')})`);
998
+ if (isTimeoutErr(e, x.signal))
999
+ throw new Refusal(file, 'clang timed out (possible non-regular file/FIFO or runaway preprocessing; outside the C safety subset)');
1000
+ throw new Refusal(file, x.code === 'ENOENT' ? `no ${activeClang} to run: clang is needed to extract ${cpp ? 'C++' : 'C'}` : `clang doesn't compile it (${sanitizeErr(String(x.stderr ?? x.message).split('\n').filter(l => /error/.test(l)).slice(0, 3).join(' | '))})`);
1001
+ }
1002
+ };
1003
+ const runFull = (args) => {
1004
+ const r = cp.spawnSync(activeClang, args, clangRunOpts({ encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], env: clangEnv }));
1005
+ if (r.error || r.signal) {
1006
+ const x = (r.error ?? {});
1007
+ const stated = r.error ? statedRefusal(r.error) : undefined;
1008
+ if (stated)
1009
+ throw new Refusal(file, stated);
1010
+ if (isTimeoutErr(r.error, r.signal))
1011
+ throw new Refusal(file, 'clang timed out (possible non-regular file/FIFO or runaway preprocessing; outside the C safety subset)');
1012
+ throw new Refusal(file, x.code === 'ENOENT' ? `no ${activeClang} to run: clang is needed to extract ${cpp ? 'C++' : 'C'}` : (x.message ?? String(r.signal)));
1013
+ }
1014
+ if (r.status !== 0)
1015
+ throw new Refusal(file, `clang doesn't compile it (${sanitizeErr(String(r.stderr ?? '').split('\n').filter(l => /error/.test(l)).slice(0, 3).join(' | '))})`);
1016
+ return { stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
1017
+ };
1018
+ const defs = run([...lang, ...activeFlags, '-dM', '-E', '/dev/null']), def = (k) => Number(new RegExp(`#define ${k} (\\d+)`).exec(defs)?.[1] ?? 0);
1019
+ if (!safety || cpp) {
1020
+ const dump = run([...lang, ...activeFlags, '-Xclang', '-ast-dump=json', ...(filter ? ['-Xclang', `-ast-dump-filter=${filter}`] : []), '-fsyntax-only', file]), inner = [], dec = new JSONDecoder();
1021
+ const tu = filter ? { kind: 'TranslationUnitDecl', inner } : JSON.parse(dump);
1022
+ if (filter)
1023
+ for (let i = dump.indexOf('{'); i >= 0; i = dump.indexOf('{', i)) {
1024
+ const [o, e] = dec.decode(dump, i);
1025
+ inner.push(o);
1026
+ i = e;
1027
+ }
1028
+ return { tu, target: { int: def('__SIZEOF_INT__') * 8, long: def('__SIZEOF_LONG__') * 8, short: def('__SIZEOF_SHORT__') * 8, llong: def('__SIZEOF_LONG_LONG__') * 8, charBits: def('__CHAR_BIT__'), charUnsigned: /#define __CHAR_UNSIGNED__/.test(defs) } };
1029
+ }
1030
+ // --- C safety mode: Clang-discovered full closure snapshot (user + system) + closed-world audit -----------------------
1031
+ // (1) Discover the complete include closure from Clang itself (`-E -H`) on the original tree
1032
+ // (no TypeScript include lexer), validate every path component-wise (refusing /proc, /dev,
1033
+ // /sys case-insensitively, -I dirs overlapping system dirs, user-visible includes resolving
1034
+ // into system dirs, and non-regular files/FIFOs), and snapshot ALL user AND system files
1035
+ // once (via O_RDONLY|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW + fstat.isFile()) into a private temp
1036
+ // tree locked read-only (`0o500` dirs, `0o400` files) with `-nostdinc` + mapped `-I` / `-isystem` dirs.
1037
+ // (2) Pass `-H` on EVERY snapshot Clang pass (preprocessor cross-check, AST dump, expanded
1038
+ // tokens, alt-path/cwd/mtime/SOURCE_DATE_EPOCH differentials, and build-mode alternates —
1039
+ // which discover and snapshot any extra variant system headers under `-nostdinc` and never
1040
+ // fall back to live system dirs) and require each include sequence to match the original's.
1041
+ // (3) At the end, walk the snapshot tree to refuse any modified, removed, or added file/dir,
1042
+ // digest snapshot bytes for BOTH user files and system headers, and re-hash BOTH on disk.
1043
+ const fsFull = node('node:fs');
1044
+ const osMod = node('node:os');
1045
+ const pathFull = node('node:path');
1046
+ const cryptoMod = node('node:crypto');
1047
+ const sha256Hex = (d) => cryptoMod.createHash('sha256').update(d).digest('hex');
1048
+ const cwd = globalThis.process?.cwd?.() ?? '/';
1049
+ // Component-wise POSIX symlink walker: NEVER calls path.resolve/normalize before symlinks,
1050
+ // so `L/../n.h` where `L -> /proc/self/cwd/sub` inspects `L` and catches the /proc hop before
1051
+ // processing `..`. Rejects /proc, /dev, /sys case-insensitively at every segment and target.
1052
+ const resolveComponentWise = (rawPath, baseDir, label, allowMissing = false) => {
1053
+ if (isSpecialVirtualPath(rawPath))
1054
+ throw new Refusal(file, `${label} ${rawPath} under /proc, /dev, or /sys is outside the C safety subset`);
1055
+ const stack = [];
1056
+ if (!rawPath.startsWith('/')) {
1057
+ const baseRes = baseDir === '/' ? '/' : resolveComponentWise(baseDir, '/', label, false);
1058
+ for (const s of baseRes.split('/'))
1059
+ if (s.length > 0)
1060
+ stack.push(s);
1061
+ }
1062
+ const queue = rawPath.split('/').filter(s => s.length > 0);
1063
+ let hops = 0;
1064
+ while (queue.length > 0) {
1065
+ const seg = queue.shift();
1066
+ if (seg === '.')
1067
+ continue;
1068
+ if (seg === '..') {
1069
+ if (stack.length > 0)
1070
+ stack.pop();
1071
+ continue;
1072
+ }
1073
+ stack.push(seg);
1074
+ const cur = `/${stack.join('/')}`;
1075
+ if (isSpecialVirtualPath(cur))
1076
+ throw new Refusal(file, `${label} ${rawPath} resolves through /proc, /dev, or /sys (${cur}; outside the C safety subset)`);
1077
+ let lst;
1078
+ try {
1079
+ lst = fsFull.lstatSync(cur);
1080
+ }
1081
+ catch {
1082
+ if (allowMissing)
1083
+ return undefined;
1084
+ throw new Refusal(file, `${label} ${rawPath} is not accessible (outside the C safety subset)`);
1085
+ }
1086
+ if (lst.isSymbolicLink()) {
1087
+ if (++hops > 40)
1088
+ throw new Refusal(file, `${label} ${rawPath} exceeds symlink hop limit (outside the C safety subset)`);
1089
+ const target = fsFull.readlinkSync(cur);
1090
+ if (isSpecialVirtualPath(target))
1091
+ throw new Refusal(file, `${label} ${rawPath} resolves through /proc, /dev, or /sys (${target}; outside the C safety subset)`);
1092
+ stack.pop();
1093
+ if (target.startsWith('/'))
1094
+ stack.length = 0;
1095
+ const tSegs = target.split('/').filter(s => s.length > 0);
1096
+ queue.unshift(...tSegs);
1097
+ }
1098
+ }
1099
+ return `/${stack.join('/')}`;
1100
+ };
1101
+ // Open an already component-wise-resolved path with O_NONBLOCK | O_NOCTTY | O_NOFOLLOW so a
1102
+ // FIFO never hangs and a symlink race fails closed, verify fstatSync(fd).isFile(), and read
1103
+ // the exact bytes once from that open descriptor.
1104
+ const openFlags = fsFull.constants.O_RDONLY | (fsFull.constants.O_NONBLOCK ?? 0) | (fsFull.constants.O_NOCTTY ?? 0) | (fsFull.constants.O_NOFOLLOW ?? 0);
1105
+ const readRegularFileOnce = (resolvedPath, rawLabel, kindLabel) => {
1106
+ if (isSpecialVirtualPath(resolvedPath))
1107
+ throw new Refusal(file, `${kindLabel} ${rawLabel} resolves under /proc, /dev, or /sys (${resolvedPath}; outside the C safety subset)`);
1108
+ let fd;
1109
+ try {
1110
+ fd = fsFull.openSync(resolvedPath, openFlags);
1111
+ }
1112
+ catch {
1113
+ throw new Refusal(file, `${kindLabel} ${rawLabel} is not accessible as a regular file (outside the C safety subset)`);
1114
+ }
1115
+ try {
1116
+ const st = fsFull.fstatSync(fd);
1117
+ if (!st.isFile())
1118
+ throw new Refusal(file, `${kindLabel} ${rawLabel} is not a regular file (outside the C safety subset)`);
1119
+ const raw = fsFull.readFileSync(fd);
1120
+ return Uint8Array.from(raw);
1121
+ }
1122
+ finally {
1123
+ fsFull.closeSync(fd);
42
1124
  }
43
1125
  };
44
- const dump = run([...lang, ...flags, '-Xclang', '-ast-dump=json', ...(filter ? ['-Xclang', `-ast-dump-filter=${filter}`] : []), '-fsyntax-only', file]), inner = [], dec = new JSONDecoder();
45
- const tu = filter ? { kind: 'TranslationUnitDecl', inner } : JSON.parse(dump);
46
- if (filter)
47
- for (let i = dump.indexOf('{'); i >= 0; i = dump.indexOf('{', i)) {
48
- const [o, e] = dec.decode(dump, i);
49
- inner.push(o);
50
- i = e;
51
- }
52
- const defs = run([...lang, ...flags, '-dM', '-E', '/dev/null']), def = (k) => Number(new RegExp(`#define ${k} (\\d+)`).exec(defs)?.[1] ?? 0);
53
- return { tu, target: { int: def('__SIZEOF_INT__') * 8, long: def('__SIZEOF_LONG__') * 8, short: def('__SIZEOF_SHORT__') * 8, llong: def('__SIZEOF_LONG_LONG__') * 8, charUnsigned: /#define __CHAR_UNSIGNED__/.test(defs) } };
1126
+ // Probe Clang's built-in search list & metadata on /dev/null BEFORE touching any user file.
1127
+ const stripUserIncludes = (fsList) => fsList.filter(f => !f.startsWith('-I'));
1128
+ const probeV = runFull([...lang, ...stripUserIncludes(activeFlags), '-E', '-v', '-o', '/dev/null', '/dev/null']);
1129
+ if (/^Configuration file:/m.test(probeV.stderr))
1130
+ throw new Refusal(file, `compiler ${activeClang} loaded an external configuration file (outside the C safety subset)`);
1131
+ const targetTriple = /^Target:\s*(\S+)/m.exec(probeV.stderr)?.[1]?.trim() ?? 'unknown';
1132
+ const compilerMatch = /clang version\s+([^\s(]+)/.exec(probeV.stderr);
1133
+ const compiler = compilerMatch ? `clang ${compilerMatch[1]}` : undefined;
1134
+ const systemDirsOrdered = parseSearchDirs(probeV.stderr, realPath);
1135
+ const systemDirReals = [...new Set(systemDirsOrdered.map(d => d.real))];
1136
+ const isUnderDir = (rp, dir) => {
1137
+ const rel = path.relative(dir, rp);
1138
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
1139
+ };
1140
+ const isSameOrUnderDir = (rp, dir) => rp === dir || isUnderDir(rp, dir);
1141
+ const isUnderSystemDir = (rp) => {
1142
+ if (rp === '<built-in>')
1143
+ return true;
1144
+ if (!rp || rp.startsWith('<'))
1145
+ return false;
1146
+ return systemDirReals.some(dir => isUnderDir(rp, dir));
1147
+ };
1148
+ const isRawUnderSystemDir = (rawNorm) => systemDirsOrdered.some(sd => isUnderDir(rawNorm, sd.raw) || isUnderDir(rawNorm, sd.real));
1149
+ const mainReal = resolveComponentWise(file, cwd, 'source file', false);
1150
+ if (isUnderSystemDir(mainReal))
1151
+ throw new Refusal(file, `source file ${file} resolves inside a system header directory (${mainReal}; outside the C safety subset)`);
1152
+ const mainPreBytes = readRegularFileOnce(mainReal, file, 'source file');
1153
+ const rootReal = root ? resolveComponentWise(root, cwd, 'project root', false) : pathFull.dirname(mainReal);
1154
+ const includeDirMap = new Map(); // raw -I dir -> component-wise resolved dir
1155
+ const includeDirRealPaths = [];
1156
+ for (const f of activeFlags) {
1157
+ if (!f.startsWith('-I') || f.length <= 2)
1158
+ continue;
1159
+ const rawDir = f.slice(2);
1160
+ const rp = resolveComponentWise(rawDir, cwd, 'include directory -I', true);
1161
+ const checkDir = rp ?? path.resolve(cwd, rawDir);
1162
+ if (systemDirReals.some(sd => isSameOrUnderDir(checkDir, sd) || isUnderDir(sd, checkDir)))
1163
+ throw new Refusal(file, `include directory -I${rawDir} (resolved: ${checkDir}) overlaps a system header directory (outside the C safety subset)`);
1164
+ if (rp) {
1165
+ try {
1166
+ if (fsFull.statSync(rp).isDirectory()) {
1167
+ includeDirMap.set(rawDir, rp);
1168
+ includeDirRealPaths.push(rp);
1169
+ }
1170
+ }
1171
+ catch { /* missing */ }
1172
+ }
1173
+ }
1174
+ const allowedUserRoots = [rootReal, ...includeDirRealPaths];
1175
+ // Fast pre-clang FIFO/non-regular guard (never decides snapshot contents — Clang -E -H is the
1176
+ // sole authority for the include closure; this only prevents a FIFO in the source dir or -I dir
1177
+ // from blocking until Clang's per-call timeout fires).
1178
+ const mainPreText = new TextDecoder('utf-8', { fatal: false }).decode(mainPreBytes);
1179
+ for (const scanDir of new Set([pathFull.dirname(mainReal), ...includeDirRealPaths])) {
1180
+ let entries;
1181
+ try {
1182
+ entries = fsFull.readdirSync(scanDir);
1183
+ }
1184
+ catch {
1185
+ continue;
1186
+ }
1187
+ if (entries.length > 4096)
1188
+ continue;
1189
+ for (const name of entries) {
1190
+ if (!mainPreText.includes(name))
1191
+ continue;
1192
+ const full = pathFull.join(scanDir, name);
1193
+ let lst;
1194
+ try {
1195
+ lst = fsFull.lstatSync(full);
1196
+ }
1197
+ catch {
1198
+ continue;
1199
+ }
1200
+ if (!lst.isFile() && !lst.isDirectory() && !lst.isSymbolicLink())
1201
+ throw new Refusal(file, `include ${name} is not a regular file (outside the C safety subset)`);
1202
+ if (lst.isSymbolicLink()) {
1203
+ let st;
1204
+ try {
1205
+ st = fsFull.statSync(full);
1206
+ }
1207
+ catch {
1208
+ continue;
1209
+ }
1210
+ if (!st.isFile() && !st.isDirectory())
1211
+ throw new Refusal(file, `include ${name} is not a regular file (outside the C safety subset)`);
1212
+ }
1213
+ }
1214
+ }
1215
+ // Snapshot tree helpers: track every created directory/file, lock dirs 0o500 & files 0o400
1216
+ // immediately after construction, and walk/verify expected sets + SHA-256 hashes at the end.
1217
+ const trackDir = (targetDir, rootDir, trackedDirs) => {
1218
+ fsFull.mkdirSync(targetDir, { recursive: true });
1219
+ let cur = targetDir;
1220
+ while (true) {
1221
+ trackedDirs.add(cur);
1222
+ if (cur === rootDir)
1223
+ break;
1224
+ const parent = pathFull.dirname(cur);
1225
+ if (parent === cur)
1226
+ break;
1227
+ cur = parent;
1228
+ }
1229
+ };
1230
+ const walkAndVerifyTree = (rootDir, expectedDirs, expectedFiles, lockReadOnly, treeLabel) => {
1231
+ const seenDirs = new Set();
1232
+ const seenFiles = new Set();
1233
+ if (lockReadOnly) {
1234
+ const lockPass = (dir) => {
1235
+ let lst;
1236
+ try {
1237
+ lst = fsFull.lstatSync(dir);
1238
+ }
1239
+ catch {
1240
+ throw new Refusal(file, `${treeLabel} directory ${dir} is not accessible (concurrent tampering detected; outside the C safety subset)`);
1241
+ }
1242
+ if (lst.isSymbolicLink() || !lst.isDirectory())
1243
+ throw new Refusal(file, `${treeLabel} path ${dir} is not a real directory (concurrent tampering detected; outside the C safety subset)`);
1244
+ if (!expectedDirs.has(dir))
1245
+ throw new Refusal(file, `unexpected directory ${dir} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1246
+ for (const name of fsFull.readdirSync(dir)) {
1247
+ const full = pathFull.join(dir, name);
1248
+ let cl;
1249
+ try {
1250
+ cl = fsFull.lstatSync(full);
1251
+ }
1252
+ catch {
1253
+ throw new Refusal(file, `${treeLabel} entry ${full} disappeared during verification (concurrent tampering detected; outside the C safety subset)`);
1254
+ }
1255
+ if (cl.isSymbolicLink())
1256
+ throw new Refusal(file, `unexpected symlink ${full} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1257
+ if (cl.isDirectory())
1258
+ lockPass(full);
1259
+ else if (cl.isFile()) {
1260
+ if (!expectedFiles.has(full))
1261
+ throw new Refusal(file, `unexpected file ${full} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1262
+ fsFull.chmodSync(full, 0o400);
1263
+ }
1264
+ else {
1265
+ throw new Refusal(file, `unexpected non-regular entry ${full} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1266
+ }
1267
+ }
1268
+ fsFull.chmodSync(dir, 0o500);
1269
+ };
1270
+ lockPass(rootDir);
1271
+ }
1272
+ const walk = (dir) => {
1273
+ let lst;
1274
+ try {
1275
+ lst = fsFull.lstatSync(dir);
1276
+ }
1277
+ catch {
1278
+ throw new Refusal(file, `${treeLabel} directory ${dir} is not accessible (concurrent tampering detected; outside the C safety subset)`);
1279
+ }
1280
+ if (lst.isSymbolicLink() || !lst.isDirectory())
1281
+ throw new Refusal(file, `${treeLabel} path ${dir} is not a real directory (concurrent tampering detected; outside the C safety subset)`);
1282
+ if (!expectedDirs.has(dir))
1283
+ throw new Refusal(file, `unexpected directory ${dir} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1284
+ seenDirs.add(dir);
1285
+ for (const name of fsFull.readdirSync(dir)) {
1286
+ const full = pathFull.join(dir, name);
1287
+ let cl;
1288
+ try {
1289
+ cl = fsFull.lstatSync(full);
1290
+ }
1291
+ catch {
1292
+ throw new Refusal(file, `${treeLabel} entry ${full} disappeared during verification (concurrent tampering detected; outside the C safety subset)`);
1293
+ }
1294
+ if (cl.isSymbolicLink())
1295
+ throw new Refusal(file, `unexpected symlink ${full} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1296
+ if (cl.isDirectory()) {
1297
+ walk(full);
1298
+ }
1299
+ else if (cl.isFile()) {
1300
+ const expectedSha = expectedFiles.get(full);
1301
+ if (!expectedSha)
1302
+ throw new Refusal(file, `unexpected file ${full} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1303
+ seenFiles.add(full);
1304
+ const curBytes = readRegularFileOnce(full, full, treeLabel);
1305
+ if (sha256Hex(curBytes) !== expectedSha)
1306
+ throw new Refusal(file, `${treeLabel} file ${full} was modified during analysis (concurrent tampering detected; outside the C safety subset)`);
1307
+ }
1308
+ else {
1309
+ throw new Refusal(file, `unexpected non-regular entry ${full} in ${treeLabel} (concurrent tampering detected; outside the C safety subset)`);
1310
+ }
1311
+ }
1312
+ };
1313
+ walk(rootDir);
1314
+ if (seenDirs.size !== expectedDirs.size)
1315
+ throw new Refusal(file, `${treeLabel} directory missing during verification (concurrent tampering detected; outside the C safety subset)`);
1316
+ if (seenFiles.size !== expectedFiles.size)
1317
+ throw new Refusal(file, `${treeLabel} file missing during verification (concurrent tampering detected; outside the C safety subset)`);
1318
+ };
1319
+ const mapHeaderSeq = (headers, snapMap, passLabel) => {
1320
+ const seq = [];
1321
+ for (const { depth, raw: rawInc } of headers) {
1322
+ const mapped = snapMap.get(rawInc) ?? snapMap.get(realPath(rawInc));
1323
+ if (!mapped)
1324
+ throw new Refusal(file, `include ${rawInc} on snapshot during ${passLabel} escaped the snapshotted closure (possible concurrent tampering or unmodeled search; outside the C safety subset)`);
1325
+ seq.push(`${depth} ${mapped}`);
1326
+ }
1327
+ return seq;
1328
+ };
1329
+ const assertHeaderSeqEquals = (headers, expectedSeq, snapMap, passLabel) => {
1330
+ const actual = mapHeaderSeq(headers, snapMap, passLabel);
1331
+ if (actual.length !== expectedSeq.length || actual.some((v, idx) => v !== expectedSeq[idx]))
1332
+ throw new Refusal(file, `snapshot include list during ${passLabel} diverged from original tree (possible concurrent modification or include search mismatch; outside the C safety subset)`);
1333
+ return actual;
1334
+ };
1335
+ const ensureDotDotDirs = (rawInc, mapOf, rootDir, trackedDirs) => {
1336
+ if (!rawInc.includes('..'))
1337
+ return;
1338
+ const absRaw = rawInc.startsWith('/') ? rawInc : `${cwd}/${rawInc}`;
1339
+ const segs = absRaw.split('/');
1340
+ let cur = '';
1341
+ for (let k = 0; k < segs.length - 1; k++) {
1342
+ const s = segs[k];
1343
+ if (!s || s === '.')
1344
+ continue;
1345
+ if (s === '..') {
1346
+ cur = pathFull.dirname(cur || '/');
1347
+ continue;
1348
+ }
1349
+ cur = `${cur}/${s}`;
1350
+ if (cur.startsWith('/'))
1351
+ trackDir(mapOf(cur), rootDir, trackedDirs);
1352
+ }
1353
+ };
1354
+ const discoverIncludes = (extraFlags) => {
1355
+ const pp = runFull([...lang, ...activeFlags, ...extraFlags, '-E', '-H', '-o', '/dev/null', file]);
1356
+ const out = [];
1357
+ for (const { depth, raw: rawInc } of parseClangHeaderLines(pp.stderr)) {
1358
+ if (rawInc.includes('\0') || rawInc.includes('\n') || rawInc.includes('\r'))
1359
+ throw new Refusal(file, 'include path containing control characters is outside the C safety subset');
1360
+ const resolved = resolveComponentWise(rawInc, cwd, 'include', false);
1361
+ const rawNorm = path.resolve(cwd, rawInc);
1362
+ const rawIsSys = isRawUnderSystemDir(rawNorm);
1363
+ const resolvedIsSys = isUnderSystemDir(resolved);
1364
+ if (!rawIsSys && resolvedIsSys)
1365
+ throw new Refusal(file, `user-visible include ${rawInc} resolves into system header directory (${resolved}; outside the C safety subset)`);
1366
+ if (rawIsSys && !resolvedIsSys)
1367
+ throw new Refusal(file, `system header ${rawInc} resolves outside system header directories (${resolved}; outside the C safety subset)`);
1368
+ if (!resolvedIsSys && resolved !== mainReal && !allowedUserRoots.some(d => isUnderDir(resolved, d)))
1369
+ throw new Refusal(file, `user include ${rawInc} (resolved: ${resolved}) lies outside project root and listed -I directories (outside the C safety subset)`);
1370
+ out.push({ depth, raw: rawInc, rawNorm, resolved, isSystem: resolvedIsSys });
1371
+ }
1372
+ return out;
1373
+ };
1374
+ const discoveredIncs = discoverIncludes([]);
1375
+ const origIncludeSeq = discoveredIncs.map(d => `${d.depth} ${d.resolved}`);
1376
+ const snapRootRaw = fsFull.mkdtempSync(pathFull.join(osMod.tmpdir(), 'gdp-c-safety-snap-'));
1377
+ activeSnapshotRoots.add(snapRootRaw);
1378
+ const snapRoot = realPath(snapRootRaw);
1379
+ const snapBase = pathFull.join(snapRoot, 'u');
1380
+ const snapOf = (absPath) => pathFull.join(snapBase, absPath.replace(/^\/+/, ''));
1381
+ const snapEntries = new Map();
1382
+ const snapToOrigReal = new Map();
1383
+ const snapExpectedDirs = new Set([snapRoot]);
1384
+ const snapExpectedFiles = new Map();
1385
+ const registerSnapPath = (snapPath, origReal) => {
1386
+ snapToOrigReal.set(snapPath, origReal);
1387
+ const rp = realPath(snapPath);
1388
+ if (rp !== snapPath)
1389
+ snapToOrigReal.set(rp, origReal);
1390
+ };
1391
+ const writeReadOnlySnap = (snapPath, bytes, sha256) => {
1392
+ if (snapExpectedFiles.has(snapPath))
1393
+ return;
1394
+ trackDir(pathFull.dirname(snapPath), snapRoot, snapExpectedDirs);
1395
+ fsFull.writeFileSync(snapPath, bytes, { mode: 0o400 });
1396
+ fsFull.chmodSync(snapPath, 0o400);
1397
+ snapExpectedFiles.set(snapPath, sha256);
1398
+ };
1399
+ const snapshotFileOnce = (origReal, rawLabel, isSystem) => {
1400
+ const existing = snapEntries.get(origReal);
1401
+ if (existing)
1402
+ return existing;
1403
+ const bytes = readRegularFileOnce(origReal, rawLabel, isSystem ? 'system header' : 'include');
1404
+ const sha256 = sha256Hex(bytes);
1405
+ const snapPath = snapOf(origReal);
1406
+ writeReadOnlySnap(snapPath, bytes, sha256);
1407
+ const entry = { origReal, snapPath, bytes, sha256, isSystem };
1408
+ snapEntries.set(origReal, entry);
1409
+ registerSnapPath(snapPath, origReal);
1410
+ return entry;
1411
+ };
1412
+ const materializeAlias = (snapAliasPath, entry) => {
1413
+ if (snapToOrigReal.has(snapAliasPath))
1414
+ return;
1415
+ writeReadOnlySnap(snapAliasPath, entry.bytes, entry.sha256);
1416
+ registerSnapPath(snapAliasPath, entry.origReal);
1417
+ };
1418
+ try {
1419
+ // Step 2: Snapshot EVERY file in the discovered closure (main + all user includes + all
1420
+ // included system headers) once into the private snapshot tree, then lock dirs 0o500 & files 0o400.
1421
+ const mainEntry = snapshotFileOnce(mainReal, file, false);
1422
+ const mainNorm = path.resolve(cwd, file);
1423
+ if (mainNorm !== mainReal)
1424
+ materializeAlias(snapOf(mainNorm), mainEntry);
1425
+ for (const inc of discoveredIncs) {
1426
+ const entry = snapshotFileOnce(inc.resolved, inc.raw, inc.isSystem);
1427
+ ensureDotDotDirs(inc.raw, snapOf, snapRoot, snapExpectedDirs);
1428
+ if (inc.rawNorm !== inc.resolved)
1429
+ materializeAlias(snapOf(inc.rawNorm), entry);
1430
+ }
1431
+ const snapMain = mainEntry.snapPath;
1432
+ // Build snapshot-only compiler flags with `-nostdinc` so Clang CANNOT reach real system or
1433
+ // user directories on disk: map every `-I` dir and every default system dir into snapRoot.
1434
+ const snapSysFlags = [];
1435
+ for (const sd of systemDirsOrdered) {
1436
+ const sDir = snapOf(sd.raw);
1437
+ trackDir(sDir, snapRoot, snapExpectedDirs);
1438
+ if (sd.framework)
1439
+ snapSysFlags.push('-iframework', sDir);
1440
+ else
1441
+ snapSysFlags.push('-isystem', sDir);
1442
+ if (sd.real !== sd.raw)
1443
+ trackDir(snapOf(sd.real), snapRoot, snapExpectedDirs);
1444
+ }
1445
+ const snapUserFlags = [];
1446
+ for (const f of activeFlags) {
1447
+ if (f.startsWith('-I') && f.length > 2) {
1448
+ const rawDir = f.slice(2);
1449
+ const rp = includeDirMap.get(rawDir);
1450
+ if (rp) {
1451
+ const sDir = snapOf(rp);
1452
+ trackDir(sDir, snapRoot, snapExpectedDirs);
1453
+ snapUserFlags.push(`-I${sDir}`);
1454
+ }
1455
+ }
1456
+ else {
1457
+ snapUserFlags.push(f);
1458
+ }
1459
+ }
1460
+ const snapFlags = ['-nostdinc', ...snapUserFlags, ...snapSysFlags];
1461
+ // Seal snapRoot read-only (files 0o400, dirs 0o500) and verify exact initial inventory.
1462
+ walkAndVerifyTree(snapRoot, snapExpectedDirs, snapExpectedFiles, true, 'snapshot');
1463
+ const mapSnapToOrig = (rawPath) => {
1464
+ if (!rawPath || rawPath.startsWith('<'))
1465
+ return rawPath;
1466
+ const direct = snapToOrigReal.get(rawPath);
1467
+ if (direct)
1468
+ return direct;
1469
+ const rp = realPath(rawPath);
1470
+ return snapToOrigReal.get(rp) ?? rp;
1471
+ };
1472
+ const snapPathReplacements = [...snapToOrigReal.entries()].sort((a, b) => b[0].length - a[0].length);
1473
+ const rewriteSnapInStr = (s) => {
1474
+ let out = s;
1475
+ for (const [sp, orig] of snapPathReplacements)
1476
+ if (out.includes(sp))
1477
+ out = out.replaceAll(sp, orig);
1478
+ return out;
1479
+ };
1480
+ sanitizeErr = rewriteSnapInStr;
1481
+ const rewriteLoc = (loc) => {
1482
+ if (!loc)
1483
+ return;
1484
+ if (typeof loc.file === 'string')
1485
+ loc.file = mapSnapToOrig(loc.file);
1486
+ if (typeof loc.presumedFile === 'string')
1487
+ loc.presumedFile = mapSnapToOrig(loc.presumedFile);
1488
+ if (loc.spellingLoc)
1489
+ rewriteLoc(loc.spellingLoc);
1490
+ if (loc.expansionLoc)
1491
+ rewriteLoc(loc.expansionLoc);
1492
+ if (loc.includedFrom && typeof loc.includedFrom === 'object')
1493
+ rewriteLoc(loc.includedFrom);
1494
+ };
1495
+ const rewriteAst = (n) => {
1496
+ rewriteLoc(n.loc);
1497
+ if (n.range) {
1498
+ rewriteLoc(n.range.begin);
1499
+ rewriteLoc(n.range.end);
1500
+ }
1501
+ if (n.type) {
1502
+ n.type.qualType = rewriteSnapInStr(n.type.qualType);
1503
+ if (n.type.desugaredQualType !== undefined)
1504
+ n.type.desugaredQualType = rewriteSnapInStr(n.type.desugaredQualType);
1505
+ }
1506
+ if (n.referencedDecl?.type)
1507
+ n.referencedDecl.type.qualType = rewriteSnapInStr(n.referencedDecl.type.qualType);
1508
+ const argType = n.argType;
1509
+ if (argType) {
1510
+ if (typeof argType.qualType === 'string')
1511
+ argType.qualType = rewriteSnapInStr(argType.qualType);
1512
+ if (typeof argType.desugaredQualType === 'string')
1513
+ argType.desugaredQualType = rewriteSnapInStr(argType.desugaredQualType);
1514
+ }
1515
+ if (n.array_filler) {
1516
+ if (Array.isArray(n.array_filler))
1517
+ for (const c of n.array_filler)
1518
+ rewriteAst(c);
1519
+ else
1520
+ rewriteAst(n.array_filler);
1521
+ }
1522
+ for (const c of n.inner ?? [])
1523
+ rewriteAst(c);
1524
+ };
1525
+ // Step 3: Cross-check `clang -E -H -dD` strictly on the locked snapshot (`-nostdinc`). Every
1526
+ // include MUST stay inside snapRoot, and the mapped include sequence MUST equal the original
1527
+ // tree's sequence exactly (same files, same depths, same order).
1528
+ const ppRes = runFull([...lang, ...snapFlags, '-E', '-H', '-dD', snapMain]);
1529
+ const physicalFiles = new Set([mainReal]);
1530
+ const systemFiles = new Set(['<built-in>']);
1531
+ const userFiles = new Set([mainReal]);
1532
+ const ppHeaders = parseClangHeaderLines(ppRes.stderr);
1533
+ assertHeaderSeqEquals(ppHeaders, origIncludeSeq, snapToOrigReal, 'preprocessor cross-check');
1534
+ for (const { raw: rawInc } of ppHeaders) {
1535
+ const mapped = snapToOrigReal.get(rawInc) ?? snapToOrigReal.get(realPath(rawInc));
1536
+ const entry = mapped ? snapEntries.get(mapped) : undefined;
1537
+ if (!mapped || !entry)
1538
+ throw new Refusal(file, `include ${rawInc} on snapshot has no snapshot entry (outside the C safety subset)`);
1539
+ physicalFiles.add(mapped);
1540
+ if (entry.isSystem)
1541
+ systemFiles.add(mapped);
1542
+ else
1543
+ userFiles.add(mapped);
1544
+ }
1545
+ const isSystemPath = (rawPath) => {
1546
+ if (rawPath === '<built-in>')
1547
+ return true;
1548
+ if (!rawPath || rawPath.startsWith('<'))
1549
+ return false;
1550
+ const mapped = mapSnapToOrig(rawPath);
1551
+ if (mapped === mainReal || userFiles.has(mapped))
1552
+ return false;
1553
+ return systemFiles.has(mapped);
1554
+ };
1555
+ // Step 4: Run Clang AST dump strictly on the locked snapshot WITH `-H`, verify its include
1556
+ // sequence matches the original's exactly, and rewrite snapshot paths back.
1557
+ const astRes = runFull([...lang, ...snapFlags, '-H', '-Xclang', '-ast-dump=json', ...(filter ? ['-Xclang', `-ast-dump-filter=${filter}`] : []), '-fsyntax-only', snapMain]);
1558
+ assertHeaderSeqEquals(parseClangHeaderLines(astRes.stderr), origIncludeSeq, snapToOrigReal, 'AST dump pass');
1559
+ const dump = astRes.stdout, inner = [], dec = new JSONDecoder();
1560
+ const tu = filter ? { kind: 'TranslationUnitDecl', inner } : JSON.parse(dump);
1561
+ if (filter)
1562
+ for (let i = dump.indexOf('{'); i >= 0; i = dump.indexOf('{', i)) {
1563
+ const [o, e] = dec.decode(dump, i);
1564
+ inner.push(o);
1565
+ i = e;
1566
+ }
1567
+ rewriteAst(tu);
1568
+ // Step 5: Audit Clang's linemarkers and extract exact user-file include order + active #define/#undef sites.
1569
+ const stack = [mainReal];
1570
+ const pendingIncludes = [];
1571
+ const includesBeforeLine = new Map();
1572
+ const recordInclude = (parent, beforeLine, child) => {
1573
+ let m = includesBeforeLine.get(parent);
1574
+ if (!m) {
1575
+ m = new Map();
1576
+ includesBeforeLine.set(parent, m);
1577
+ }
1578
+ let arr = m.get(beforeLine);
1579
+ if (!arr) {
1580
+ arr = [];
1581
+ m.set(beforeLine, arr);
1582
+ }
1583
+ arr.push(child);
1584
+ };
1585
+ const activeUserDefines = new Set();
1586
+ const activeUserUndefs = new Set();
1587
+ let curFile = mainReal;
1588
+ let curLine = 1;
1589
+ for (const rawLine of ppRes.stdout.split('\n')) {
1590
+ const lm = /^# (\d+) "((?:[^"\\]|\\.)*)"(.*)$/.exec(rawLine);
1591
+ if (lm) {
1592
+ const lineNum = Number(lm[1]);
1593
+ const rawPath = lm[2].replace(/\\(["\\])/g, '$1');
1594
+ const nums = new Set(lm[3].trim().split(/\s+/).filter(Boolean));
1595
+ curLine = lineNum;
1596
+ if (!rawPath)
1597
+ continue;
1598
+ if (!rawPath.startsWith('<')) {
1599
+ const rp = mapSnapToOrig(rawPath);
1600
+ const sys = isSystemPath(rawPath);
1601
+ if (nums.has('3') && !sys)
1602
+ throw new Refusal(rp, '#pragma GCC system_header or system-header linemarker in non-system file is outside the C safety subset');
1603
+ const prev = stack[stack.length - 1];
1604
+ if (nums.has('1')) {
1605
+ if (!physicalFiles.has(rp))
1606
+ throw new Refusal(prev ?? file, `linemarker references non-included file ${rp} (outside the C safety subset)`);
1607
+ if (prev && userFiles.has(prev) && userFiles.has(rp))
1608
+ pendingIncludes.push({ parent: prev, child: rp });
1609
+ stack.push(rp);
1610
+ }
1611
+ else if (nums.has('2')) {
1612
+ const topEntry = pendingIncludes[pendingIncludes.length - 1];
1613
+ if (topEntry && topEntry.parent === rp && stack[stack.length - 1] === topEntry.child) {
1614
+ pendingIncludes.pop();
1615
+ recordInclude(topEntry.parent, lineNum, topEntry.child);
1616
+ }
1617
+ const idx = stack.lastIndexOf(rp);
1618
+ if (idx >= 0)
1619
+ stack.length = idx + 1;
1620
+ else if (stack.length > 1)
1621
+ stack.pop();
1622
+ }
1623
+ else if (prev && !isSystemPath(prev) && rp !== prev) {
1624
+ throw new Refusal(prev, `#line or linemarker filename change to ${rp} is outside the C safety subset`);
1625
+ }
1626
+ curFile = rp;
1627
+ }
1628
+ else {
1629
+ if (nums.has('1'))
1630
+ stack.push(rawPath);
1631
+ else if (nums.has('2')) {
1632
+ const idx = stack.lastIndexOf(rawPath);
1633
+ if (idx >= 0)
1634
+ stack.length = idx + 1;
1635
+ else if (stack.length > 1)
1636
+ stack.pop();
1637
+ }
1638
+ curFile = rawPath;
1639
+ }
1640
+ continue;
1641
+ }
1642
+ if (userFiles.has(curFile)) {
1643
+ const dm = /^#define\s+([A-Za-z_]\w*)/.exec(rawLine);
1644
+ if (dm)
1645
+ activeUserDefines.add(`${curFile}:${curLine}:${dm[1]}`);
1646
+ else {
1647
+ const um = /^#undef\s+([A-Za-z_]\w*)/.exec(rawLine);
1648
+ if (um)
1649
+ activeUserUndefs.add(`${curFile}:${curLine}:${um[1]}`);
1650
+ }
1651
+ }
1652
+ curLine++;
1653
+ }
1654
+ // Step 6: Audit every user file's preprocessor directives & macros using the snapshot ONLY.
1655
+ const stdFlags = activeFlags.filter(f => f.startsWith('-std='));
1656
+ const hasDefFlags = activeFlags.some(f => f.startsWith('-D') || f.startsWith('-U'));
1657
+ const bareDefs = hasDefFlags ? run([...lang, ...stdFlags, '-dM', '-E', '/dev/null']) : defs;
1658
+ const stdcVersion = /^#define __STDC_VERSION__\s+(\S+)/m.exec(defs)?.[1] ?? 'none';
1659
+ const strictAnsi = /^#define __STRICT_ANSI__(?:\s|$)/m.test(defs);
1660
+ const explicitStd = [...activeFlags].reverse().find(f => f.startsWith('-std='))?.slice(5);
1661
+ const inferredStd = stdcVersion === '202311L' ? (strictAnsi ? 'c23' : 'gnu23')
1662
+ : stdcVersion === '201710L' ? (strictAnsi ? 'c17' : 'gnu17')
1663
+ : stdcVersion === '201112L' ? (strictAnsi ? 'c11' : 'gnu11')
1664
+ : stdcVersion === '199901L' ? (strictAnsi ? 'c99' : 'gnu99')
1665
+ : (strictAnsi ? 'c89' : 'gnu89');
1666
+ const effectiveStd = explicitStd ?? inferredStd;
1667
+ const libc = detectLibc(activeClang, lang, stdFlags, targetTriple, clangEnv);
1668
+ auditUserPreprocessor({
1669
+ activeClang,
1670
+ stdFlags,
1671
+ effectiveStd,
1672
+ clangEnv,
1673
+ mainReal,
1674
+ userFiles,
1675
+ flags: activeFlags,
1676
+ bareDefs,
1677
+ includesBeforeLine,
1678
+ activeUserDefines,
1679
+ activeUserUndefs,
1680
+ readBytes: p => snapEntries.get(p).bytes,
1681
+ diskPath: p => snapEntries.get(p).snapPath,
1682
+ basename: p => path.basename(p),
1683
+ });
1684
+ const ndebugMatch = /^#define NDEBUG(?:\s+(.*))?$/m.exec(defs);
1685
+ const ndebugDefined = !!ndebugMatch;
1686
+ const ndebugVal = ndebugMatch?.[1]?.trim() ?? '';
1687
+ const optimizeDefined = /^#define __OPTIMIZE__(?:\s|$)/m.test(defs);
1688
+ const debugMatch = /^#define DEBUG(?:\s+(.*))?$/m.exec(defs);
1689
+ const debugDefined = !!debugMatch;
1690
+ const debugVal = debugMatch?.[1]?.trim() ?? '';
1691
+ // Step 7: Capture expanded user tokens & folded AST facts strictly from the locked snapshot
1692
+ // WITH `-H` include-list cross-check.
1693
+ const baseTokens = dumpUserExpandedTokens({
1694
+ activeClang,
1695
+ lang,
1696
+ flags: snapFlags,
1697
+ targetFile: snapMain,
1698
+ reportFile: file,
1699
+ isSystemExpFile: isSystemPath,
1700
+ userFiles,
1701
+ mapFile: mapSnapToOrig,
1702
+ basename: p => path.basename(p),
1703
+ clangEnv,
1704
+ verifyHeaders: h => { assertHeaderSeqEquals(h, origIncludeSeq, snapToOrigReal, 'expanded token pass'); },
1705
+ });
1706
+ const baseAstFacts = astFactsOf(tu, isSystemPath);
1707
+ // Step 8: Differential backstop written purely from in-memory snapshot bytes into a locked
1708
+ // private temp tree (`0o500` dirs, `0o400` files, `-nostdinc` + mapped snapshotted system dirs)
1709
+ // across alternate path/basename length, two empty cwds with stdin=/dev/null, two mtimes, and
1710
+ // two SOURCE_DATE_EPOCH days — every pass checks `-H` equality and walks the tree at the end.
1711
+ const altRootRaw = fsFull.mkdtempSync(pathFull.join(osMod.tmpdir(), 'gdp-c-safety-diff-path-check-'));
1712
+ activeSnapshotRoots.add(altRootRaw);
1713
+ const altRoot = realPath(altRootRaw);
1714
+ try {
1715
+ const mirrorOf = (rp) => pathFull.join(altRoot, 'p_extra_len_dir', rp.replace(/^\/+/, ''));
1716
+ const altCwd1 = pathFull.join(altRoot, 'alt_empty_cwd_1');
1717
+ const altCwd2 = pathFull.join(altRoot, 'alt_empty_cwd_two_longer');
1718
+ const altExpectedDirs = new Set([altRoot]);
1719
+ const altExpectedFiles = new Map();
1720
+ const altSnapToOrigReal = new Map(snapToOrigReal);
1721
+ trackDir(altCwd1, altRoot, altExpectedDirs);
1722
+ trackDir(altCwd2, altRoot, altExpectedDirs);
1723
+ const mirroredPaths = [];
1724
+ const writeMirrored = (dst, orig, bytes, sha256) => {
1725
+ if (!altExpectedFiles.has(dst)) {
1726
+ trackDir(pathFull.dirname(dst), altRoot, altExpectedDirs);
1727
+ fsFull.writeFileSync(dst, bytes, { mode: 0o400 });
1728
+ fsFull.chmodSync(dst, 0o400);
1729
+ fsFull.utimesSync(dst, 1700000000, 1700000000);
1730
+ altExpectedFiles.set(dst, sha256);
1731
+ mirroredPaths.push(dst);
1732
+ }
1733
+ altSnapToOrigReal.set(dst, orig);
1734
+ const rp = realPath(dst);
1735
+ if (rp !== dst)
1736
+ altSnapToOrigReal.set(rp, orig);
1737
+ };
1738
+ for (const [sp, orig] of snapToOrigReal) {
1739
+ if (!userFiles.has(orig))
1740
+ continue;
1741
+ const relToBase = path.relative(snapBase, sp);
1742
+ if (!relToBase || relToBase.startsWith('..') || path.isAbsolute(relToBase))
1743
+ continue;
1744
+ const entry = snapEntries.get(orig);
1745
+ writeMirrored(pathFull.join(altRoot, 'p_extra_len_dir', relToBase), orig, entry.bytes, entry.sha256);
1746
+ }
1747
+ for (const uf of userFiles) {
1748
+ const entry = snapEntries.get(uf);
1749
+ writeMirrored(mirrorOf(uf), uf, entry.bytes, entry.sha256);
1750
+ }
1751
+ for (const inc of discoveredIncs) {
1752
+ if (!inc.isSystem)
1753
+ ensureDotDotDirs(inc.raw, mirrorOf, altRoot, altExpectedDirs);
1754
+ }
1755
+ const altMainDir = pathFull.dirname(mirrorOf(mainReal));
1756
+ const altMain = pathFull.join(altMainDir, `gdp_alt_path_${path.basename(mainReal)}`);
1757
+ writeMirrored(altMain, mainReal, mainEntry.bytes, mainEntry.sha256);
1758
+ const altUserFlags = [];
1759
+ for (const f of activeFlags) {
1760
+ if (f.startsWith('-I') && f.length > 2) {
1761
+ const d = includeDirMap.get(f.slice(2));
1762
+ if (d) {
1763
+ const mDir = mirrorOf(d);
1764
+ trackDir(mDir, altRoot, altExpectedDirs);
1765
+ altUserFlags.push(`-I${mDir}`);
1766
+ }
1767
+ }
1768
+ else {
1769
+ altUserFlags.push(f);
1770
+ }
1771
+ }
1772
+ const altFlags = ['-nostdinc', ...altUserFlags, ...snapSysFlags];
1773
+ walkAndVerifyTree(altRoot, altExpectedDirs, altExpectedFiles, true, 'alt-path snapshot');
1774
+ const dumpAltAstFacts = (env, altCwd, passLabel) => {
1775
+ const r = cp.spawnSync(activeClang, [...lang, ...altFlags, '-H', '-Xclang', '-ast-dump=json', '-fsyntax-only', altMain], clangRunOpts({
1776
+ encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], env, cwd: altCwd,
1777
+ }));
1778
+ if (r.error || r.signal || r.status !== 0) {
1779
+ const stated = r.error ? statedRefusal(r.error) : undefined;
1780
+ if (stated)
1781
+ throw new Refusal(file, stated);
1782
+ if (isTimeoutErr(r.error, r.signal))
1783
+ throw new Refusal(file, 'user AST differential invariance check timed out (outside the C safety subset)');
1784
+ throw new Refusal(file, 'user AST failed differential path/cwd/date invariance check (outside the C safety subset)');
1785
+ }
1786
+ assertHeaderSeqEquals(parseClangHeaderLines(r.stderr ?? ''), origIncludeSeq, altSnapToOrigReal, passLabel);
1787
+ return astFactsOf(JSON.parse(r.stdout ?? ''), isSystemPath);
1788
+ };
1789
+ const env1 = scrubbedClangEnv({ SOURCE_DATE_EPOCH: '1000000000' });
1790
+ const altTok1 = dumpUserExpandedTokens({
1791
+ activeClang,
1792
+ lang,
1793
+ flags: altFlags,
1794
+ targetFile: altMain,
1795
+ reportFile: file,
1796
+ isSystemExpFile: isSystemPath,
1797
+ clangEnv: env1,
1798
+ cwd: altCwd1,
1799
+ failMessage: 'preprocessed user code failed differential path/cwd/date invariance check (outside the C safety subset)',
1800
+ verifyHeaders: h => { assertHeaderSeqEquals(h, origIncludeSeq, altSnapToOrigReal, 'alt-path token pass 1'); },
1801
+ });
1802
+ const altFacts1 = dumpAltAstFacts(env1, altCwd1, 'alt-path AST pass 1');
1803
+ for (const mp of mirroredPaths) {
1804
+ try {
1805
+ fsFull.utimesSync(mp, 1700172837, 1700172837);
1806
+ }
1807
+ catch {
1808
+ fsFull.chmodSync(mp, 0o600);
1809
+ fsFull.utimesSync(mp, 1700172837, 1700172837);
1810
+ fsFull.chmodSync(mp, 0o400);
1811
+ }
1812
+ }
1813
+ const env2 = scrubbedClangEnv({ SOURCE_DATE_EPOCH: '1000172837' });
1814
+ const altTok2 = dumpUserExpandedTokens({
1815
+ activeClang,
1816
+ lang,
1817
+ flags: altFlags,
1818
+ targetFile: altMain,
1819
+ reportFile: file,
1820
+ isSystemExpFile: isSystemPath,
1821
+ clangEnv: env2,
1822
+ cwd: altCwd2,
1823
+ failMessage: 'preprocessed user code failed differential path/cwd/date invariance check (outside the C safety subset)',
1824
+ verifyHeaders: h => { assertHeaderSeqEquals(h, origIncludeSeq, altSnapToOrigReal, 'alt-path token pass 2'); },
1825
+ });
1826
+ const altFacts2 = dumpAltAstFacts(env2, altCwd2, 'alt-path AST pass 2');
1827
+ walkAndVerifyTree(altRoot, altExpectedDirs, altExpectedFiles, false, 'alt-path snapshot');
1828
+ if (altTok1 !== baseTokens || altTok2 !== baseTokens || altTok1 !== altTok2)
1829
+ throw new Refusal(file, 'preprocessed user code depends on invocation path, cwd, stdin, or date/time (differs under alternate path, cwd, mtime, or SOURCE_DATE_EPOCH; outside the C safety subset)');
1830
+ if (altFacts1 !== baseAstFacts || altFacts2 !== baseAstFacts || altFacts1 !== altFacts2)
1831
+ throw new Refusal(file, 'folded AST facts (types, array extents, or constants) depend on invocation path, cwd, stdin, or date/time (differs under alternate path, cwd, mtime, or SOURCE_DATE_EPOCH; outside the C safety subset)');
1832
+ }
1833
+ finally {
1834
+ activeSnapshotRoots.delete(altRootRaw);
1835
+ unlockAndRemoveSnapshotRoot(altRootRaw);
1836
+ }
1837
+ // Step 9: Build-mode differential alternates strictly under `-nostdinc` (NEVER falling back to
1838
+ // live system directories) with `-H` include-list cross-check on every pass. If a build-mode
1839
+ // variant requires a different transitive system-header closure (e.g. `-O2` glibc pulling
1840
+ // `bits/stdlib-bsearch.h` or `-DNDEBUG=1` skipping a sub-header), discover that variant's
1841
+ // closure via Clang `-E -H`, require all user & depth-1 includes to match the base closure,
1842
+ // snapshot any extra system headers into a fresh locked (`0o500`/`0o400`) `-nostdinc` snapshot
1843
+ // tree, cross-check `-H`, walk the tree at the end, and include extra system headers in the
1844
+ // final disk re-hash.
1845
+ const alternates = [
1846
+ ...(ndebugDefined ? [{ label: 'NDEBUG', extra: ['-UNDEBUG'] }] : []),
1847
+ ...(!ndebugDefined || ndebugVal !== '0' ? [{ label: 'NDEBUG', extra: ['-DNDEBUG=0'] }] : []),
1848
+ ...(!ndebugDefined || ndebugVal !== '1' ? [{ label: 'NDEBUG', extra: ['-DNDEBUG=1'] }] : []),
1849
+ ...(optimizeDefined ? [{ label: '__OPTIMIZE__', extra: ['-O0'] }] : []),
1850
+ { label: '__OPTIMIZE__', extra: ['-O2'] },
1851
+ { label: '__OPTIMIZE_SIZE__', extra: ['-Os'] },
1852
+ { label: '__SANITIZE_ADDRESS__/__SANITIZE_UNDEFINED__', extra: ['-fsanitize=address,undefined', '-fno-sanitize-ignorelist'] },
1853
+ { label: '__SANITIZE_ADDRESS__/__SANITIZE_UNDEFINED__', extra: ['-D__SANITIZE_ADDRESS__=1', '-D__SANITIZE_UNDEFINED__=1'] },
1854
+ ...(debugDefined ? [{ label: 'DEBUG', extra: ['-UDEBUG'] }] : []),
1855
+ ...(!debugDefined || debugVal !== '0' ? [{ label: 'DEBUG', extra: ['-DDEBUG=0'] }] : []),
1856
+ ...(!debugDefined || debugVal !== '1' ? [{ label: 'DEBUG', extra: ['-DDEBUG=1'] }] : []),
1857
+ ...(!debugDefined || debugVal !== '2' ? [{ label: 'DEBUG', extra: ['-DDEBUG=2'] }] : []),
1858
+ ];
1859
+ const baseUserIncSeq = discoveredIncs.filter(d => !d.isSystem).map(d => `${d.depth} ${d.resolved}`);
1860
+ const baseDepth1IncSeq = discoveredIncs.filter(d => d.depth === '.').map(d => `${d.depth} ${d.resolved}`);
1861
+ const variantSysEntries = new Map();
1862
+ const runBuildModeVariantSnapshot = (alt, baseSucceeded, baseAltTok, baseMappedSeq) => {
1863
+ const altDiscovered = discoverIncludes(alt.extra);
1864
+ const altOrigSeq = altDiscovered.map(d => `${d.depth} ${d.resolved}`);
1865
+ const altUserSeq = altDiscovered.filter(d => !d.isSystem).map(d => `${d.depth} ${d.resolved}`);
1866
+ const altDepth1Seq = altDiscovered.filter(d => d.depth === '.').map(d => `${d.depth} ${d.resolved}`);
1867
+ if (altUserSeq.length !== baseUserIncSeq.length ||
1868
+ altUserSeq.some((v, idx) => v !== baseUserIncSeq[idx]) ||
1869
+ altDepth1Seq.length !== baseDepth1IncSeq.length ||
1870
+ altDepth1Seq.some((v, idx) => v !== baseDepth1IncSeq[idx])) {
1871
+ throw new Refusal(file, `preprocessed user code depends on ${alt.label} (include structure changed under ${alt.extra.join(' ')}; proof only holds for one build-mode configuration)`);
1872
+ }
1873
+ const needsExtraSys = altDiscovered.some(inc => !snapEntries.has(inc.resolved));
1874
+ if (!needsExtraSys && baseSucceeded && baseMappedSeq.length === altOrigSeq.length && baseMappedSeq.every((v, idx) => v === altOrigSeq[idx])) {
1875
+ return baseAltTok;
1876
+ }
1877
+ const varRootRaw = fsFull.mkdtempSync(pathFull.join(osMod.tmpdir(), 'gdp-c-safety-alt-snap-'));
1878
+ activeSnapshotRoots.add(varRootRaw);
1879
+ const varRoot = realPath(varRootRaw);
1880
+ const varBase = pathFull.join(varRoot, 'u');
1881
+ const varOf = (absPath) => pathFull.join(varBase, absPath.replace(/^\/+/, ''));
1882
+ const varExpectedDirs = new Set([varRoot]);
1883
+ const varExpectedFiles = new Map();
1884
+ const varSnapToOrigReal = new Map();
1885
+ const varSysFiles = new Set(['<built-in>', ...systemFiles]);
1886
+ const writeVarFile = (dst, orig, bytes, sha256) => {
1887
+ if (!varExpectedFiles.has(dst)) {
1888
+ trackDir(pathFull.dirname(dst), varRoot, varExpectedDirs);
1889
+ fsFull.writeFileSync(dst, bytes, { mode: 0o400 });
1890
+ fsFull.chmodSync(dst, 0o400);
1891
+ varExpectedFiles.set(dst, sha256);
1892
+ }
1893
+ varSnapToOrigReal.set(dst, orig);
1894
+ const rp = realPath(dst);
1895
+ if (rp !== dst)
1896
+ varSnapToOrigReal.set(rp, orig);
1897
+ };
1898
+ try {
1899
+ // Populate ALL user files strictly from already-snapshotted base bytes (never re-read user files).
1900
+ for (const [sp, orig] of snapToOrigReal) {
1901
+ if (!userFiles.has(orig))
1902
+ continue;
1903
+ const relToBase = path.relative(snapBase, sp);
1904
+ if (!relToBase || relToBase.startsWith('..') || path.isAbsolute(relToBase))
1905
+ continue;
1906
+ const entry = snapEntries.get(orig);
1907
+ writeVarFile(pathFull.join(varBase, relToBase), orig, entry.bytes, entry.sha256);
1908
+ }
1909
+ for (const uf of userFiles) {
1910
+ const entry = snapEntries.get(uf);
1911
+ writeVarFile(varOf(uf), uf, entry.bytes, entry.sha256);
1912
+ }
1913
+ // Populate system headers from base snapshot bytes or read newly discovered system sub-headers once.
1914
+ for (const inc of altDiscovered) {
1915
+ ensureDotDotDirs(inc.raw, varOf, varRoot, varExpectedDirs);
1916
+ if (!inc.isSystem)
1917
+ continue;
1918
+ varSysFiles.add(inc.resolved);
1919
+ const baseEntry = snapEntries.get(inc.resolved);
1920
+ let bytes;
1921
+ let sha256;
1922
+ if (baseEntry) {
1923
+ bytes = baseEntry.bytes;
1924
+ sha256 = baseEntry.sha256;
1925
+ }
1926
+ else {
1927
+ let extraEntry = variantSysEntries.get(inc.resolved);
1928
+ if (!extraEntry) {
1929
+ const b = readRegularFileOnce(inc.resolved, inc.raw, 'variant system header');
1930
+ extraEntry = { origReal: inc.resolved, bytes: b, sha256: sha256Hex(b) };
1931
+ variantSysEntries.set(inc.resolved, extraEntry);
1932
+ }
1933
+ bytes = extraEntry.bytes;
1934
+ sha256 = extraEntry.sha256;
1935
+ }
1936
+ writeVarFile(varOf(inc.resolved), inc.resolved, bytes, sha256);
1937
+ if (inc.rawNorm !== inc.resolved)
1938
+ writeVarFile(varOf(inc.rawNorm), inc.resolved, bytes, sha256);
1939
+ }
1940
+ const varSysFlags = [];
1941
+ for (const sd of systemDirsOrdered) {
1942
+ const sDir = varOf(sd.raw);
1943
+ trackDir(sDir, varRoot, varExpectedDirs);
1944
+ if (sd.framework)
1945
+ varSysFlags.push('-iframework', sDir);
1946
+ else
1947
+ varSysFlags.push('-isystem', sDir);
1948
+ if (sd.real !== sd.raw)
1949
+ trackDir(varOf(sd.real), varRoot, varExpectedDirs);
1950
+ }
1951
+ const varUserFlags = [];
1952
+ for (const f of activeFlags) {
1953
+ if (f.startsWith('-I') && f.length > 2) {
1954
+ const rp = includeDirMap.get(f.slice(2));
1955
+ if (rp) {
1956
+ const sDir = varOf(rp);
1957
+ trackDir(sDir, varRoot, varExpectedDirs);
1958
+ varUserFlags.push(`-I${sDir}`);
1959
+ }
1960
+ }
1961
+ else {
1962
+ varUserFlags.push(f);
1963
+ }
1964
+ }
1965
+ const varFlags = ['-nostdinc', ...varUserFlags, ...varSysFlags, ...alt.extra];
1966
+ const varMain = varOf(mainReal);
1967
+ walkAndVerifyTree(varRoot, varExpectedDirs, varExpectedFiles, true, `build-mode ${alt.label} variant snapshot`);
1968
+ const isVarSystemPath = (rawPath) => {
1969
+ if (rawPath === '<built-in>')
1970
+ return true;
1971
+ if (!rawPath || rawPath.startsWith('<'))
1972
+ return false;
1973
+ const mapped = varSnapToOrigReal.get(rawPath) ?? varSnapToOrigReal.get(realPath(rawPath)) ?? realPath(rawPath);
1974
+ if (mapped === mainReal || userFiles.has(mapped))
1975
+ return false;
1976
+ return varSysFiles.has(mapped);
1977
+ };
1978
+ const tok = dumpUserExpandedTokens({
1979
+ activeClang,
1980
+ lang,
1981
+ flags: varFlags,
1982
+ targetFile: varMain,
1983
+ reportFile: file,
1984
+ isSystemExpFile: isVarSystemPath,
1985
+ clangEnv,
1986
+ failMessage: `preprocessed user code depends on ${alt.label} (preprocessing failed under ${alt.extra.join(' ')}; proof only holds for one build-mode configuration)`,
1987
+ verifyHeaders: h => { assertHeaderSeqEquals(h, altOrigSeq, varSnapToOrigReal, `build-mode ${alt.label} variant snapshot pass`); },
1988
+ });
1989
+ walkAndVerifyTree(varRoot, varExpectedDirs, varExpectedFiles, false, `build-mode ${alt.label} variant snapshot`);
1990
+ return tok;
1991
+ }
1992
+ finally {
1993
+ activeSnapshotRoots.delete(varRootRaw);
1994
+ unlockAndRemoveSnapshotRoot(varRootRaw);
1995
+ }
1996
+ };
1997
+ for (const alt of alternates) {
1998
+ let altTok = '';
1999
+ let baseSucceeded = false;
2000
+ let baseHeaders = [];
2001
+ try {
2002
+ altTok = dumpUserExpandedTokens({
2003
+ activeClang,
2004
+ lang,
2005
+ flags: [...snapFlags, ...alt.extra],
2006
+ targetFile: snapMain,
2007
+ reportFile: file,
2008
+ isSystemExpFile: isSystemPath,
2009
+ clangEnv,
2010
+ failMessage: `preprocessed user code depends on ${alt.label} (preprocessing failed under ${alt.extra.join(' ')}; proof only holds for one build-mode configuration)`,
2011
+ onHeaders: h => { baseHeaders = [...h]; },
2012
+ });
2013
+ baseSucceeded = true;
2014
+ }
2015
+ catch (e) {
2016
+ if (!(e instanceof Refusal))
2017
+ throw e;
2018
+ }
2019
+ if (baseSucceeded) {
2020
+ // Hard-refuse immediately if any `-H` include escaped snapToOrigReal (concurrent injection).
2021
+ const baseMappedSeq = mapHeaderSeq(baseHeaders, snapToOrigReal, `build-mode ${alt.label} pass`);
2022
+ if (baseMappedSeq.length !== origIncludeSeq.length || baseMappedSeq.some((v, idx) => v !== origIncludeSeq[idx])) {
2023
+ altTok = runBuildModeVariantSnapshot(alt, true, altTok, baseMappedSeq);
2024
+ }
2025
+ }
2026
+ else {
2027
+ altTok = runBuildModeVariantSnapshot(alt, false, '', []);
2028
+ }
2029
+ if (altTok !== baseTokens)
2030
+ throw new Refusal(file, `preprocessed user code depends on ${alt.label} (differs under ${alt.extra.join(' ')}; proof only holds for one build-mode configuration)`);
2031
+ }
2032
+ // Step 10: Digest the SNAPSHOT bytes of EVERY included file (BOTH user files AND system
2033
+ // headers — zero fresh disk read for digests), walk the entire snapshot tree to refuse any
2034
+ // modified, removed, or unexpectedly added files/directories, and re-hash ALL original user,
2035
+ // system, and build-mode variant system files on disk at the end to refuse concurrent writers.
2036
+ const userFileList = [...userFiles]
2037
+ .filter(p => !p.startsWith('<'))
2038
+ .sort()
2039
+ .map(p => ({ path: p, sha256: snapEntries.get(p).sha256 }));
2040
+ const userFilesSha256 = sha256Hex(userFileList.map(h => `${h.path}\0${h.sha256}\n`).join(''));
2041
+ const systemHeaders = [...systemFiles]
2042
+ .filter(p => !p.startsWith('<'))
2043
+ .sort()
2044
+ .map(p => ({ path: p, sha256: snapEntries.get(p).sha256 }));
2045
+ const systemHeadersSha256 = sha256Hex(systemHeaders.map(h => `${h.path}\0${h.sha256}\n`).join(''));
2046
+ const snapshotBytes = new Map();
2047
+ for (const { path: p } of userFileList)
2048
+ snapshotBytes.set(p, snapEntries.get(p).bytes);
2049
+ // Walk the entire snapshot tree and refuse any file/directory outside the expected set or modified.
2050
+ walkAndVerifyTree(snapRoot, snapExpectedDirs, snapExpectedFiles, false, 'snapshot');
2051
+ const allCheckedFiles = [
2052
+ ...userFileList.map(f => ({ ...f, kind: 'user file' })),
2053
+ ...systemHeaders.map(f => ({ ...f, kind: 'system header' })),
2054
+ ...[...variantSysEntries.values()]
2055
+ .filter(e => !systemFiles.has(e.origReal))
2056
+ .sort((a, b) => a.origReal.localeCompare(b.origReal))
2057
+ .map(e => ({ path: e.origReal, sha256: e.sha256, kind: 'variant system header' })),
2058
+ ];
2059
+ const verifySnapshotUnchanged = () => {
2060
+ for (const { path: origPath, sha256: expectedSha, kind } of allCheckedFiles) {
2061
+ const currentResolved = resolveComponentWise(origPath, '/', kind, false);
2062
+ if (currentResolved !== origPath)
2063
+ throw new Refusal(file, `${kind} ${origPath} path resolution changed on disk during analysis (concurrent modification detected; outside the C safety subset)`);
2064
+ const endBytes = readRegularFileOnce(currentResolved, origPath, kind);
2065
+ if (sha256Hex(endBytes) !== expectedSha)
2066
+ throw new Refusal(file, `${kind} ${origPath} changed on disk during analysis (concurrent modification detected; outside the C safety subset)`);
2067
+ }
2068
+ };
2069
+ verifySnapshotUnchanged();
2070
+ const includeDirs = activeFlags.filter(f => f.startsWith('-I'));
2071
+ const macroConfig = {
2072
+ target: targetTriple,
2073
+ ...(compiler ? { compiler } : {}),
2074
+ compilerPath: activeClang,
2075
+ libc,
2076
+ userFilesSha256,
2077
+ userFiles: userFileList,
2078
+ systemHeadersSha256,
2079
+ systemHeaders,
2080
+ std: effectiveStd,
2081
+ stdcVersion,
2082
+ envScrubbed: true,
2083
+ includeDirs,
2084
+ flags: [...activeFlags],
2085
+ defines: activeFlags.filter(f => f.startsWith('-D') || f.startsWith('-U')),
2086
+ ndebugDefined,
2087
+ optimizeDefined,
2088
+ debugDefined,
2089
+ };
2090
+ const safetyMeta = { systemFiles, userFiles, macroConfig, snapshotBytes, verifySnapshotUnchanged };
2091
+ return { tu, target: { int: def('__SIZEOF_INT__') * 8, long: def('__SIZEOF_LONG__') * 8, short: def('__SIZEOF_SHORT__') * 8, llong: def('__SIZEOF_LONG_LONG__') * 8, charBits: def('__CHAR_BIT__'), charUnsigned: /#define __CHAR_UNSIGNED__/.test(defs), safetyMeta } };
2092
+ }
2093
+ finally {
2094
+ activeSnapshotRoots.delete(snapRootRaw);
2095
+ unlockAndRemoveSnapshotRoot(snapRootRaw);
2096
+ }
54
2097
  }
55
2098
  // The values of names a law reads that the code defines as integer constants (a macro, an enum constant, a constexpr
56
2099
  // variable), folded by clang itself: each the value of an enumerator of a probe that includes the file. A name that
@@ -66,7 +2109,7 @@ export function constantsOf(file, flags, clang, cpp, names) {
66
2109
  fs.writeFileSync(probe, `#include ${JSON.stringify(path.resolve(file))}\n${left.map((n, i) => `enum gdp_k${i}_e ${cpp ? ': long long ' : ''}{ gdp_k${i} = (${n}) };`).join('\n')}\n`);
67
2110
  let dump = '';
68
2111
  try {
69
- dump = cp.execFileSync(clang, [...(cpp ? ['-x', 'c++'] : ['-x', 'c']), ...flags, '-w', '-ferror-limit=0', '-Xclang', '-ast-dump=json', '-Xclang', '-ast-dump-filter=gdp_k', '-fsyntax-only', probe], { encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() });
2112
+ dump = cp.execFileSync(clang, [...(cpp ? ['-x', 'c++'] : ['-x', 'c']), ...flags, '-w', '-ferror-limit=0', '-Xclang', '-ast-dump=json', '-Xclang', '-ast-dump-filter=gdp_k', '-fsyntax-only', probe], clangRunOpts({ encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'], env: scrubbedClangEnv() }));
70
2113
  }
71
2114
  catch (e) {
72
2115
  // (the lines that don't compile: their names left out, the rest tried again)
@@ -119,27 +2162,39 @@ export function flagsFor(file, compileCommands) {
119
2162
  // Where each node is: clang writes a location's file and line only where they change from the last one it wrote, in
120
2163
  // the dump's order (an include's chain, `includedFrom`, doesn't count): read in that order, each node gets its own.
121
2164
  function locate(root) {
122
- let file = '', line = 0;
123
- const at = (l) => {
2165
+ let file = '', line = 0, presumed;
2166
+ const at = (l, files, pairs) => {
124
2167
  if (!l)
125
2168
  return undefined;
126
2169
  if (l.spellingLoc || l.expansionLoc) {
127
- at(l.spellingLoc);
128
- return at(l.expansionLoc);
2170
+ const sp = at(l.spellingLoc, files, pairs), spFile = presumed === '<command line>' ? '<command line>' : file, spLine = line;
2171
+ const ex = at(l.expansionLoc, files, pairs), exFile = presumed === '<command line>' ? '<command line>' : file, exLine = line;
2172
+ if (pairs && spFile && exFile)
2173
+ pairs.push({ spell: spFile, spellLine: spLine, expand: exFile, expandLine: exLine });
2174
+ return ex ?? sp;
129
2175
  }
130
- if (l.file !== undefined)
2176
+ if (l.file !== undefined) {
131
2177
  file = l.file;
2178
+ presumed = l.presumedFile;
2179
+ }
2180
+ else if (l.presumedFile !== undefined)
2181
+ presumed = l.presumedFile;
132
2182
  if (l.line !== undefined)
133
2183
  line = l.line;
2184
+ const effFile = presumed === '<command line>' ? '<command line>' : file;
2185
+ if (effFile && files)
2186
+ files.add(effFile);
134
2187
  return l.offset === undefined ? undefined : { file, line, col: l.col ?? 0, off: l.offset, tok: l.tokLen ?? 0 };
135
2188
  };
136
2189
  const walk = (n) => {
2190
+ const files = new Set();
2191
+ const pairs = [];
137
2192
  for (const k of Object.keys(n)) {
138
2193
  if (k === 'loc')
139
- n.$at = at(n.loc);
2194
+ n.$at = at(n.loc, files, pairs);
140
2195
  else if (k === 'range') {
141
- n.$b = at(n.range.begin);
142
- n.$e = at(n.range.end);
2196
+ n.$b = at(n.range.begin, files, pairs);
2197
+ n.$e = at(n.range.end, files, pairs);
143
2198
  }
144
2199
  // (doc comments, FullComment and its parts, are no code)
145
2200
  // (a for's absent parts are empty objects, kind-less)
@@ -156,6 +2211,10 @@ function locate(root) {
156
2211
  }
157
2212
  }
158
2213
  n.$at ??= n.$b;
2214
+ if (files.size)
2215
+ n.$files = files;
2216
+ if (pairs.length)
2217
+ n.$macroExpansions = pairs;
159
2218
  };
160
2219
  walk(root);
161
2220
  }
@@ -168,31 +2227,65 @@ const FAIL = { abort: 'abort()', __assert_rtn: 'an assertion failing', __assert_
168
2227
  // (`picks`: an overloaded method's arity, the one read: `functions: ['throttle/1']`)
169
2228
  // (leave: globals the rule leaves out, an output the code writes for other code, never read into what it keeps)
170
2229
  // (cut: the file's own functions a call of which the request answers, as another file's)
171
- export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pickNames = [], leave = [], cut = []) {
2230
+ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pickNames = [], leave = [], cut = [], safety = false) {
172
2231
  const path = node('node:path'), fs = node('node:fs');
173
- const main = path.resolve(file), base = path.basename(file), dir = `${path.resolve(root ?? main.replace(/\/[^/]*$/, ''))}/`, srcs = new Map();
2232
+ const realPath = (p) => { try {
2233
+ return fs.realpathSync(p);
2234
+ }
2235
+ catch {
2236
+ return path.resolve(p);
2237
+ } };
2238
+ const main = path.resolve(file), mainReal = realPath(file), base = path.basename(file), dir = `${path.resolve(root ?? main.replace(/\/[^/]*$/, ''))}/`, realDir = `${realPath(root ?? mainReal.replace(/\/[^/]*$/, ''))}/`, srcs = new Map();
174
2239
  locate(tu);
175
- const top = tu.inner ?? [], mine = (n) => n.$at?.file === main || n.$at?.file === file, own = (n) => mine(n) || (!!n.$at?.file && path.resolve(n.$at.file).startsWith(dir));
2240
+ const top = tu.inner ?? [], mine = (n) => n.$at?.file === main || n.$at?.file === mainReal || n.$at?.file === file, own = (n) => mine(n) || (!!n.$at?.file && (path.resolve(n.$at.file).startsWith(dir) || realPath(n.$at.file).startsWith(realDir)));
176
2241
  const refuse = (n, what) => { throw new Refusal(pos(n), what); };
177
2242
  const pos = (n) => (n?.$at && own(n) ? `${path.basename(n.$at.file)}:${n.$at.line}:${n.$at.col}` : base);
178
- const src = (f) => { let s = srcs.get(f); if (s === undefined) {
179
- try {
180
- s = fs.readFileSync(path.resolve(f), 'utf8');
2243
+ const snapBytes = target.safetyMeta?.snapshotBytes;
2244
+ const src = (f) => {
2245
+ let s = srcs.get(f);
2246
+ if (s === undefined) {
2247
+ const sb = snapBytes?.get(f) ?? snapBytes?.get(realPath(f));
2248
+ if (sb)
2249
+ s = new TextDecoder('utf-8', { fatal: false }).decode(sb);
2250
+ else {
2251
+ try {
2252
+ s = fs.readFileSync(path.resolve(f), 'utf8');
2253
+ }
2254
+ catch {
2255
+ s = '';
2256
+ }
2257
+ }
2258
+ srcs.set(f, s);
181
2259
  }
182
- catch {
183
- s = '';
2260
+ return s;
2261
+ };
2262
+ const srcBytesMap = new Map();
2263
+ const sliceBytes = (f, start, end) => {
2264
+ let b = srcBytesMap.get(f);
2265
+ if (b === undefined) {
2266
+ b = snapBytes?.get(f) ?? snapBytes?.get(realPath(f)) ?? new TextEncoder().encode(src(f));
2267
+ srcBytesMap.set(f, b);
184
2268
  }
185
- ;
186
- srcs.set(f, s);
187
- } return s; };
188
- const text = (n) => (n.$b && n.$e && n.$b.file === n.$e.file && own(n) && n.$e.off + n.$e.tok >= n.$b.off ? src(n.$b.file).slice(n.$b.off, n.$e.off + n.$e.tok) || n.kind : n.kind);
2269
+ return new TextDecoder().decode(b.subarray(start, end));
2270
+ };
2271
+ const text = (n) => (n.$b && n.$e && n.$b.file === n.$e.file && own(n) && n.$e.off + n.$e.tok >= n.$b.off ? sliceBytes(n.$b.file, n.$b.off, n.$e.off + n.$e.tok) || n.kind : n.kind);
2272
+ if (safety) {
2273
+ if (cpp)
2274
+ refuse(undefined, 'C++ is outside the checked C safety subset');
2275
+ if (leave.length || cut.length || Object.keys(picks).length)
2276
+ refuse(undefined, 'C safety does not allow erased state or call boundaries');
2277
+ if ((target.charBits ?? 8) !== 8 || target.int !== 32 || target.short !== 16)
2278
+ refuse(undefined, 'unsupported C integer ABI for safety lowering');
2279
+ }
189
2280
  // The declarations: typedefs, records and enums of every file (a header's types are the file's too), the globals.
190
- const typedefs = new Map(), records = new Map(), tags = new Map(), anon = new Map();
2281
+ const typedefs = new Map(), typedefNode = new Map(), records = new Map(), tags = new Map(), anon = new Map();
191
2282
  const members = new Map(), fieldNode = new Map(), enums = new Map(), enumById = new Map(), cxx = [];
192
- const enumConst = new Map(), named = new Map(), globals = new Map(), fields = new Map(), recName = new Map();
2283
+ const enumConst = new Map(), named = new Map(), globals = new Map(), globalByName = new Map(), redeclaredGlobals = new Set(), fields = new Map(), recName = new Map();
193
2284
  const declOf = (n) => n.decl ?? (n.inner ?? []).map(declOf).find(Boolean);
194
2285
  const visitDecl = (n) => {
195
2286
  if (n.kind === 'TypedefDecl' && n.name) {
2287
+ if (n.id)
2288
+ typedefNode.set(n.id, n);
196
2289
  const d = declOf(n);
197
2290
  // (a typedef of an unnamed enum names it: clang 21 spells it `enum state_t`, desugared to the typedef's own name)
198
2291
  const en = d?.kind === 'EnumDecl' ? enumById.get(d.id) : undefined;
@@ -251,8 +2344,22 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
251
2344
  named.set(c.name, named.has(c.name) && named.get(c.name) !== v ? NaN : v);
252
2345
  }
253
2346
  }
254
- else if (n.kind === 'VarDecl')
2347
+ else if (n.kind === 'VarDecl') {
255
2348
  globals.set(n.id, n);
2349
+ if (n.previousDecl) {
2350
+ redeclaredGlobals.add(n.id);
2351
+ redeclaredGlobals.add(String(n.previousDecl));
2352
+ }
2353
+ if (n.name) {
2354
+ const list = globalByName.get(n.name) ?? [];
2355
+ list.push(n);
2356
+ globalByName.set(n.name, list);
2357
+ if (list.length > 1)
2358
+ for (const d of list)
2359
+ if (d.id)
2360
+ redeclaredGlobals.add(d.id);
2361
+ }
2362
+ }
256
2363
  else if (n.kind === 'LinkageSpecDecl' || n.kind === 'NamespaceDecl')
257
2364
  for (const c of n.inner ?? [])
258
2365
  visitDecl(c);
@@ -360,6 +2467,15 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
360
2467
  function tyOf(ty) { return parseT(ty.qualType, ty.desugaredQualType); }
361
2468
  function parseT(s0, desug) {
362
2469
  const s = s0.replace(/\b(const|volatile|restrict|__restrict)\b/g, '').replace(/\s+/g, ' ').replace(/ \*/g, '*').replace(/\*/g, ' *').replace(/\* \*/g, '**').trim();
2470
+ if (safety && !s.includes('*') && typedefs.has(s)) {
2471
+ const td = typedefs.get(s), underlying = td.desug ?? td.qual;
2472
+ if (!td.rec || /[*[]/.test(underlying)) {
2473
+ const it = T(parseT(underlying));
2474
+ if (it.k === 'int')
2475
+ return intT(s, it.bits, it.signed);
2476
+ return it.k === 'bool' ? boolT : parseT(underlying);
2477
+ }
2478
+ }
363
2479
  if (s === '_Bool' || s === 'bool')
364
2480
  return boolT;
365
2481
  const arr = /^(.*?)\s*\[(\d+)\]$/.exec(s);
@@ -404,7 +2520,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
404
2520
  return recT(tags.get(s.replace(/^(\w+::)+/, '')), s);
405
2521
  const td = typedefs.get(s.replace(/^(struct|union|class) /, ''));
406
2522
  if (td) {
407
- if (td.rec && records.has(td.rec))
2523
+ if (td.rec && !/[*[]/.test(td.desug ?? td.qual) && records.has(td.rec))
408
2524
  return recT(td.rec, s);
409
2525
  const inner = parseT(td.desug ?? td.qual), it = T(inner);
410
2526
  // (an integer type keeps its name: the notes and the harness spell it so)
@@ -530,16 +2646,18 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
530
2646
  continue;
531
2647
  }
532
2648
  const qt = g.type.qualType;
533
- if (/^const /.test(qt) && !writes.has(id))
2649
+ if (!safety && /^const /.test(qt) && !writes.has(id))
2650
+ continue;
2651
+ if (safety && /\bconst\b/.test(qt) && /\[\d+\]/.test(qt) && g.init && !writes.has(id))
534
2652
  continue;
535
2653
  if (/\[\]$/.test(qt.trim()))
536
2654
  refuse(g, `${g.name}: an array of unknown size (its length is another file's)`);
537
- if (!writes.has(id) && (g.storageClass === 'extern' || /\bvolatile\b/.test(qt) || g.storageClass !== 'static'))
2655
+ if (!safety && !writes.has(id) && (g.storageClass === 'extern' || /\bvolatile\b/.test(qt) || g.storageClass !== 'static'))
538
2656
  ginput.add(id);
539
2657
  gfield.set(id, gnodes.length);
540
2658
  gnodes.push(g);
541
2659
  }
542
- if (!gnodes.length)
2660
+ if (!safety && !gnodes.length)
543
2661
  refuse(undefined, `no global of ${base} its functions read or write (the state, when the file keeps it in globals)`);
544
2662
  }
545
2663
  const entryT = entryRec ? recT(entryRec, entry) : gmode ? add(`globals:${entry}`, { k: 'struct', own: true, name: entry, go: 'gdp_G', fields: gnodes.map(g => ({ name: g.name, t: tyOf(g.type), embedded: false })) }) : refuse(undefined, `no ${cpp ? 'class' : 'struct'} ${entry} in ${base}${cpp ? ' (a class template is outside the subset)' : ''}${!cpp && entry !== stem ? ` (a file that keeps its state in globals: name ${stem}, its stem)` : ''}`);
@@ -554,39 +2672,226 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
554
2672
  byValue.set(q.id, v);
555
2673
  return v;
556
2674
  }
557
- const ref = /[^&]&$/.test(q.type.qualType.trim()), t = ref ? parseT(q.type.qualType.trim().slice(0, -1), q.type.desugaredQualType?.trim().replace(/&$/, '')) : tyOf(q.type), pt = ref ? { k: 'ptr', elem: t, go: q.type.qualType } : T(t);
558
- // (C++: a reference to a struct, the caller's object, read as a pointer to it)
559
- if (ref && T(t).k === 'struct') {
560
- const r = add(`ref:${t}`, { k: 'ptr', go: q.type.qualType, elem: t });
561
- byValue.set(q.id, r);
562
- structRefs.add(q.id);
563
- return r;
2675
+ const ref = /[^&]&$/.test(q.type.qualType.trim()), t = ref ? parseT(q.type.qualType.trim().slice(0, -1), q.type.desugaredQualType?.trim().replace(/&$/, '')) : tyOf(q.type), pt = ref ? { k: 'ptr', elem: t, go: q.type.qualType } : T(t);
2676
+ // (C++: a reference to a struct, the caller's object, read as a pointer to it)
2677
+ if (ref && T(t).k === 'struct') {
2678
+ const r = add(`ref:${t}`, { k: 'ptr', go: q.type.qualType, elem: t });
2679
+ byValue.set(q.id, r);
2680
+ structRefs.add(q.id);
2681
+ return r;
2682
+ }
2683
+ if (pt.k !== 'ptr' || !['int', 'bool'].includes(T(pt.elem).k))
2684
+ return tyOf(q.type);
2685
+ if (ref)
2686
+ refs.add(q.id);
2687
+ const e = pt.elem, b = add(`box:${e}`, { k: 'struct', own: true, box: true, name: T(e).go, go: T(e).go, fields: [{ name: 'value', t: e, embedded: false }] }), bp = add(`ptr:${b}`, { k: 'ptr', go: pt.go, elem: b });
2688
+ boxed.set(q.id, bp);
2689
+ return bp;
2690
+ };
2691
+ const THIS = { kind: 'ParmVarDecl', id: 'this', name: 'this', type: { qualType: `${entry} *` } };
2692
+ const recvOf = (f) => { if (gmode)
2693
+ return THIS; if (f.$m)
2694
+ return f.storageClass === 'static' ? undefined : THIS; const p = params(f)[0], t = p ? T(tyOf(p.type)) : undefined; return t?.k === 'ptr' && t.elem === entryT ? p : undefined; };
2695
+ const args0 = (f) => (f.$m || gmode ? params(f) : params(f).slice(recvOf(f) ? 1 : 0));
2696
+ for (const f of [...funcs.values(), ...ctors])
2697
+ for (const q of args0(f))
2698
+ boxOf(q);
2699
+ const strip = (n) => ((['ParenExpr', 'MaterializeTemporaryExpr', 'ExprWithCleanups', 'CXXBindTemporaryExpr', 'CXXDefaultInitExpr'].includes(n.kind) || (n.kind === 'UnaryOperator' && n.opcode === '__extension__') || (CAST.has(n.kind) && ['LValueToRValue', 'NoOp'].includes(n.castKind))) && n.inner?.length ? strip(n.inner[0]) : n);
2700
+ // A default member initializer's use (CXXDefaultInitExpr): clang 19 dumps the initializer inside it, clang 18 and
2701
+ // earlier nothing (nor the field), so a constructor's is given its field's own (an empty one elsewhere is refused).
2702
+ const fillDefault = (n, f) => {
2703
+ if (n.kind === 'CXXDefaultInitExpr' && !n.inner?.length && f?.inner?.length && !f.inner[0].kind.endsWith('Attr'))
2704
+ n.inner = [f.inner[0]];
2705
+ return n;
2706
+ };
2707
+ const at = (n, t) => ({ p: pos(n), t, text: text(n) });
2708
+ // Use the AST node's source range, not the wording or position of an emitted diagnostic.
2709
+ // In safety mode, sites are inventoried before lowering and frozen so lowering cannot silently create or drop sites.
2710
+ const sites = new Map(), locations = new Map();
2711
+ let sitesFrozen = false, activeSites;
2712
+ const siteOf = (n, kind) => {
2713
+ const old = sites.get(n);
2714
+ if (old) {
2715
+ if (old.kind !== kind)
2716
+ refuse(n, `mismatched C safety site kind (${old.kind} vs ${kind})`);
2717
+ if (activeSites && !activeSites.includes(old))
2718
+ activeSites.push(old);
2719
+ return old;
2720
+ }
2721
+ if (sitesFrozen)
2722
+ refuse(n, 'lowering requested an uninventoried C safety site');
2723
+ const start = n.$b ?? refuse(n, 'a checked C operation without a source range');
2724
+ const loc = `${path.basename(start.file)}:${start.line}:${start.col}`;
2725
+ const idx = (locations.get(loc) ?? 0) + 1;
2726
+ locations.set(loc, idx);
2727
+ const site = { where: idx === 1 ? loc : `${loc}#${idx}`, kind };
2728
+ sites.set(n, site);
2729
+ if (activeSites)
2730
+ activeSites.push(site);
2731
+ return site;
2732
+ };
2733
+ const checked = (n, t, op) => {
2734
+ if (!safety || !['+', '-', '*', '/', '%', '&'].includes(op))
2735
+ return {};
2736
+ const kind = op === '/' || op === '%' ? 'division' : op !== '&' && T(t).signed ? 'overflow' : undefined;
2737
+ return { checkedType: t, ...(kind ? { site: siteOf(n, kind) } : {}) };
2738
+ };
2739
+ // Clang's JSON AST emits array_filler as [filler, ...semanticInits] with no inner key when an
2740
+ // InitListExpr has an array filler (partial or designated initializers). Handle both that form
2741
+ // and a separated array_filler + inner form, and refuse unknown/union shapes.
2742
+ const initListChildren = (n) => {
2743
+ if (n.kind !== 'InitListExpr' || 'field' in n)
2744
+ return undefined;
2745
+ const rawFiller = n.array_filler;
2746
+ if (rawFiller === undefined)
2747
+ return { elems: n.inner ?? [] };
2748
+ if (Array.isArray(rawFiller)) {
2749
+ if (!rawFiller.length)
2750
+ return undefined;
2751
+ if (n.inner === undefined)
2752
+ return { filler: rawFiller[0], elems: rawFiller.slice(1) };
2753
+ if (rawFiller.length === 1)
2754
+ return { filler: rawFiller[0], elems: n.inner };
2755
+ return undefined;
2756
+ }
2757
+ if (typeof rawFiller === 'object' && rawFiller !== null && 'kind' in rawFiller && n.inner !== undefined)
2758
+ return { filler: rawFiller, elems: n.inner };
2759
+ return undefined;
2760
+ };
2761
+ const isAllZeroInit = (n0) => {
2762
+ const n = strip(n0);
2763
+ if (n.kind === 'ImplicitValueInitExpr')
2764
+ return true;
2765
+ if (n.kind === 'InitListExpr') {
2766
+ const il = initListChildren(n);
2767
+ if (!il)
2768
+ return false;
2769
+ if (il.filler && strip(il.filler).kind !== 'ImplicitValueInitExpr')
2770
+ return false;
2771
+ return il.elems.every(isAllZeroInit);
2772
+ }
2773
+ return fold(n) === 0;
2774
+ };
2775
+ const fitsIn = (v, t) => {
2776
+ if (t.k === 'bool')
2777
+ return v === 0n || v === 1n;
2778
+ if (t.k !== 'int' || !t.bits || t.bits < 1 || t.bits > 32)
2779
+ return false;
2780
+ const lo = t.signed ? -(1n << BigInt(t.bits - 1)) : 0n;
2781
+ const hi = t.signed ? (1n << BigInt(t.bits - 1)) - 1n : (1n << BigInt(t.bits)) - 1n;
2782
+ return v >= lo && v <= hi;
2783
+ };
2784
+ const exactConstInit = (n0, et) => {
2785
+ const n = strip(n0);
2786
+ if (n.kind === 'ImplicitValueInitExpr')
2787
+ return 0;
2788
+ if (n.kind === 'ConstantExpr' && n.inner?.length === 1)
2789
+ return exactConstInit(n.inner[0], et);
2790
+ if (n.kind === 'ImplicitCastExpr' && n.inner?.length === 1) {
2791
+ if (n.castKind === 'NoOp')
2792
+ return exactConstInit(n.inner[0], et);
2793
+ if (n.castKind === 'IntegralCast') {
2794
+ const ct = n.type ? T(tyOf(n.type)) : undefined;
2795
+ if (!ct)
2796
+ return undefined;
2797
+ const v = exactConstInit(n.inner[0], ct);
2798
+ return v !== undefined && fitsIn(BigInt(v), et) ? v : undefined;
2799
+ }
2800
+ if (n.castKind === 'IntegralToBoolean') {
2801
+ const it = n.inner[0]?.type ? T(tyOf(n.inner[0].type)) : undefined;
2802
+ if (!it)
2803
+ return undefined;
2804
+ const v = exactConstInit(n.inner[0], it);
2805
+ return v === undefined ? undefined : (v === 0 ? 0 : 1);
2806
+ }
2807
+ return undefined;
564
2808
  }
565
- if (pt.k !== 'ptr' || !['int', 'bool'].includes(T(pt.elem).k))
566
- return tyOf(q.type);
567
- if (ref)
568
- refs.add(q.id);
569
- const e = pt.elem, b = add(`box:${e}`, { k: 'struct', own: true, box: true, name: T(e).go, go: T(e).go, fields: [{ name: 'value', t: e, embedded: false }] }), bp = add(`ptr:${b}`, { k: 'ptr', go: pt.go, elem: b });
570
- boxed.set(q.id, bp);
571
- return bp;
2809
+ if (n.kind === 'CXXBoolLiteralExpr')
2810
+ return n.value ? 1 : 0;
2811
+ let v;
2812
+ if (n.kind === 'IntegerLiteral' && n.value !== undefined)
2813
+ v = BigInt(n.value);
2814
+ else if (n.kind === 'UnaryOperator' && (n.opcode === '-' || n.opcode === '+') && n.inner?.length === 1) {
2815
+ const inner = strip(n.inner[0]);
2816
+ if (inner.kind === 'IntegerLiteral' && inner.value !== undefined)
2817
+ v = n.opcode === '-' ? -BigInt(inner.value) : BigInt(inner.value);
2818
+ }
2819
+ if (v === undefined)
2820
+ return undefined;
2821
+ if (n.type && !fitsIn(v, T(tyOf(n.type))))
2822
+ return undefined;
2823
+ if (et.k === 'bool')
2824
+ return v === 0n ? 0 : 1;
2825
+ if (!fitsIn(v, et))
2826
+ return undefined;
2827
+ return Number(v);
572
2828
  };
573
- const THIS = { kind: 'ParmVarDecl', id: 'this', name: 'this', type: { qualType: `${entry} *` } };
574
- const recvOf = (f) => { if (gmode)
575
- return THIS; if (f.$m)
576
- return f.storageClass === 'static' ? undefined : THIS; const p = params(f)[0], t = p ? T(tyOf(p.type)) : undefined; return t?.k === 'ptr' && t.elem === entryT ? p : undefined; };
577
- const args0 = (f) => (f.$m || gmode ? params(f) : params(f).slice(recvOf(f) ? 1 : 0));
578
- for (const f of [...funcs.values(), ...ctors])
579
- for (const q of args0(f))
580
- boxOf(q);
581
- const strip = (n) => ((['ParenExpr', 'MaterializeTemporaryExpr', 'ExprWithCleanups', 'CXXBindTemporaryExpr', 'CXXDefaultInitExpr'].includes(n.kind) || (n.kind === 'UnaryOperator' && n.opcode === '__extension__') || (CAST.has(n.kind) && ['LValueToRValue', 'NoOp'].includes(n.castKind))) && n.inner?.length ? strip(n.inner[0]) : n);
582
- // A default member initializer's use (CXXDefaultInitExpr): clang 19 dumps the initializer inside it, clang 18 and
583
- // earlier nothing (nor the field), so a constructor's is given its field's own (an empty one elsewhere is refused).
584
- const fillDefault = (n, f) => {
585
- if (n.kind === 'CXXDefaultInitExpr' && !n.inner?.length && f?.inner?.length && !f.inner[0].kind.endsWith('Attr'))
586
- n.inner = [f.inner[0]];
587
- return n;
2829
+ const constTableOf = (n) => {
2830
+ const idx = [], nodes = [];
2831
+ let b = n;
2832
+ while (b.kind === 'ArraySubscriptExpr') {
2833
+ nodes.unshift(b);
2834
+ idx.unshift(b.inner[1]);
2835
+ b = strip(b.inner[0]);
2836
+ if (CAST.has(b.kind) && b.castKind === 'ArrayToPointerDecay')
2837
+ b = strip(b.inner[0]);
2838
+ }
2839
+ const d = b.kind === 'DeclRefExpr' ? b.referencedDecl : undefined;
2840
+ if (d?.kind !== 'VarDecl' || !globals.has(d.id))
2841
+ return undefined;
2842
+ const g = globals.get(d.id), qt = g.type?.qualType ?? '';
2843
+ if (!/\bconst\b/.test(qt) || /\b(?:volatile|_Atomic|enum)\b/.test(`${qt} ${g.type?.desugaredQualType ?? ''}`))
2844
+ return undefined;
2845
+ if (g.storageClass !== 'static' || g.tls || !mine(g) || !g.init || g.inner?.length !== 1 || g.inner.some(k => k.kind.endsWith('Attr')))
2846
+ return undefined;
2847
+ if (g.previousDecl || redeclaredGlobals.has(g.id) || (g.name && (globalByName.get(g.name)?.length ?? 0) > 1))
2848
+ return undefined;
2849
+ const dims = [...qt.matchAll(/\[(\d+)\]/g)].map(m => Number(m[1]));
2850
+ if (!dims.length || dims.length !== idx.length || dims.some(k => !Number.isSafeInteger(k) || k <= 0))
2851
+ return undefined;
2852
+ const total = dims.reduce((u, v) => u * v, 1);
2853
+ if (!Number.isSafeInteger(total) || total <= 0 || total > 256)
2854
+ return undefined;
2855
+ const elemT = n.type ? tyOf(n.type) : -1, et = T(elemT);
2856
+ if (!et || et.nullflag || !(et.k === 'bool' || et.k === 'int' && et.bits > 0 && et.bits <= 32))
2857
+ return undefined;
2858
+ const vals = [];
2859
+ const fill = (v, dim) => {
2860
+ if (!v)
2861
+ return false;
2862
+ const s0 = strip(v);
2863
+ if (dim === dims.length) {
2864
+ const k = exactConstInit(s0, et);
2865
+ if (k === undefined)
2866
+ return false;
2867
+ vals.push(k);
2868
+ return true;
2869
+ }
2870
+ if (s0.kind === 'ImplicitValueInitExpr') {
2871
+ const count = dims.slice(dim).reduce((u, w) => u * w, 1);
2872
+ for (let i = 0; i < count; i++)
2873
+ vals.push(0);
2874
+ return true;
2875
+ }
2876
+ const il = initListChildren(s0);
2877
+ if (!il)
2878
+ return false;
2879
+ const { elems, filler } = il;
2880
+ if (elems.length > dims[dim] || elems.some(k => k.kind === 'DesignatedInitExpr' || k.kind === 'DesignatedInitUpdateExpr' || k.kind === 'NoInitExpr'))
2881
+ return false;
2882
+ if (filler && strip(filler).kind !== 'ImplicitValueInitExpr')
2883
+ return false;
2884
+ if (elems.length < dims[dim] && !filler)
2885
+ return false;
2886
+ for (let i = 0; i < dims[dim]; i++)
2887
+ if (!fill(i < elems.length ? elems[i] : filler, dim + 1))
2888
+ return false;
2889
+ return true;
2890
+ };
2891
+ if (!fill(g.inner[0], 0) || vals.length !== total)
2892
+ return undefined;
2893
+ return { g, dims, idx, nodes, vals, elemT };
588
2894
  };
589
- const at = (n, t) => ({ p: pos(n), t, text: text(n) });
590
2895
  const no = (n, why) => ({ e: 'no', ...at(n, -1), why });
591
2896
  const lit = (n, v, t) => ({ e: 'lit', ...at(n, t), c: { int: String(v) } });
592
2897
  const isBoolish = (n0) => {
@@ -647,10 +2952,10 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
647
2952
  return { e: 'bin', ...at(n, boolT), op: n.opcode, x: cond(n.inner[0]), y: guard(() => cond(n.inner[1])) };
648
2953
  if (n.kind === 'UnaryOperator' && n.opcode === '!')
649
2954
  return { e: 'un', ...at(n, boolT), op: '!', x: cond(n.inner[0]) };
650
- const v = (n.kind === 'ImplicitCastExpr' && (n.castKind === 'IntegralToBoolean' || n.castKind === 'PointerToBoolean')) ? n.inner[0] : n, vt = v.type ? tyOf(v.type) : -1;
2955
+ const v = ((n.kind === 'ImplicitCastExpr' || safety && n.kind === 'CStyleCastExpr') && (n.castKind === 'IntegralToBoolean' || n.castKind === 'PointerToBoolean')) ? n.inner[0] : n, vt = v.type ? tyOf(v.type) : -1;
651
2956
  if (vt >= 0 && T(vt).k === 'bool')
652
2957
  return x(v);
653
- const k = fold(v);
2958
+ const k = safety ? undefined : fold(v);
654
2959
  if (k !== undefined)
655
2960
  return { e: 'lit', ...at(n, boolT), c: { bool: k !== 0 } };
656
2961
  if (vt >= 0 && T(vt).k === 'ptr')
@@ -686,42 +2991,6 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
686
2991
  // (a float's value: left out, a value nothing the rule keeps may read; one read into an integer, a condition or a
687
2992
  // comparison is refused there. Its operands are the code's measurements: an assignment or a call of the file's own
688
2993
  // inside it is refused, its effect would be lost.)
689
- // Clang's JSON AST emits array_filler as [filler, ...semanticInits] with no inner key when an
690
- // InitListExpr has an array filler (partial or designated initializers). Handle both that form
691
- // and a separated array_filler + inner form, and refuse unknown/union shapes.
692
- const initListChildren = (n) => {
693
- if (n.kind !== 'InitListExpr' || 'field' in n)
694
- return undefined;
695
- const rawFiller = n.array_filler;
696
- if (rawFiller === undefined)
697
- return { elems: n.inner ?? [] };
698
- if (Array.isArray(rawFiller)) {
699
- if (!rawFiller.length)
700
- return undefined;
701
- if (n.inner === undefined)
702
- return { filler: rawFiller[0], elems: rawFiller.slice(1) };
703
- if (rawFiller.length === 1)
704
- return { filler: rawFiller[0], elems: n.inner };
705
- return undefined;
706
- }
707
- if (typeof rawFiller === 'object' && rawFiller !== null && 'kind' in rawFiller && n.inner !== undefined)
708
- return { filler: rawFiller, elems: n.inner };
709
- return undefined;
710
- };
711
- const isAllZeroInit = (n0) => {
712
- const n = strip(n0);
713
- if (n.kind === 'ImplicitValueInitExpr')
714
- return true;
715
- if (n.kind === 'InitListExpr') {
716
- const il = initListChildren(n);
717
- if (!il)
718
- return false;
719
- if (il.filler && strip(il.filler).kind !== 'ImplicitValueInitExpr')
720
- return false;
721
- return il.elems.every(isAllZeroInit);
722
- }
723
- return fold(n) === 0;
724
- };
725
2994
  // A constant table read at indices (a transition table, a lookup; a const or constexpr array, a class's static one):
726
2995
  // its entry by cases on the indices, each index outside its dimension undefined behavior, the step's failure (checked
727
2996
  // before the statement, so the index must be free of side effects and read where the statement surely reads it).
@@ -811,10 +3080,18 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
811
3080
  return { e: 'opaque', ...a, why: `${text(n)}: left out (leave: an output for other code, never read into the rule)` };
812
3081
  if (t >= 0 && T(t).k === 'float' && !asPlace)
813
3082
  return effects(n) ? no(n, `${text(n)}: a float computed with an effect of the file's own code (floats are left out)`) : { e: 'opaque', ...a, why: `${text(n)}: a float (left out of the rule: a binary fraction that rounds)` };
814
- const k = t >= 0 && T(t).k === 'int' ? fold(n) : undefined;
3083
+ const k = !safety && t >= 0 && T(t).k === 'int' ? fold(n) : undefined;
815
3084
  if (k !== undefined)
816
3085
  return Number.isSafeInteger(k) ? lit(n, k, t) : no(n, `${text(n)}: the constant ${n.kind === 'IntegerLiteral' ? n.value : k} is past 2^53 (the rule's numbers stop there)`);
817
3086
  switch (n.kind) {
3087
+ case 'IntegerLiteral':
3088
+ if (safety)
3089
+ return { e: 'lit', ...a, c: { int: n.value } };
3090
+ break;
3091
+ case 'ConstantExpr':
3092
+ if (safety && kids.length === 1)
3093
+ return x(kids[0]);
3094
+ break;
818
3095
  case 'CXXBoolLiteralExpr': return { e: 'lit', ...a, c: { bool: !!n.value } };
819
3096
  case 'CXXThisExpr': return { e: 'id', ...a, o: 'var', id: 'this', n: 'this' };
820
3097
  case 'CXXNullPtrLiteralExpr': return { e: 'id', ...a, o: 'nil' };
@@ -892,7 +3169,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
892
3169
  const c = cond(n);
893
3170
  return T(t).k === 'bool' ? c : { e: 'ite', ...a, x: c, y: lit(n, 1, t), b: lit(n, 0, t) };
894
3171
  }
895
- if (op === '&') {
3172
+ if (!safety && op === '&') {
896
3173
  // u & (2^k − 1): u's low k bits, u % 2^k for an unsigned u.
897
3174
  const m = fold(r);
898
3175
  // (of a signed x, two's complement: the floor remainder, ((x % 2^k) + 2^k) % 2^k by C's truncating %)
@@ -902,7 +3179,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
902
3179
  }
903
3180
  }
904
3181
  if (ARITH.has(op))
905
- return { e: 'bin', ...a, op: op === '^' ? '^' : op, x: x(l), y: x(r) };
3182
+ return { e: 'bin', ...a, ...checked(n, t, op), op, x: x(l), y: x(r) };
906
3183
  if (op === ',')
907
3184
  return no(n, 'the comma operator');
908
3185
  if (op === '=')
@@ -914,7 +3191,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
914
3191
  if (op === '!')
915
3192
  return T(t).k === 'bool' ? cond(n) : { e: 'ite', ...a, x: cond(n), y: lit(n, 1, t), b: lit(n, 0, t) };
916
3193
  if (op === '-' || op === '+')
917
- return { e: 'un', ...a, op, x: x(kids[0]) };
3194
+ return { e: 'un', ...a, ...checked(n, t, op === '-' ? '-' : ''), op, x: x(kids[0]) };
918
3195
  if (op === '~')
919
3196
  return { e: 'un', ...a, op: '^', x: x(kids[0]) };
920
3197
  if (op === '&')
@@ -949,12 +3226,17 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
949
3226
  return { e: 'comp', ...a, elts: kids.flatMap((k, i) => (k.kind === 'ImplicitValueInitExpr' ? [] : [{ field: tt.fields[i].name, v: x(k) }])) };
950
3227
  }
951
3228
  case 'ArraySubscriptExpr': {
952
- const tb = table(n);
3229
+ if (safety) {
3230
+ const ct = constTableOf(n);
3231
+ if (ct)
3232
+ return { e: 'table', ...a, sites: ct.nodes.map(k => siteOf(k, 'bounds')), dims: ct.dims, vals: ct.vals, indices: ct.idx.map(x) };
3233
+ }
3234
+ const tb = safety ? undefined : table(n);
953
3235
  if (tb)
954
3236
  return tb;
955
3237
  // An index into an array of the state (its decay to a pointer undone); pointer arithmetic is outside.
956
3238
  const b = strip(kids[0]), arr = b.kind === 'ImplicitCastExpr' && b.castKind === 'ArrayToPointerDecay' ? b.inner[0] : undefined;
957
- return arr ? { e: 'index', ...a, x: place(arr), i: x(kids[1]) } : no(n, `${text(n)}: an index into a pointer (pointer arithmetic)`);
3239
+ return arr ? { e: 'index', ...a, ...(safety ? { site: siteOf(n, 'bounds') } : {}), x: place(arr), i: x(kids[1]) } : no(n, `${text(n)}: an index into a pointer (pointer arithmetic)`);
958
3240
  }
959
3241
  case 'StringLiteral': return no(n, `${text(n)}: a string (char arrays are outside the subset)`);
960
3242
  case 'FloatingLiteral': return no(n, `${text(n)}: a float (the subset reads integers)`);
@@ -1150,6 +3432,11 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
1150
3432
  }
1151
3433
  case 'CompoundAssignOperator': {
1152
3434
  const [l, r] = kids, lt = tyOf(l.type), ct = tyOf(n.computeLHSType), op = n.opcode.slice(0, -1);
3435
+ if (safety) {
3436
+ const result = n.computeResultType, ot = result ? tyOf(result) : refuse(n, 'missing C compound-assignment result type');
3437
+ // The validator limits this to scalar places with total, effect-free address computation.
3438
+ return [{ s: 'assign', p, op: '=', l: [place(l)], r: [conv2(n, lt, { e: 'bin', ...at(n, ot), ...checked(n, ot, op), op, x: conv2(l, ot, x(l)), y: conv2(r, ot, x(r)) })] }];
3439
+ }
1153
3440
  const m = op === '&' ? fold(r) : undefined, mask = m !== undefined && m > 0 && Number.isInteger(Math.log2(m + 1)) && T(ct).signed === false;
1154
3441
  const y = mask ? lit(r, m + 1, ct) : x(r), bop = mask ? '%' : op;
1155
3442
  if (ct === lt)
@@ -1165,6 +3452,10 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
1165
3452
  const l = kids[0], lt = tyOf(l.type), tt = T(lt);
1166
3453
  if (tt.k !== 'int')
1167
3454
  return sno(n, `${text(n)}: ${n.opcode} of a ${l.type.qualType}`);
3455
+ if (safety) {
3456
+ const it = tt.bits >= target.int ? lt : intT('int', target.int, true), op = n.opcode[0];
3457
+ return [{ s: 'assign', p, op: '=', l: [place(l)], r: [conv2(n, lt, { e: 'bin', ...at(n, it), ...checked(n, it, op), op, x: conv2(l, it, x(l)), y: lit(n, 1, it) })] }];
3458
+ }
1168
3459
  if (tt.bits >= target.int)
1169
3460
  return [{ s: 'incdec', p, op: n.opcode, x: place(l) }];
1170
3461
  // (a narrow integer is promoted to int, the result converted back)
@@ -1250,9 +3541,741 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
1250
3541
  ...(/\.\.\.\)$/.test(f.type.qualType) ? { params: [{ t: -1, variadic: true }] } : {}),
1251
3542
  static: f.storageClass === 'static', ...(f.virtual ? { why: `${name}: a virtual method (its dispatch)` } : {}) };
1252
3543
  };
3544
+ const validated = new Set(), validatedHelpers = new Set();
3545
+ const methodSites = new Map(), ctorSites = [];
3546
+ // Validate the Clang AST before any lowering can erase a construct. Only pure expressions are admitted;
3547
+ // where C does not order operands, at most one may fault. Assignments may have a faulting lvalue OR RHS.
3548
+ // Inventory every typed safety site during validation and freeze the inventory before lowering.
3549
+ if (safety) {
3550
+ function bad(n, why) { return refuse(n, `${why} (outside the C safety subset)`); }
3551
+ const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/\/\/[^\n]*/g, ' ');
3552
+ const hasMacroLoc = (l) => Boolean(l?.expansionLoc || l?.spellingLoc);
3553
+ const scalar = (n, t = n.type ? tyOf(n.type) : -1) => {
3554
+ const q = T(t), raw = n.type?.desugaredQualType ?? n.type?.qualType ?? '';
3555
+ if (/\b(?:volatile|_Atomic|enum)\b/.test(`${n.type?.qualType ?? ''} ${raw}`) || !q || q.nullflag || !(q.k === 'bool' || q.k === 'int' && q.bits > 0 && q.bits <= 32))
3556
+ bad(n, `unmodeled scalar type ${raw}`);
3557
+ return q;
3558
+ };
3559
+ const validatePointerTypedef = (aliasId, n) => {
3560
+ const seen = new Set();
3561
+ let cur = aliasId;
3562
+ while (cur) {
3563
+ if (seen.has(cur))
3564
+ bad(n, 'cyclic typedef in pointer declarator');
3565
+ seen.add(cur);
3566
+ const td = typedefNode.get(cur);
3567
+ if (!td || td.inner?.some(k => k.kind.endsWith('Attr')) || hasMacroLoc(td.loc))
3568
+ bad(n, 'uninspectable pointer typedef declarator');
3569
+ const raw = `${td.type?.qualType ?? ''} ${td.type?.desugaredQualType ?? ''}`;
3570
+ if (/[[\]()]/.test(raw) || /\b(?:volatile|_Atomic)\b/.test(raw))
3571
+ bad(n, 'adjusted array or variably-modified pointer typedef');
3572
+ cur = td.type?.typeAliasDeclId;
3573
+ }
3574
+ };
3575
+ const validateParamDecl = (q, kind) => {
3576
+ if (!q.id || !q.name || q.name === '_' || q.inner?.some(k => k.kind.endsWith('Attr')))
3577
+ bad(q, 'a parameter with unmodeled binding or attributes');
3578
+ if (!q.$at || !q.$b || !q.$e || !mine(q) || q.$b.file !== main || q.$e.file !== main)
3579
+ bad(q, 'a parameter without inspectable source range in main file');
3580
+ if (hasMacroLoc(q.loc) || hasMacroLoc(q.range?.end))
3581
+ bad(q, 'a macro-expanded parameter declarator');
3582
+ if (hasMacroLoc(q.range?.begin)) {
3583
+ const sp = q.range?.begin?.spellingLoc;
3584
+ const okBool = kind === 'scalar' && q.type?.qualType === 'bool' && !!sp?.file && /(?:^|\/)stdbool\.h$/.test(sp.file);
3585
+ if (!okBool)
3586
+ bad(q, 'a macro-expanded parameter declarator');
3587
+ }
3588
+ if (q.$e.off !== q.$at.off || q.$e.tok !== q.$at.tok)
3589
+ bad(q, 'an adjusted or variably-modified parameter declarator');
3590
+ const rawDecl = stripComments(sliceBytes(main, q.$b.off, q.$e.off + q.$e.tok)).trim();
3591
+ if (!rawDecl || /[[\]()]/.test(rawDecl) || /\b(?:volatile|_Atomic)\b/.test(`${rawDecl} ${q.type?.qualType ?? ''} ${q.type?.desugaredQualType ?? ''}`))
3592
+ bad(q, 'an adjusted, variably-modified, or qualified parameter declarator');
3593
+ if (kind === 'scalar') {
3594
+ if (rawDecl.includes('*'))
3595
+ bad(q, 'a pointer declarator for a scalar parameter');
3596
+ scalar(q);
3597
+ }
3598
+ else {
3599
+ const aliasId = q.type?.typeAliasDeclId;
3600
+ if (aliasId) {
3601
+ validatePointerTypedef(aliasId, q);
3602
+ if (!/^(?:const\s+)?[A-Za-z_]\w*(?:\s+(?:const|restrict|__restrict))*\s+[A-Za-z_]\w*$/.test(rawDecl))
3603
+ bad(q, 'a non-plain pointer-typedef parameter declarator');
3604
+ }
3605
+ else if (!/^(?:const\s+)?(?:(?:struct|signed|unsigned|short|long)\s+)*[A-Za-z_]\w*\s*\*\s*(?:(?:const|restrict|__restrict)\s+)*[A-Za-z_]\w*$/.test(rawDecl)) {
3606
+ bad(q, 'an adjusted or non-plain pointer parameter declarator');
3607
+ }
3608
+ if (kind === 'out') {
3609
+ const pt = T(tyOf(q.type));
3610
+ if (pt.k !== 'ptr')
3611
+ bad(q, 'an out-parameter that is not a pointer');
3612
+ scalar(q, pt.elem);
3613
+ }
3614
+ }
3615
+ };
3616
+ const checkNoRedeclaredGlobal = (g) => {
3617
+ if (g.previousDecl || redeclaredGlobals.has(g.id) || (g.name && (globalByName.get(g.name)?.length ?? 0) > 1))
3618
+ bad(g, `global ${g.name ?? ''} has multiple declarations in its linkage chain`);
3619
+ };
3620
+ const field = (n, receiver) => {
3621
+ const f = fields.get(n.referencedMemberDecl ?? ''), b = n.inner?.[0] && strip(n.inner[0]);
3622
+ if (!f || f.rec !== entryRec || !n.isArrow || b?.kind !== 'DeclRefExpr' || !receiver || b.referencedDecl?.id !== receiver)
3623
+ bad(n, 'a member not directly in the event receiver');
3624
+ };
3625
+ const isOutDeref = (n, outParams) => {
3626
+ if (n.kind !== 'UnaryOperator' || n.opcode !== '*' || !n.inner?.length)
3627
+ return false;
3628
+ const r = strip(n.inner[0]);
3629
+ return r.kind === 'DeclRefExpr' && !!r.referencedDecl?.id && outParams.has(r.referencedDecl.id);
3630
+ };
3631
+ const direct = (n, receiver, outParams, allowArray = false, inInit = false) => {
3632
+ if (n.kind === 'MemberExpr')
3633
+ field(n, receiver);
3634
+ else if (n.kind === 'DeclRefExpr') {
3635
+ const d = n.referencedDecl;
3636
+ if (!d || !['VarDecl', 'ParmVarDecl'].includes(d.kind) || d.id === receiver || outParams.has(d.id) || (globals.has(d.id) && (inInit || !gfield.has(d.id))))
3637
+ bad(n, 'a reference to an unmodeled declaration');
3638
+ }
3639
+ else if (!allowArray && isOutDeref(n, outParams)) {
3640
+ // valid direct scalar out-parameter dereference
3641
+ }
3642
+ else
3643
+ bad(n, 'an indirect or computed place');
3644
+ if (!allowArray)
3645
+ scalar(n);
3646
+ };
3647
+ const access = (n, receiver, outParams, inInit = false) => {
3648
+ scalar(n);
3649
+ const b = strip(n.inner[0]), arr = b.kind === 'ImplicitCastExpr' && b.castKind === 'ArrayToPointerDecay' && b.inner?.[0];
3650
+ if (!arr)
3651
+ return bad(n, 'array access through a pointer or an unknown extent');
3652
+ const a = strip(arr);
3653
+ direct(a, receiver, outParams, true, inInit);
3654
+ const t = T(tyOf(a.type));
3655
+ if (!t.fixed || !Number.isSafeInteger(t.len) || t.len <= 0)
3656
+ bad(a, 'array without a known positive extent');
3657
+ expr(n.inner[1], receiver, outParams, inInit);
3658
+ siteOf(n, 'bounds');
3659
+ return true;
3660
+ };
3661
+ const unordered = (n, a, b) => {
3662
+ if (a && b)
3663
+ bad(n, 'unspecified order between two potentially faulting operands');
3664
+ return a || b;
3665
+ };
3666
+ const safeConstVal = (n0) => {
3667
+ const n = strip(n0);
3668
+ if (n.kind === 'ConstantExpr' && n.inner?.length === 1)
3669
+ return safeConstVal(n.inner[0]);
3670
+ if (n.kind === 'IntegerLiteral' && n.value !== undefined && n.type) {
3671
+ const t = T(tyOf(n.type));
3672
+ if (t.k !== 'int' || !t.bits || t.bits > 32)
3673
+ return undefined;
3674
+ const v = BigInt(n.value), hi = 2n ** BigInt(t.bits - Number(t.signed)) - 1n;
3675
+ return v >= 0n && v <= hi ? v : undefined;
3676
+ }
3677
+ if (n.kind === 'UnaryOperator' && (n.opcode === '+' || n.opcode === '-') && n.inner?.length === 1 && n.type) {
3678
+ const v = safeConstVal(n.inner[0]), t = T(tyOf(n.type));
3679
+ if (v === undefined || t.k !== 'int' || !t.bits || t.bits > 32)
3680
+ return undefined;
3681
+ const r = n.opcode === '-' ? -v : v;
3682
+ if (t.signed) {
3683
+ const lo = -(2n ** BigInt(t.bits - 1)), hi = -lo - 1n;
3684
+ return r >= lo && r <= hi ? r : undefined;
3685
+ }
3686
+ const m = 2n ** BigInt(t.bits);
3687
+ return ((r % m) + m) % m;
3688
+ }
3689
+ if (n.kind === 'BinaryOperator' && n.inner?.length === 2 && n.type) {
3690
+ const a = safeConstVal(n.inner[0]), b = safeConstVal(n.inner[1]), t = T(tyOf(n.type));
3691
+ if (a === undefined || b === undefined || t.k !== 'int' || !t.bits || t.bits > 32)
3692
+ return undefined;
3693
+ const lo = t.signed ? -(2n ** BigInt(t.bits - 1)) : 0n, hi = t.signed ? -lo - 1n : (2n ** BigInt(t.bits)) - 1n;
3694
+ let r;
3695
+ if (n.opcode === '+')
3696
+ r = a + b;
3697
+ else if (n.opcode === '-')
3698
+ r = a - b;
3699
+ else if (n.opcode === '*')
3700
+ r = a * b;
3701
+ else if (n.opcode === '/' || n.opcode === '%') {
3702
+ if (b === 0n || (t.signed && a === lo && b === -1n))
3703
+ return undefined;
3704
+ r = n.opcode === '/' ? a / b : a % b;
3705
+ }
3706
+ else
3707
+ return undefined;
3708
+ if (t.signed)
3709
+ return r >= lo && r <= hi ? r : undefined;
3710
+ const m = 2n ** BigInt(t.bits);
3711
+ return ((r % m) + m) % m;
3712
+ }
3713
+ return undefined;
3714
+ };
3715
+ const helperInfo = new Map(), activeCallStack = new Set();
3716
+ let activeMutates = false;
3717
+ const isStatePlace = (n0, outParams) => {
3718
+ const n = strip(n0);
3719
+ if (n.kind === 'MemberExpr' || n.kind === 'ArraySubscriptExpr')
3720
+ return true;
3721
+ if (isOutDeref(n, outParams))
3722
+ return true;
3723
+ if (n.kind === 'DeclRefExpr' && n.referencedDecl?.id && gfield.has(n.referencedDecl.id))
3724
+ return true;
3725
+ return false;
3726
+ };
3727
+ const validateCall = (n, receiver, outParams, inInit, allowMutate) => {
3728
+ if (inInit)
3729
+ return bad(n, 'a call inside a global initializer');
3730
+ const kids = n.inner ?? [], cname = calleeName(n), callee = cname && !FAIL[cname] ? funcs.get(cname) : undefined;
3731
+ if (!callee || !mine(callee))
3732
+ return bad(n, `call to ${cname ?? 'indirect function'}`);
3733
+ if (activeCallStack.has(cname))
3734
+ return bad(n, `recursive call to ${cname}`);
3735
+ const callArgs = kids.slice(1), cRecv = recvOf(callee), cParams = args0(callee);
3736
+ let argFault = false;
3737
+ if (!gmode && cRecv) {
3738
+ if (callArgs.length !== cParams.length + 1)
3739
+ return bad(n, `arity mismatch calling ${cname}`);
3740
+ const r0 = strip(callArgs[0]);
3741
+ if (r0.kind !== 'DeclRefExpr' || !receiver || r0.referencedDecl?.id !== receiver)
3742
+ return bad(n, `helper ${cname} called without the event receiver`);
3743
+ for (let i = 0; i < cParams.length; i++) {
3744
+ const ca = callArgs[i + 1], cp = cParams[i];
3745
+ if (boxed.has(cp.id)) {
3746
+ const ar = strip(ca);
3747
+ if (ar.kind !== 'DeclRefExpr' || !ar.referencedDecl?.id || !outParams.has(ar.referencedDecl.id))
3748
+ return bad(ca, `helper ${cname} out-parameter must forward a direct out-parameter`);
3749
+ }
3750
+ else
3751
+ argFault = unordered(n, argFault, expr(ca, receiver, outParams, inInit));
3752
+ }
3753
+ }
3754
+ else {
3755
+ if (callArgs.length !== cParams.length)
3756
+ return bad(n, `arity mismatch calling ${cname}`);
3757
+ for (let i = 0; i < cParams.length; i++) {
3758
+ const ca = callArgs[i], cp = cParams[i];
3759
+ if (boxed.has(cp.id)) {
3760
+ const ar = strip(ca);
3761
+ if (ar.kind !== 'DeclRefExpr' || !ar.referencedDecl?.id || !outParams.has(ar.referencedDecl.id))
3762
+ return bad(ca, `helper ${cname} out-parameter must forward a direct out-parameter`);
3763
+ }
3764
+ else
3765
+ argFault = unordered(n, argFault, expr(ca, receiver, outParams, inInit));
3766
+ }
3767
+ }
3768
+ const info = validateFunc(cname, callee, false);
3769
+ if (info.mutates) {
3770
+ if (!allowMutate)
3771
+ bad(n, `call to state-mutating helper ${cname} inside an expression`);
3772
+ activeMutates = true;
3773
+ }
3774
+ for (const s of info.sites)
3775
+ if (activeSites && !activeSites.includes(s))
3776
+ activeSites.push(s);
3777
+ return argFault || info.canFault;
3778
+ };
3779
+ const expr = (n, receiver, outParams = new Set(), inInit = false) => {
3780
+ const kids = n.inner ?? [], [l, r] = kids;
3781
+ if (n.kind === 'ParenExpr')
3782
+ return expr(l, receiver, outParams, inInit);
3783
+ if (n.kind === 'ConstantExpr' && kids.length === 1)
3784
+ return expr(l, receiver, outParams, inInit);
3785
+ if (CAST.has(n.kind)) {
3786
+ if (n.castKind !== 'ToVoid')
3787
+ scalar(n);
3788
+ if (!['LValueToRValue', 'NoOp', 'IntegralCast', 'IntegralToBoolean', 'ToVoid'].includes(n.castKind))
3789
+ return bad(n, `a ${n.castKind} conversion`);
3790
+ return expr(l, receiver, outParams, inInit);
3791
+ }
3792
+ const t = scalar(n);
3793
+ switch (n.kind) {
3794
+ case 'IntegerLiteral': {
3795
+ const v = BigInt(n.value), hi = 2n ** BigInt(t.bits - Number(t.signed)) - 1n;
3796
+ if (v < 0 || v > hi)
3797
+ bad(n, 'an integer literal outside its exact Clang type range');
3798
+ return false;
3799
+ }
3800
+ case 'DeclRefExpr':
3801
+ case 'MemberExpr':
3802
+ direct(n, receiver, outParams, false, inInit);
3803
+ return false;
3804
+ case 'ArraySubscriptExpr': {
3805
+ const ct = constTableOf(n);
3806
+ if (ct) {
3807
+ checkNoRedeclaredGlobal(ct.g);
3808
+ let anyFault = false;
3809
+ for (let k = 0; k < ct.idx.length; k++) {
3810
+ const f = expr(ct.idx[k], receiver, outParams, inInit);
3811
+ // Earlier subscript bounds check already may fault; later index expressions are unordered with it.
3812
+ if (k > 0)
3813
+ unordered(ct.nodes[k], true, f);
3814
+ else
3815
+ anyFault = f;
3816
+ siteOf(ct.nodes[k], 'bounds');
3817
+ }
3818
+ void anyFault;
3819
+ return true;
3820
+ }
3821
+ return access(n, receiver, outParams, inInit);
3822
+ }
3823
+ case 'BinaryOperator': {
3824
+ const op = n.opcode, a = expr(l, receiver, outParams, inInit), b = expr(r, receiver, outParams, inInit);
3825
+ if (op === '&&' || op === '||')
3826
+ return a || b;
3827
+ const child = unordered(n, a, b);
3828
+ if (CMP.has(op))
3829
+ return child;
3830
+ if (op === '&') {
3831
+ const m = fold(r);
3832
+ if (m === undefined || m <= 0 || m + 1 > 2 ** 31 || !Number.isInteger(Math.log2(m + 1)))
3833
+ bad(n, 'bitwise & with other than a positive power-of-two constant mask');
3834
+ return child;
3835
+ }
3836
+ if (['+', '-', '*', '/', '%'].includes(op)) {
3837
+ if (op === '/' || op === '%')
3838
+ siteOf(n, 'division');
3839
+ else if (t.signed === true)
3840
+ siteOf(n, 'overflow');
3841
+ if (!child && safeConstVal(n) !== undefined)
3842
+ return false;
3843
+ return child || t.signed === true || op === '/' || op === '%';
3844
+ }
3845
+ return bad(n, `a ${op} expression`);
3846
+ }
3847
+ case 'UnaryOperator':
3848
+ if (n.opcode === '*' && isOutDeref(n, outParams))
3849
+ return false;
3850
+ if (['+', '-', '!'].includes(n.opcode)) {
3851
+ const child = expr(l, receiver, outParams, inInit);
3852
+ if (n.opcode === '-' && t.signed === true)
3853
+ siteOf(n, 'overflow');
3854
+ return child || (n.opcode === '-' && t.signed === true && strip(l).kind !== 'IntegerLiteral');
3855
+ }
3856
+ return bad(n, `a ${n.opcode} expression`);
3857
+ case 'ConditionalOperator': return kids.map(k => expr(k, receiver, outParams, inInit)).some(Boolean);
3858
+ case 'InitListExpr':
3859
+ if (n.array_filler === undefined && kids.length <= 1)
3860
+ return !!l && expr(l, receiver, outParams, inInit);
3861
+ break;
3862
+ case 'CallExpr': return validateCall(n, receiver, outParams, inInit, false);
3863
+ }
3864
+ return bad(n, n.kind);
3865
+ };
3866
+ const placeFault = (n, receiver, outParams) => {
3867
+ const v = strip(n);
3868
+ if (isStatePlace(v, outParams))
3869
+ activeMutates = true;
3870
+ if (v.kind === 'ArraySubscriptExpr')
3871
+ return access(v, receiver, outParams);
3872
+ direct(v, receiver, outParams);
3873
+ return false;
3874
+ };
3875
+ const stmt = (n, receiver, outParams) => {
3876
+ const kids = n.inner ?? [], [l, r] = kids;
3877
+ switch (n.kind) {
3878
+ case 'CompoundStmt': return kids.map(k => stmt(k, receiver, outParams)).some(Boolean);
3879
+ case 'NullStmt': return false;
3880
+ case 'ParenExpr': return stmt(l, receiver, outParams);
3881
+ case 'CallExpr': return validateCall(n, receiver, outParams, false, true);
3882
+ case 'WhileStmt':
3883
+ case 'ForStmt':
3884
+ case 'DoStmt': return bad(n, 'a loop (while/for/do)');
3885
+ case 'SwitchStmt':
3886
+ case 'GotoStmt':
3887
+ case 'BreakStmt':
3888
+ case 'ContinueStmt':
3889
+ case 'LabelStmt': return bad(n, `a ${n.kind} statement`);
3890
+ case 'ReturnStmt': return kids.map(k => expr(k, receiver, outParams)).some(Boolean);
3891
+ case 'IfStmt': {
3892
+ if (n.hasInitStorage || n.hasVarStorage || (kids.length !== 2 && kids.length !== 3))
3893
+ return bad(n, 'an if with extra context');
3894
+ const c = expr(l, receiver, outParams), arms = kids.slice(1).map(k => stmt(k, receiver, outParams)).some(Boolean);
3895
+ return c || arms;
3896
+ }
3897
+ case 'DeclStmt': {
3898
+ let f = false;
3899
+ for (const d of kids) {
3900
+ if (d.kind !== 'VarDecl' || d.name === '_' || (d.storageClass && d.storageClass !== 'auto' && d.storageClass !== 'register') || !d.init || d.inner?.length !== 1)
3901
+ return bad(d, 'a local without a modeled automatic scalar initializer');
3902
+ scalar(d);
3903
+ if (expr(d.inner[0], receiver, outParams))
3904
+ f = true;
3905
+ }
3906
+ return f;
3907
+ }
3908
+ case 'BinaryOperator':
3909
+ if (n.opcode === '=')
3910
+ return unordered(n, placeFault(l, receiver, outParams), expr(r, receiver, outParams));
3911
+ if (n.opcode === ',')
3912
+ return kids.map(k => stmt(k, receiver, outParams)).some(Boolean);
3913
+ break;
3914
+ case 'CompoundAssignOperator': {
3915
+ if (!['+=', '-=', '*=', '/=', '%='].includes(n.opcode) || placeFault(l, receiver, outParams))
3916
+ return bad(n, 'a compound assignment to other than a direct scalar place or an unsupported operator');
3917
+ const op = n.opcode.slice(0, -1), rf = expr(r, receiver, outParams);
3918
+ const result = n.computeResultType, ot = result ? tyOf(result) : bad(n, 'missing C compound-assignment result type');
3919
+ if (op === '/' || op === '%') {
3920
+ siteOf(n, 'division');
3921
+ return true;
3922
+ }
3923
+ if (T(ot).signed === true) {
3924
+ siteOf(n, 'overflow');
3925
+ return true;
3926
+ }
3927
+ return rf;
3928
+ }
3929
+ case 'UnaryOperator':
3930
+ if (['++', '--'].includes(n.opcode)) {
3931
+ if (placeFault(l, receiver, outParams))
3932
+ return bad(n, 'increment/decrement of other than a direct scalar place');
3933
+ const lt = tyOf(l.type), tt = scalar(l, lt);
3934
+ if (tt.k !== 'int')
3935
+ return bad(n, 'increment/decrement of a non-integer place');
3936
+ const it = tt.bits >= target.int ? lt : intT('int', target.int, true);
3937
+ if (T(it).signed === true) {
3938
+ siteOf(n, 'overflow');
3939
+ return true;
3940
+ }
3941
+ return false;
3942
+ }
3943
+ break;
3944
+ }
3945
+ return expr(n, receiver, outParams);
3946
+ };
3947
+ const validateFunc = (name, f, isEntry) => {
3948
+ const cached = helperInfo.get(name);
3949
+ if (cached) {
3950
+ if (isEntry)
3951
+ validated.add(name);
3952
+ else
3953
+ validatedHelpers.add(name);
3954
+ return cached;
3955
+ }
3956
+ if (!mine(f) || f.variadic || f.inner?.some(k => k.kind.endsWith('Attr')) || hasMacroLoc(f.loc))
3957
+ bad(f, 'a definition outside the main file, or an attributed, macro-spelled, or variadic function');
3958
+ const recv = recvOf(f);
3959
+ if (!gmode && recv)
3960
+ validateParamDecl(recv, 'receiver');
3961
+ else if (!gmode && isEntry)
3962
+ bad(f, 'an entry method without a receiver');
3963
+ const ret = parseT(f.type.qualType.slice(0, retEnd(f.type.qualType)));
3964
+ if (T(ret).k !== 'void')
3965
+ scalar(f, ret);
3966
+ const outParams = new Set();
3967
+ for (const q of args0(f)) {
3968
+ if (boxed.has(q.id)) {
3969
+ validateParamDecl(q, 'out');
3970
+ outParams.add(q.id);
3971
+ }
3972
+ else
3973
+ validateParamDecl(q, 'scalar');
3974
+ }
3975
+ const prevSites = activeSites, prevMutates = activeMutates, fnSites = [];
3976
+ activeSites = fnSites;
3977
+ activeMutates = false;
3978
+ activeCallStack.add(name);
3979
+ let canFault = false, mutates = false;
3980
+ try {
3981
+ canFault = stmt(f.inner.find(c => c.kind === 'CompoundStmt'), gmode ? undefined : recv?.id, outParams);
3982
+ mutates = activeMutates;
3983
+ }
3984
+ finally {
3985
+ activeCallStack.delete(name);
3986
+ activeSites = prevSites;
3987
+ activeMutates = prevMutates;
3988
+ }
3989
+ const info = { sites: fnSites, canFault, mutates };
3990
+ helperInfo.set(name, info);
3991
+ methodSites.set(name, fnSites);
3992
+ if (isEntry)
3993
+ validated.add(name);
3994
+ else
3995
+ validatedHelpers.add(name);
3996
+ return info;
3997
+ };
3998
+ const state = (d) => {
3999
+ const q = T(tyOf(d.type)), raw = `${d.type.qualType} ${d.type.desugaredQualType ?? ''}`;
4000
+ if (/\b(?:volatile|_Atomic)\b/.test(raw) || d.isBitfield || !d.name || d.inner?.some(k => k.kind.endsWith('Attr')))
4001
+ bad(d, 'state with unmodeled qualifiers, attributes or layout');
4002
+ if (q.k === 'array' && q.fixed) {
4003
+ if (!Number.isSafeInteger(q.len) || q.len <= 0 || d.init)
4004
+ bad(d, 'an array without a modeled fixed zero start');
4005
+ scalar(d, q.elem);
4006
+ }
4007
+ else
4008
+ scalar(d);
4009
+ };
4010
+ if (entryRec) {
4011
+ const rec = records.get(entryRec);
4012
+ if (rec.tagUsed !== 'struct' || rec.inner?.some(k => k.kind.endsWith('Attr')))
4013
+ bad(rec, 'an entry other than a plain struct');
4014
+ for (const f of rec.inner ?? [])
4015
+ if (f.kind === 'FieldDecl')
4016
+ state(f);
4017
+ }
4018
+ activeSites = ctorSites;
4019
+ for (const g of gnodes) {
4020
+ checkNoRedeclaredGlobal(g);
4021
+ state(g);
4022
+ if (g.storageClass !== 'static' || g.tls || !mine(g))
4023
+ bad(g, 'state not defined as file-local in this translation unit');
4024
+ if (g.init) {
4025
+ if (g.inner?.length !== 1)
4026
+ bad(g, 'global initializer with unexpected structure');
4027
+ expr(g.inner[0], undefined, new Set(), true);
4028
+ }
4029
+ }
4030
+ activeSites = undefined;
4031
+ for (const [name, f] of funcs) {
4032
+ if (gmode ? !requests.has(name) : !recvOf(f) || (pickNames.length ? !pickNames.includes(name) : !mine(f) || f.storageClass === 'static'))
4033
+ continue;
4034
+ validateFunc(name, f, true);
4035
+ }
4036
+ if (pickNames.length) {
4037
+ for (const want of pickNames)
4038
+ if (!validated.has(want))
4039
+ bad(td0(), `selected method ${want} is missing or lacks a modeled receiver`);
4040
+ }
4041
+ // Closed-TU function coverage & symbol/preprocessor audit:
4042
+ // - System headers are classified strictly by resolved path under Clang's built-in or -isystem
4043
+ // search directories (never linemarker flag 3); every non-system file in the TU (including
4044
+ // headers under root, relative ../, or -I) is audited identically to own code.
4045
+ // - Every non-system function body must be a selected validated method or an inlined
4046
+ // file-local static helper; any other body (even static, inline, or __-prefixed) is refused
4047
+ // and named.
4048
+ // - Symbol export/alias/attribute escapes (__attribute__((alias/weak/constructor/destructor)),
4049
+ // #pragma weak, _Pragma("weak ..."), file-scope __asm__, post-definition redeclarations),
4050
+ // system_header pragmas and #line/linemarker directives in all spellings (#, %:, ??=, _Pragma),
4051
+ // global initializers referencing functions in any non-system file, pointer/fn-ptr struct
4052
+ // fields in globals, and user-code build-mode divergence (checked in clangDump) are refused.
4053
+ const meta = target.safetyMeta;
4054
+ const systemFiles = meta?.systemFiles;
4055
+ const userFiles = meta?.userFiles ?? new Set([mainReal]);
4056
+ const isSystemFile = (f) => {
4057
+ if (!f)
4058
+ return false;
4059
+ if (f === '<built-in>')
4060
+ return true;
4061
+ if (f === '<command line>')
4062
+ return false;
4063
+ const rp = realPath(f);
4064
+ if (userFiles.has(rp) || rp === mainReal)
4065
+ return false;
4066
+ if (systemFiles)
4067
+ return systemFiles.has(rp);
4068
+ return !own({ $at: { file: f, line: 0, col: 0, off: 0, tok: 0 } });
4069
+ };
4070
+ // A node is system ONLY if BOTH its expansion location AND every spelling/expansion file in
4071
+ // its loc/range chain are system files (never trusting expansionLoc alone when a user or -D
4072
+ // macro is expanded inside a system header).
4073
+ const isSystemNode = (n) => {
4074
+ if (!isSystemFile(n.$at?.file))
4075
+ return false;
4076
+ if (n.$files) {
4077
+ for (const f of n.$files)
4078
+ if (!isSystemFile(f))
4079
+ return false;
4080
+ }
4081
+ return true;
4082
+ };
4083
+ // Whole-class refusal: refuse any user-defined (or -D command-line) macro expanded inside a
4084
+ // system header anywhere in the TU (prevents hiding functions, attributes, aliases, or globals
4085
+ // inside system header locations via macro hijacking such as `#define ptrdiff_t ...`).
4086
+ const auditMacroExpansions = (n) => {
4087
+ for (const { spell, spellLine, expand, expandLine } of n.$macroExpansions ?? []) {
4088
+ if (expand !== '<built-in>' && isSystemFile(expand) && !isSystemFile(spell)) {
4089
+ const where = spell === '<command line>' ? '<command line>' : `${path.basename(spell)}:${spellLine}:1`;
4090
+ throw new Refusal(where, `user-defined macro expanded inside system header ${path.basename(expand)}:${expandLine} is outside the C safety subset`);
4091
+ }
4092
+ }
4093
+ if (!isSystemNode(n)) {
4094
+ if (n.kind === 'SourceLocExpr' || n.kind === 'PredefinedExpr')
4095
+ throw new Refusal(pos(n), `invocation/location-dependent expression (${n.kind}) is outside the C safety subset`);
4096
+ const refName = n.kind === 'DeclRefExpr' ? n.referencedDecl?.name : undefined;
4097
+ if (refName?.startsWith('__builtin_') && !ALLOWED_BUILTINS.has(refName))
4098
+ throw new Refusal(pos(n), `compiler builtin ${refName} is outside the C safety subset`);
4099
+ }
4100
+ for (const c of n.inner ?? [])
4101
+ auditMacroExpansions(c);
4102
+ };
4103
+ auditMacroExpansions(tu);
4104
+ // Fallback closed-world directive scan only when readC(..., safety=true) was called directly
4105
+ // without clangDump(..., safety=true) (which already ran the full auditUserPreprocessor pass).
4106
+ if (!meta) {
4107
+ const resolved = resolveSafetyClang('clang', file).bin;
4108
+ const fsRaw = node('node:fs');
4109
+ auditUserPreprocessor({
4110
+ activeClang: resolved,
4111
+ stdFlags: [],
4112
+ effectiveStd: 'gnu17',
4113
+ clangEnv: scrubbedClangEnv(),
4114
+ mainReal,
4115
+ userFiles,
4116
+ flags: [],
4117
+ bareDefs: '',
4118
+ includesBeforeLine: new Map(),
4119
+ activeUserDefines: new Set(),
4120
+ activeUserUndefs: new Set(),
4121
+ readBytes: p => fsRaw.readFileSync(p),
4122
+ basename: p => path.basename(p),
4123
+ });
4124
+ }
4125
+ const hasUnsafePtrType = (raw) => /\bvoid\s*\*|\(\s*\*|\*\s*\*/.test(raw);
4126
+ const typeIdxMentionsEntry = (start) => {
4127
+ if (!entryRec || start < 0)
4128
+ return false;
4129
+ const seen = new Set();
4130
+ const check = (idx) => {
4131
+ if (seen.has(idx))
4132
+ return false;
4133
+ seen.add(idx);
4134
+ if (idx === entryT)
4135
+ return true;
4136
+ const q = T(idx);
4137
+ if (!q)
4138
+ return false;
4139
+ if (q.elem !== undefined && check(q.elem))
4140
+ return true;
4141
+ if (q.fields?.some(fl => check(fl.t)))
4142
+ return true;
4143
+ return false;
4144
+ };
4145
+ return check(start);
4146
+ };
4147
+ const typeIdxHasPtrOrFunc = (start) => {
4148
+ if (start < 0)
4149
+ return false;
4150
+ const seen = new Set();
4151
+ const check = (idx) => {
4152
+ if (seen.has(idx))
4153
+ return false;
4154
+ seen.add(idx);
4155
+ const q = T(idx);
4156
+ if (!q)
4157
+ return false;
4158
+ if (q.k === 'ptr' || q.k === 'func' || q.k === 'ref' || q.k === 'opaque' || q.k === 'union' || q.nullflag)
4159
+ return true;
4160
+ if (q.elem !== undefined && check(q.elem))
4161
+ return true;
4162
+ if (q.fields?.some(fl => check(fl.t)))
4163
+ return true;
4164
+ return false;
4165
+ };
4166
+ return check(start);
4167
+ };
4168
+ const typeMentionsEntry = (ty) => !!entryRec && !!ty && typeIdxMentionsEntry(tyOf(ty));
4169
+ const uncheckedFns = [];
4170
+ for (const [name, f] of funcs) {
4171
+ if (validated.has(name))
4172
+ continue;
4173
+ if (f.storageClass === 'static' && validatedHelpers.has(name))
4174
+ continue;
4175
+ uncheckedFns.push({ name, node: f });
4176
+ }
4177
+ for (const n of top) {
4178
+ if (n.kind === 'FunctionDecl' && !n.isImplicit && !own(n) && n.inner?.some(c => c.kind === 'CompoundStmt')) {
4179
+ if (!isSystemNode(n))
4180
+ uncheckedFns.push({ name: n.name ?? '<anonymous>', node: n });
4181
+ }
4182
+ }
4183
+ if (uncheckedFns.length) {
4184
+ const names = uncheckedFns.map(u => u.name);
4185
+ const covered = [...validated];
4186
+ throw new SafetyUncoveredRefusal(pos(uncheckedFns[0].node), `unchecked function${names.length === 1 ? '' : 's'} in translation unit: ${names.join(', ')} (every function with a body must be covered by C safety; covered: ${covered.length ? covered.join(', ') : 'none'})`, covered, names, meta?.macroConfig);
4187
+ }
4188
+ // Reject file-scope asm, attributed/aliased/weak/constructor/destructor/post-definition
4189
+ // function declarations, bodyless external prototypes that could write state, non-system
4190
+ // globals with attributes/extern/pointers/fn-ptrs (including inside struct/array fields) or
4191
+ // function-referencing initializers, and system-header declarations referencing modeled state.
4192
+ const scanForeignStateAccess = (n, fnName) => {
4193
+ if (n.kind === 'MemberExpr' && entryRec && fields.get(n.referencedMemberDecl ?? '')?.rec === entryRec)
4194
+ bad(n, `external header function ${fnName} accesses entry struct ${entry}`);
4195
+ if (n.kind === 'DeclRefExpr' && n.referencedDecl?.kind === 'VarDecl' && gfield.has(n.referencedDecl.id))
4196
+ bad(n, `external header function ${fnName} accesses modeled global state`);
4197
+ if ((n.kind === 'ParmVarDecl' || n.kind === 'VarDecl') && typeMentionsEntry(n.type))
4198
+ bad(n, `external header function ${fnName} references entry struct ${entry}`);
4199
+ for (const c of n.inner ?? [])
4200
+ scanForeignStateAccess(c, fnName);
4201
+ };
4202
+ const definedFns = new Set();
4203
+ for (const n of top) {
4204
+ if (n.kind === 'FileScopeAsmDecl')
4205
+ bad(n, 'file-scope inline assembly is outside the closed translation unit');
4206
+ if (n.kind === 'FunctionDecl' && !n.isImplicit) {
4207
+ const hasBody = !!n.inner?.some(c => c.kind === 'CompoundStmt');
4208
+ const nonSys = !isSystemNode(n);
4209
+ const fnName = n.name ?? '<anonymous>';
4210
+ if (nonSys) {
4211
+ if (n.inner?.some(c => c.kind.endsWith('Attr')))
4212
+ bad(n, `attributed function declaration ${fnName} (alias/weak/constructor/destructor) is outside the closed translation unit`);
4213
+ if (!hasBody && n.name && definedFns.has(n.name))
4214
+ bad(n, `post-definition redeclaration of function ${fnName} is outside the closed translation unit`);
4215
+ }
4216
+ if (hasBody && n.name)
4217
+ definedFns.add(n.name);
4218
+ if (!hasBody && !(n.name && funcs.has(n.name))) {
4219
+ const ps = params(n);
4220
+ const qt = n.type?.qualType ?? '';
4221
+ const retIdx = qt ? parseT(qt.slice(0, retEnd(qt))) : -1;
4222
+ if (typeIdxMentionsEntry(retIdx) || ps.some(q => typeMentionsEntry(q.type)))
4223
+ bad(n, `external function prototype ${fnName} references entry struct ${entry} with no body in this translation unit`);
4224
+ if (nonSys) {
4225
+ if (n.variadic || (ps.length === 0 && /\(\s*\)$/.test(qt)))
4226
+ bad(n, `external function prototype ${fnName} has no body and an unclosed parameter list`);
4227
+ if (retIdx >= 0 && !['void', 'bool', 'int'].includes(T(retIdx).k))
4228
+ bad(n, `external function prototype ${fnName} returns non-scalar type ${T(retIdx).go ?? T(retIdx).k} with no body in this translation unit`);
4229
+ for (const q of ps) {
4230
+ const raw = `${q.type?.qualType ?? ''} ${q.type?.desugaredQualType ?? ''}`;
4231
+ const pt = q.type ? T(tyOf(q.type)) : undefined;
4232
+ if (hasUnsafePtrType(raw) || !pt || !['int', 'bool'].includes(pt.k))
4233
+ bad(q, `external function prototype ${fnName} takes pointer or non-scalar parameter ${q.name ?? ''} with no body in this translation unit`);
4234
+ }
4235
+ }
4236
+ }
4237
+ else if (hasBody && !own(n)) {
4238
+ scanForeignStateAccess(n, fnName);
4239
+ }
4240
+ }
4241
+ if (n.kind === 'VarDecl' && !n.isImplicit) {
4242
+ if (!isSystemNode(n)) {
4243
+ if (!gfield.has(n.id)) {
4244
+ const raw = `${n.type?.qualType ?? ''} ${n.type?.desugaredQualType ?? ''}`;
4245
+ if (n.inner?.some(c => c.kind.endsWith('Attr')))
4246
+ bad(n, `attributed global ${n.name ?? ''} is outside the closed translation unit`);
4247
+ if (n.storageClass === 'extern')
4248
+ bad(n, `extern global ${n.name ?? ''} is outside the closed translation unit`);
4249
+ if (typeMentionsEntry(n.type))
4250
+ bad(n, `global ${n.name ?? ''} references entry struct ${entry}`);
4251
+ if (hasUnsafePtrType(raw) || (n.type && typeIdxHasPtrOrFunc(tyOf(n.type))))
4252
+ bad(n, `pointer, function-pointer, or unmodeled aggregate global ${n.name ?? ''} is outside the closed translation unit`);
4253
+ }
4254
+ if (n.init) {
4255
+ const scanInit = (c) => {
4256
+ if (c.kind === 'DeclRefExpr' && c.referencedDecl?.kind === 'FunctionDecl')
4257
+ bad(c, `global ${n.name ?? ''} initializer references function ${c.referencedDecl.name}`);
4258
+ for (const k of c.inner ?? [])
4259
+ scanInit(k);
4260
+ };
4261
+ scanInit(n);
4262
+ }
4263
+ }
4264
+ else if (typeMentionsEntry(n.type)) {
4265
+ bad(n, `external header global ${n.name ?? ''} references entry struct ${entry}`);
4266
+ }
4267
+ }
4268
+ }
4269
+ sitesFrozen = true;
4270
+ }
1253
4271
  let ctor;
1254
4272
  for (const [name, f] of funcs)
1255
- out.push(fn(name, f));
4273
+ if (!safety || validated.has(name) || validatedHelpers.has(name)) {
4274
+ const gf = fn(name, f);
4275
+ if (safety)
4276
+ gf.safetySites = methodSites.get(name) ?? [];
4277
+ out.push(gf);
4278
+ }
1256
4279
  // (the globals' start: each one's initializer, where it has one; C's zero where not)
1257
4280
  if (gmode) {
1258
4281
  const pre = [];
@@ -1273,7 +4296,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
1273
4296
  else
1274
4297
  pre.push({ s: 'assign', p: pos(v), op: '=', l: [place], r: [x(v)] });
1275
4298
  }
1276
- ctor = { name: '$ctor', p: pos(td0()), span: [0, 0], recv: { t: ptrT, ptr: true, type: entry, name: 'this', id: 'this' }, params: [], results: [], body: pre };
4299
+ ctor = { name: '$ctor', p: pos(td0()), span: [0, 0], recv: { t: ptrT, ptr: true, type: entry, name: 'this', id: 'this' }, params: [], results: [], body: pre, ...(safety ? { safetySites: ctorSites } : {}) };
1277
4300
  }
1278
4301
  // The constructor (C++): its member initializers (each field's own in-class one where it has no other), then its body;
1279
4302
  // the rule starts where it leaves the object, its parameters the rule's.
@@ -1302,13 +4325,13 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pi
1302
4325
  ctor = c ? fn('$ctor', Object.assign(c, { $m: true }), pre) : { name: '$ctor', p: pos(td0()), span: [0, 0], recv: { t: add(`ptr:${entryT}`, { k: 'ptr', go: `${entry} *`, elem: entryT }), ptr: true, type: entry, name: 'this', id: 'this' }, params: [], results: [], body: pre };
1303
4326
  }
1304
4327
  const td = td0();
1305
- const pkg = { lang: cpp ? 'cpp' : 'c', package: entry, files: [{ name: base, imports: [] }], funcs: out, types: [{ name: entry, t: entryT, p: pos(td), span: [td.$b?.line ?? 0, td.$e?.line ?? 0] }], consts: [], vars: [], errors: [], ttab, ...(ctor ? { ctor } : {}) };
4328
+ const pkg = { lang: cpp ? 'cpp' : 'c', ...(safety ? { safety: true } : {}), package: entry, files: [{ name: base, imports: [] }], funcs: out, types: [{ name: entry, t: entryT, p: pos(td), span: [td.$b?.line ?? 0, td.$e?.line ?? 0] }], consts: [], vars: [], errors: [], ttab, ...(ctor ? { ctor } : {}) };
1306
4329
  // (by default: the file's non-static functions taking the struct; a class's public methods)
1307
- const methods = gmode ? [...requests] : out.filter((f, i) => { const n = [...funcs.values()][i]; return f.recv && !f.static && (n.$m ? n.$access === 'public' : mine(n)); }).map(f => f.name);
4330
+ const methods = safety ? [...validated] : gmode ? [...requests] : out.filter((f, i) => { const n = [...funcs.values()][i]; return f.recv && !f.static && (n.$m ? n.$access === 'public' : mine(n)); }).map(f => f.name);
1308
4331
  // (the class's qualified name, which the harness spells: `this`'s type, as clang prints it)
1309
4332
  const thisOf = (n) => (n.kind === 'CXXThisExpr' ? n.type.qualType : (n.inner ?? []).map(thisOf).find(Boolean));
1310
4333
  const self = cpp ? cxx.filter(m => m.$rec === entryRec).map(thisOf).find(Boolean)?.replace(/^const /, '').replace(/ \*$/, '') : undefined;
1311
- return { pkg, methods, entry, cname: self ?? T(entryT).go, consts: Object.fromEntries([...named].filter(([, v]) => Number.isSafeInteger(v))),
4334
+ return { pkg, methods, ...(safety && validatedHelpers.size ? { helpers: [...validatedHelpers] } : {}), ...(safety && target.safetyMeta ? { macroConfig: target.safetyMeta.macroConfig, ...(target.safetyMeta.verifySnapshotUnchanged ? { verifySnapshotUnchanged: target.safetyMeta.verifySnapshotUnchanged } : {}) } : {}), entry, cname: self ?? T(entryT).go, consts: Object.fromEntries([...named].filter(([, v]) => Number.isSafeInteger(v))),
1312
4335
  ...(gmode ? { globals: { state: gnodes.map(g => g.name), inputs: gnodes.filter(g => ginput.has(g.id)).map(g => g.name), types: Object.fromEntries(gnodes.map(g => [g.name, g.type.qualType])),
1313
4336
  // (declared only, another file's to define: the check defines it, zero at the start)
1314
4337
  externs: gnodes.filter(g => ![...globals.values()].some(d => d.name === g.name && (d.storageClass !== 'extern' || d.init))).map(g => g.name) } } : {}) };