clang/utils/safe-c/juliet-port.ts
Raw file ยท Directory on GitHub
1// Ports NIST Juliet cases to Safe C into a separate tree, so their fixed
2// good() versions can compile and be scored. Each transform is the change a
3// person porting the code would make, and none removes a bug: see each rule.
4// bun juliet-port.ts <juliet root> <out root> [cwe,...]
5import { join, dirname } from "path";
6import { mkdirSync, cpSync, existsSync, readdirSync, statSync, readFileSync, writeFileSync } from "fs";
7
8const [src, out, cweArg] = process.argv.slice(2);
9// JULIET_PORT_OFF=f,g turns transforms off by letter, to gate each one alone.
10const off = new Set((process.env.JULIET_PORT_OFF ?? "").split(",").filter(Boolean));
11if (!src || !out) { console.error("usage: bun juliet-port.ts <juliet root> <out root> [121,122]"); process.exit(2); }
12const cwes = (cweArg ?? "476,690,415,416,121,122,124,126,127,369").split(",");
13const TC = join(src, "suite/C/testcases"), OTC = join(out, "suite/C/testcases");
14cpSync(join(src, "suite/C/testcasesupport"), join(out, "suite/C/testcasesupport"), { recursive: true });
15cpSync(join(import.meta.dir, "juliet_port.h"), join(out, "suite/C/testcasesupport/juliet_port.h"));
16
17const stats: Record<string, number> = { files: 0, strfns: 0 };
18// caseText: every file of the case as written (a, b, c... parts), comments out.
19function port(text: string, file: string, caseText: string): string {
20 text = text.replace(/\r\n/g, "\n"); // Juliet ships CRLF
21 // A pointer local set to NULL needs no annotation: the compiler tracks which
22 // of its values may be null, and a _Nullable declaration would forget that
23 // a later assignment made it nonnull.
24 // (f) Flow variants 05, 07 (and 09, 10, 13, 14 through juliet_port.h) pick
25 // their path with a flag that is set once and never written: `static int
26 // staticTrue = 1`. A porter declares such a flag const, which is what it
27 // is, so the compiler sees which branch runs. Every path runs exactly as
28 // before, so bad() still takes its buggy branch.
29 if (!off.has("f")) text = text.replace(/^static int (static(?:True|False|Five)) = (\d+);/gm,
30 (_m, name, v) => { stats.constFlags = (stats.constFlags ?? 0) + 1; return `static const int ${name} = ${v};`; });
31 // (g) Flow variants 21 and 22 tell a sink which path to take through a
32 // file-scope int (`badStatic = 1; badSink(data);`). Safe C rejects a
33 // mutable global because threads could race on it; the program has one
34 // thread, so a porter makes it _Thread_local, as the error suggests. Every
35 // read sees the value the same thread just wrote, exactly as before.
36 if (!off.has("g")) text = text.replace(/^(static |extern )?int (\w*(?:Static|Global))( = \d+)?;/gm,
37 (_m, sc, name, init) => { stats.threadLocal = (stats.threadLocal ?? 0) + 1; return `${sc ?? ""}_Thread_local int ${name}${init ?? ""};`; });
38 // (c) Flow variants 34 and 67 pass the data through a union or struct
39 // that lives only in locals and parameters: a borrow carrier, which Safe
40 // C spells _View (Rust: a struct with a lifetime).
41 text = text.replace(/typedef union\s*\n\{/g, () => { stats.views = (stats.views ?? 0) + 1; return "typedef union _View\n{"; });
42 text = text.replace(/typedef struct (\w*_structType)\b/g, (_m, name) => { stats.views = (stats.views ?? 0) + 1; return `typedef struct _View ${name}`; });
43 // (d) charVoid keeps a string literal in void * fields and casts it back
44 // to print it: give the fields their real type (static text). The bug,
45 // writing past charFirst into those fields, is unchanged.
46 if (text.includes("voidSecond")) {
47 stats.statics = (stats.statics ?? 0) + 1;
48 text = text.replace(/^(\s+)void \* (voidSecond|voidThird);/gm, (_m, i, n) => `${i}const ${/wchar_t charFirst/.test(text) ? "wchar_t" : "char"} *_Static ${n};`);
49 text = text.replace(/(voidSecond\s*=\s*)\(void \*\)/g, "$1");
50 text = text.replace(/\((?:char|wchar_t) \*\)(structCharVoid(?:\.|->)voidSecond)/g, "$1");
51 }
52 // (e) A buffer handed to a sink as `T * data` must carry its bounds
53 // across the call (Rust: a slice); a plain pointer parameter is one
54 // element, so the sink's copy would trap on correct code. The buggy
55 // versions keep their buffers' real bounds and still trap.
56 // Variants 63 and 64 pass a pointer to one variable (`dataPtr`), not a
57 // buffer, and declare it as `data` in another file: leave them alone.
58 const pointsToOne = /_6[34][a-z]?\.c$/.test(file);
59 // ...but when that variable is the buffer pointer itself (`T * * dataPtr`),
60 // the pointer it points to carries the buffer's bounds.
61 if (pointsToOne)
62 text = text.replace(/([(,]\s*)((?:const\s+)?[A-Za-z_]\w*) \* \* (data|dataPtr)(\s*[,)])/g,
63 (_m, pre, ty, name, post) => { stats.slices = (stats.slices ?? 0) + 1; return `${pre}${ty} *__bidi_indexable * ${name}${post}`; });
64 if (!pointsToOne) text = text.replace(/([(,]\s*)((?:const\s+)?[A-Za-z_]\w*) \* data(\s*[,)])/g,
65 (_m, pre, ty, post) => { stats.slices = (stats.slices ?? 0) + 1; return `${pre}${ty} *__bidi_indexable data${post}`; });
66 text = text.replace(/\(\*funcPtr\) \(((?:const\s+)?[A-Za-z_]\w*) \*\)/g, "(*funcPtr) ($1 *__bidi_indexable)");
67 // ...and the same through a source function's result (variants 42, 61)
68 // or a carrier's field (34, 67).
69 text = text.replace(/^((?:static\s+)?(?:const\s+)?[A-Za-z_]\w*) \* ([A-Za-z_]\w*[Ss]ource\s*\()/gm,
70 (_m, ty, fn) => { stats.slices = (stats.slices ?? 0) + 1; return `${ty} *__bidi_indexable ${fn}`; });
71 text = text.replace(/^(\s+(?:const\s+)?[A-Za-z_]\w*) \* (structFirst|unionFirst|unionSecond);/gm, "$1 *__bidi_indexable $2;");
72 // Outside the null and lifetime CWEs a null check cannot hide the bug: the
73 // pointer is never null at run time, in bad() or good(), so it never fires.
74 // If it did fire, exit(-1) scores as a miss. In CWE 476/690 null is the
75 // bug, and in 415/416 a check could read a freed pointer: no checks there.
76 const guardOk = /CWE(121|122|124|126|127|369)_/.test(file);
77 const guard = (ind: string, v: string) => `\n${ind}if (${v} == NULL) {exit(-1);}`;
78 const bump = (k: string) => { stats[k] = (stats[k] ?? 0) + 1; };
79 const P = "\\*__bidi_indexable";
80 // (h) A source handed a NULL variable to overwrite takes and may return
81 // null, and the caller checks the result with Juliet's own idiom, as a Rust
82 // port unwraps an Option.
83 const nullSources = new Set([...caseText.matchAll(/\bdata = NULL;(?:[^;{}]*;)?\s*data = (\w*Source)\(data\);/g)].map(m => m[1]));
84 if (!off.has("h")) {
85 text = text.replace(new RegExp(`^((?:static\\s+)?(?:const\\s+)?\\w+ ${P}) (\\w*Source)\\(((?:const\\s+)?\\w+ ${P}) data\\)`, "gm"), (m, r, fn, p) => {
86 if (!nullSources.has(fn)) return m;
87 bump("nullableSources"); return `${r} _Nullable ${fn}(${p} _Nullable data)`; });
88 if (guardOk) text = text.replace(/^([ \t]+)data = (\w*Source)\(data\);/gm, (m, ind, fn) => {
89 if (!nullSources.has(fn)) return m;
90 bump("sourceGuards"); return m + guard(ind, "data"); });
91 }
92 // (i) Variants 45 and 68 carry the data through a file-scope variable. Like
93 // (g) it is _Thread_local. A heap buffer moved through one is _Owned, and
94 // the sink that frees it takes it out. A stack buffer or interior pointer in
95 // a global has no safe spelling (nor in Rust): it is _Unchecked, and its one
96 // read is __unsafe (counted). The unsafe part is only its lifetime; the
97 // pointer keeps its bounds, and the sink's accesses stay outside, checked.
98 // In CWE 690 the global may be null and the sink decides.
99 if (!off.has("i")) {
100 const is690 = /CWE690_/.test(file);
101 const movesHeap = /\bfree\(data\)/.test(caseText) && guardOk;
102 text = text.replace(/^(static |extern )?((?:const )?(?:unsigned )?\w+) (\* )?(CWE\w+Data\w*);/gm, (m, sc, ty, ptr, name) => {
103 if (ptr && !movesHeap && !(guardOk && /\*/.test(ptr)) && !is690) return m;
104 bump("dataGlobals");
105 return `${sc ?? ""}_Thread_local ${ty} ${ptr ? (movesHeap || is690 ? "*_Owned" : "*_Unchecked") + " __bidi_indexable _Nullable " : ""}${name};`;
106 });
107 if (movesHeap) text = text.replace(/^([ \t]+)((?:const )?\w+ \* data) = (CWE\w+Data\w*);/gm, (_m, ind, decl, g) => `${ind}${decl} = _Take(${g});${guard(ind, "data")}`);
108 else if (is690) text = text.replace(/^([ \t]+\w+ \* data) = (CWE\w+Data\w*);/gm, "$1 = _Take($2);");
109 else if (guardOk) text = text.replace(/^([ \t]+)((?:const )?\w+ \*) data = (CWE\w+Data\w*);/gm, (_m, ind, ty, g) => {
110 bump("unsafeReads"); return `${ind}${ty} data = NULL;\n${ind}__unsafe { data = ${g}; }${guard(ind, "data")}`; });
111 }
112 // (j) A sink that frees its argument takes ownership of it (Rust: Box<T> by
113 // value), and so does every function that passes its argument on to one.
114 // (k) A sink that checks its argument for null before using it accepts
115 // null (Rust: Option), and so does one that passes it on to such a sink.
116 // A sink that does not check stays nonnull, so the null CWEs' bad paths are
117 // still rejected.
118 const fns = new Map<string, string>();
119 for (const m of caseText.matchAll(/^[\w *]*?\b(\w+)\([^()]*\bdata\)\n\{\n([\s\S]*?)\n\}/gm)) fns.set(m[1], m[2]);
120 const closure = (base: (b: string) => boolean) => {
121 const set = new Set([...fns].filter(([, b]) => base(b)).map(([f]) => f));
122 for (let grew = true; grew;) {
123 grew = false;
124 for (const [f, b] of fns) if (!set.has(f) && [...set].some(g => new RegExp(`\\b${g}\\(data\\)`).test(b))) { set.add(f); grew = true; }
125 }
126 return set;
127 };
128 const owns = closure(b => /\brealloc\(data,/.test(b) || (/\b(?:free|fclose)\(data\)/.test(b) && !/\bdata = (?!=)/.test(b)));
129 const checks = closure(b => { const c = b.search(/if \(data [!=]= NULL\)/), w = b.search(/\bdata = (?!=)|\bdata\[|\*data\b|\(data[,)]/); return c >= 0 && (w < 0 || c < w); });
130 text = text.replace(new RegExp(`\\b(\\w+)\\(((?:const )?\\w+ ${P}(?: _Nullable)?) data\\)`, "g"), (m, fn, p) => {
131 const o = !off.has("j") && owns.has(fn), n = !off.has("k") && checks.has(fn) && !p.endsWith("_Nullable");
132 if (o) bump("ownedParams");
133 if (n) bump("nullableParams");
134 return o || n ? `${fn}(${p}${n ? " _Nullable" : ""}${o ? " _Owned" : ""} data)` : m;
135 });
136 text = text.replace(new RegExp(`\\(\\*funcPtr\\) \\(((?:const )?\\w+ ${P})\\) = (\\w+);`, "g"), (_m, p, fn) =>
137 `(*funcPtr) (${p}${checks.has(fn) && !off.has("k") ? " _Nullable" : ""})${owns.has(fn) && !off.has("j") ? " _Takes(1)" : ""} = ${fn};`);
138 // (l) Variants 08, 11 and 17 set the data under a condition no compiler can
139 // see through (a call's result, a loop's first iteration). Declare it
140 // initialized; bad() then overwrites it with its buggy value as before. A
141 // pointer starts null and is checked after the block that sets it.
142 if (!off.has("l") && /_(08|11|17)\.c$/.test(file)) {
143 text = text.replace(/^( {4})((?:const |unsigned )?\w+) (\* ?)?data;$/gm, (m, ind, ty, ptr) => {
144 if (ptr && !guardOk) return m;
145 bump("initDecls"); return `${ind}${ty} ${ptr ? "* data = NULL" : "data = 0"};`; });
146 if (guardOk && /\* data = NULL;/.test(text))
147 text = text.replace(/^ {4}(?:if|for) ?\([^\n]*\n {4}\{\n[\s\S]*?^ {4}\}(?:\n {4}else\n {4}\{\n[\s\S]*?^ {4}\})?/gm, m => {
148 if (!/^ {8,12}data = /m.test(m)) return m;
149 bump("initGuards"); return m + guard(" ", "data"); });
150 }
151 // (m) Variant 66 passes the data in an array of five: the sink's parameter
152 // says how many elements it has, and the elements carry their own bounds.
153 if (!off.has("m")) {
154 text = text.replace(/\b((?:const )?\w+) \* dataArray\[(5?)\]/g, (_m, ty, n) => { bump("arrays"); return `${ty} *__bidi_indexable dataArray[${n || "__counted_by(5)"}]`; });
155 text = text.replace(/\b((?:const )?(?:unsigned )?\w+) dataArray\[\]/g, (_m, ty) => { bump("arrays"); return `${ty} dataArray[__counted_by(5)]`; });
156 }
157 // (n) Variant 64 passes &data as void * and casts it straight back. Give
158 // the parameter its real type and drop the cast.
159 if (!off.has("n") && /_64[a-z]\.c$/.test(file)) {
160 const t = caseText.match(/\(((?:const )?(?:unsigned )?\w+) \*( \*)?\)dataVoidPtr/);
161 if (t) {
162 const pt = t[2] ? `${t[1]} *__bidi_indexable *` : `${t[1]} *`;
163 text = text.replace(/\bvoid \* dataVoidPtr/g, () => { bump("typedVoid"); return pt + " dataVoidPtr"; });
164 text = text.replace(/^(\s+)[\w ]+\*(?: \*)? ?dataPtr = \([^()]*\)dataVoidPtr;/gm, `$1${pt} dataPtr = dataVoidPtr;`);
165 }
166 }
167 // (o) Variant 32 reaches the data through two pointers to it: the pointee
168 // carries the buffer's bounds. It may be null until the source sets it when
169 // the case starts it at NULL.
170 if (!off.has("o") && /_32\.c$/.test(file) && /\*dataPtr1 = &data;/.test(text)) {
171 const nul = /\bdata = NULL;/.test(caseText) || /CWE690_/.test(file) ? " _Nullable" : "";
172 text = text.replace(/^( {4})((?:const )?\w+) \* data;/gm, `$1$2 *__bidi_indexable${nul} data;`);
173 text = text.replace(/^( {4})((?:const )?\w+) \* ?\*dataPtr([12]) = &data;/gm, (_m, i, ty, n) => { bump("ptrToPtr"); return `${i}${ty} *__bidi_indexable${nul} *dataPtr${n} = &data;`; });
174 if (guardOk && nul) text = text.replace(/^( +)((?:const )?\w+ \* data = \*dataPtr2;)/gm, (m, ind) => m + guard(ind, "data"));
175 }
176 // (p) CWE 690's only good path checks the result in the sink, so whatever
177 // carries it there may hold null: say so on the field, array element or
178 // pointee. A bad sink that uses it unchecked is then rejected.
179 if (!off.has("p") && /CWE690_/.test(file)) {
180 text = text.replace(/\*__bidi_indexable (structFirst|unionFirst|unionSecond|dataArray\[)/g, (_m, n) => { bump("nullableCarriers"); return "*__bidi_indexable _Nullable " + n; });
181 if (/_6[34][a-z]?\.c$/.test(file)) {
182 text = text.replace(/\*__bidi_indexable \* (data\w*)/g, (_m, n) => { bump("nullableCarriers"); return "*__bidi_indexable _Nullable * " + n; });
183 text = text.replace(/^( {4})(\w+) \* data;/gm, "$1$2 *__bidi_indexable _Nullable data;");
184 }
185 }
186 // (q) CWE 476's char cases only read string literals through the pointer:
187 // make it pointer to const, as the literal is.
188 if (!off.has("q") && /CWE476_\w+__(char|wchar_t)_\d/.test(file)) {
189 const ty = file.match(/__(char|wchar_t)_\d/)![1];
190 text = text.replace(new RegExp(`(?<!const )\\b${ty} (\\*[^;)\\n]*\\bdata|\\*[^;)\\n]*(?:Data|structFirst|unionFirst|unionSecond|\\w*Source\\(|dataPtr|dataArray))`, "g"), (_m, r) => { bump("constText"); return `const ${ty} ${r}`; });
191 text = text.replace(new RegExp(`(funcPtr\\) \\()(${ty} \\*)`, "g"), "$1const $2");
192 }
193 // (b) strcpy/strcat/wcscpy/wcscat: checked copies that trap (juliet_port.h).
194 // The header also holds the constant flags of (f), so every file includes it.
195 if (/\b(strcpy|strcat|wcscpy|wcscat|strncat|wcsncat|strncpy|wcsncpy)\s*\(/.test(text)) stats.strfns++;
196 text = text.replace(/#include "std_testcase.h"\n/, '#include "std_testcase.h"\n' + (off.has("f") ? "#define JULIET_PORT_NO_CONST_FLAGS\n" : "") + '#include "juliet_port.h"\n');
197 return text;
198}
199const caseCache = new Map<string, string>();
200const stem = (p: string) => p.replace(/(_\d+)[a-z]?\.c$/, "$1");
201function caseOf(p: string): string {
202 const k = stem(p);
203 let t = caseCache.get(k);
204 if (t === undefined) {
205 t = "abcde".split("").map(x => k + x + ".c").concat(k + ".c").filter(f => existsSync(f))
206 .map(f => readFileSync(f, "utf8").replace(/\r\n/g, "\n").replace(/ *\/\*[\s\S]*?\*\//g, "")).join("\n");
207 caseCache.set(k, t);
208 }
209 return t;
210}
211for (const d of readdirSync(TC)) {
212 if (!cwes.some(c => d.startsWith(`CWE${c}_`))) continue;
213 const walk = (dir: string) => {
214 for (const e of readdirSync(dir)) {
215 const p = join(dir, e), rel = p.slice(TC.length + 1), o = join(OTC, rel);
216 if (statSync(p).isDirectory()) { walk(p); continue; }
217 mkdirSync(dirname(o), { recursive: true });
218 if (p.endsWith(".c")) { stats.files++; writeFileSync(o, port(readFileSync(p, "utf8"), p, caseOf(p))); }
219 else cpSync(p, o);
220 }
221 };
222 walk(join(TC, d));
223}
224console.log(JSON.stringify(stats));
225