interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tests / osh / test_osh_lex.c

990 lines · 46308 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * test_osh_lex.c -- host driver for the osh lexer unit (src/osh/osh_lex.osc), aien-architecture#158 cut 4a.
19 *
20 * Compiles osh_lex.osc, then runs lex_run in the reference interpreter AND as native AArch64, with exact-size
21 * heap buffers for the input and the workspace (under ASan every out-of-range byte is a report), against:
22 * - the independent C reference tokenizer (src/osh/osh_lex_ref.c), token for token;
23 * - itself, with the input fed in random chunk splits (resumption), whole workspace byte for byte;
24 * - the lexer-level conformance vectors (aien-protocols specs/osh-platform/vectors, vendored in
25 * tests/osh/vectors);
26 * - a table of hostile cases and a fixed-seed byte/fragment fuzz.
27 * Usage: test_osh_lex OSH_LEX_OSC VECTORS_DIR [FUZZ_COUNT]
28 * Final line: OSH_LEX_PASS or OSH_LEX_FAIL.
29 */
30#include <stdarg.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34
35#include "osc_cg.h"
36#include "osc_front.h"
37#include "osc_interp.h"
38#include "osc_native.h"
39#include "osc_rt.h"
40#include "osh_layout.h"
41#include "osh_lex_ref.h"
42
43#define WS ((size_t)OSH_WS_CELLS)
44
45static unsigned long n_checks, n_fail;
46static unsigned long n_interp_calls, n_native_calls;
47static unsigned long n_cases, n_ref_cmp, n_ref_tok, n_chunk_runs, n_engine_cmp, n_traps;
48static unsigned long n_vec, n_vec_lex, n_hostile, n_fuzz, n_abi, n_bvec;
49static unsigned long n_status[4]; /* fuzz outcomes: done, more, refused, other */
50static unsigned long n_code[256];
51
52static void check(int cond, const char *fmt, ...)
53{
54 n_checks++;
55 if (cond) return;
56 n_fail++;
57 if (n_fail <= 40) {
58 va_list ap;
59 va_start(ap, fmt);
60 fprintf(stderr, "FAIL: ");
61 vfprintf(stderr, fmt, ap);
62 fprintf(stderr, "\n");
63 va_end(ap);
64 }
65}
66
67/* ---- the unit ---- */
68static OscUnit *U;
69static OscRt *RI, *RN;
70static OscCode CODE;
71static OscNative NM;
72static int FI = -1;
73static void *ENTRY;
74
75typedef enum { INTERP = 0, NATIVE = 1 } Engine;
76
77/* a session: an exact-size workspace */
78typedef struct {
79 uint64_t *w;
80} Sess;
81
82static void sess_init(Sess *s)
83{
84 s->w = calloc(WS, sizeof(uint64_t));
85 if (!s->w) { fprintf(stderr, "oom\n"); exit(2); }
86 s->w[OSH_S_MAGIC] = OSH_ABI_MAGIC;
87 s->w[OSH_S_VERSION] = OSH_ABI_VERSION;
88 s->w[OSH_S_WS_CELLS] = OSH_WS_CELLS;
89}
90
91static void sess_free(Sess *s) { free(s->w); s->w = NULL; }
92
93/* one lex_run call on an exact-size copy of data[0..len): the return value, or ~0 on a trap */
94static uint64_t call_raw(Engine e, uint64_t *w, size_t wn, const uint8_t *data, size_t len)
95{
96 uint8_t *b = NULL;
97 if (len) {
98 b = malloc(len);
99 if (!b) { fprintf(stderr, "oom\n"); exit(2); }
100 memcpy(b, data, len);
101 }
102 uint64_t args[4] = { (uint64_t)(uintptr_t)b, len, (uint64_t)(uintptr_t)w, wn };
103 uint64_t ret = 0;
104 int trap;
105 check(osc_ir_slice_args_ok(&U->funcs[FI], args, 4) == 0, "host entry refused valid buffers");
106 if (e == INTERP) {
107 osc_rt_reset(RI);
108 trap = osc_interp_run_prevalidated(U, FI, args, 4, RI, &ret);
109 n_interp_calls++;
110 } else {
111 osc_rt_reset(RN);
112 trap = osc_native_call(U, FI, &NM, CODE.entry[FI], RN, args, 4, &ret);
113 n_native_calls++;
114 }
115 free(b);
116 if (trap != 0) {
117 n_traps++;
118 check(0, "%s trap %d (len %zu)", e == INTERP ? "interp" : "native", trap, len);
119 return ~0ULL;
120 }
121 return ret;
122}
123
124static uint64_t call(Engine e, Sess *s, const uint8_t *data, size_t len)
125{
126 return call_raw(e, s->w, WS, data, len);
127}
128
129/* run to completion over the whole buffer (101 repeats with no new input); returns the final status */
130static uint64_t lex_all(Engine e, Sess *s, const uint8_t *d, size_t n, unsigned *resumes)
131{
132 unsigned r = 0;
133 for (;;) {
134 uint64_t st = call(e, s, d, n);
135 if (st == 101) {
136 r++;
137 if (r > 8) { check(0, "more than 8 budget resumes for %zu bytes", n); break; }
138 continue;
139 }
140 if (resumes) *resumes = r;
141 return st;
142 }
143 if (resumes) *resumes = r;
144 return ~0ULL;
145}
146
147/* feed d[0..n) in the given chunk pattern: mode 0 one byte, 1 random 1..16, 2 random up to the rest.
148 * Returns the final status (the status of the last call). */
149static uint64_t lex_chunked(Engine e, Sess *s, const uint8_t *d, size_t n, unsigned mode, uint64_t *rng,
150 uint64_t (*rnd)(uint64_t *))
151{
152 size_t cur = 0;
153 uint64_t st = 0;
154 if (n == 0) return lex_all(e, s, d, 0, NULL);
155 while (cur < n) {
156 size_t ch = 1;
157 if (mode == 1) ch = 1 + rnd(rng) % 16;
158 else if (mode == 2) ch = 1 + rnd(rng) % (n - cur);
159 if (ch > n - cur) ch = n - cur;
160 cur += ch;
161 st = lex_all(e, s, d, cur, NULL);
162 n_chunk_runs++;
163 if (st >= 200) break; /* terminal: the host stops feeding */
164 }
165 return st;
166}
167
168static uint64_t rng_next(uint64_t *s)
169{
170 uint64_t x = *s;
171 x ^= x >> 12;
172 x ^= x << 25;
173 x ^= x >> 27;
174 *s = x;
175 return x * 0x2545F4914F6CDD1DULL;
176}
177
178/* ---- comparison against the reference ---- */
179static void cmp_ref(const char *tag, const uint8_t *d, size_t n, int eoi, const Sess *s, uint64_t st)
180{
181 OshRefLex *r = malloc(sizeof *r);
182 osh_lex_ref(d, n, eoi, r);
183 n_ref_cmp++;
184 const uint64_t *w = s->w;
185 int ok = 1;
186 if (st != r->status) ok = 0;
187 if (w[OSH_LX_NTOK] != r->ntok) ok = 0;
188 if (r->status >= 200) {
189 if (w[OSH_S_ERR_CODE] != r->status || w[OSH_S_ERR_OFF] != r->err_off || w[OSH_S_PHASE] != 255) ok = 0;
190 } else if (w[OSH_S_PHASE] != 0 || (w[OSH_S_CURSOR] != n && !(st == 100 && n > 0 && d[n - 1] == 0x5c && w[OSH_S_CURSOR] == n - 1))) {
191 ok = 0;
192 }
193 unsigned m = r->ntok < w[OSH_LX_NTOK] ? r->ntok : (unsigned)w[OSH_LX_NTOK];
194 if (m > OSH_REF_TOKEN_CAP) m = OSH_REF_TOKEN_CAP;
195 for (unsigned t = 0; t < m && ok; t++) {
196 const uint64_t *c = &w[OSH_TOKENS + 4 * t];
197 const OshRefTok *k = &r->tok[t];
198 n_ref_tok++;
199 uint64_t hdr = k->kind | (k->flags << 8) | (k->nseg << 24) | (k->line << 32);
200 if (c[0] != hdr || c[1] != k->start || c[2] != k->len || c[3] != k->aux) ok = 0;
201 }
202 if (!ok) {
203 fprintf(stderr, " ref mismatch [%s] len %zu: osc status %llu ntok %llu err %llu@%llu | ref status %u ntok %u err@%llu\n input:",
204 tag, n, (unsigned long long)st, (unsigned long long)w[OSH_LX_NTOK], (unsigned long long)w[OSH_S_ERR_CODE],
205 (unsigned long long)w[OSH_S_ERR_OFF], r->status, r->ntok, (unsigned long long)r->err_off);
206 for (size_t q = 0; q < n && q < 100; q++) fprintf(stderr, " %02x", d[q]);
207 fprintf(stderr, "\n");
208 for (unsigned t = 0; t < m; t++) {
209 const uint64_t *c = &w[OSH_TOKENS + 4 * t];
210 const OshRefTok *k = &r->tok[t];
211 uint64_t hdr = k->kind | (k->flags << 8) | (k->nseg << 24) | (k->line << 32);
212 if (c[0] != hdr || c[1] != k->start || c[2] != k->len || c[3] != k->aux) {
213 fprintf(stderr, " tok %u osc %llx %llu %llu %llu | ref %llx %llu %llu %llu\n", t, (unsigned long long)c[0],
214 (unsigned long long)c[1], (unsigned long long)c[2], (unsigned long long)c[3], (unsigned long long)hdr,
215 (unsigned long long)k->start, (unsigned long long)k->len, (unsigned long long)k->aux);
216 break;
217 }
218 }
219 }
220 check(ok, "reference mismatch [%s]", tag);
221 free(r);
222}
223
224/* One input through everything. Returns the single-shot interpreter status; sess_out receives its workspace
225 * when non-NULL (caller frees). */
226typedef struct {
227 uint64_t status;
228 unsigned resumes;
229 uint64_t err_off;
230 uint64_t ntok;
231 uint64_t w[OSH_LX_MID + 1];
232} Outcome;
233
234static void run_one(const char *tag, const uint8_t *d, size_t n, int eoi, uint64_t *rng, unsigned long iter, Outcome *out)
235{
236 Sess a, b, c, e;
237 unsigned ra = 0, rb = 0;
238 sess_init(&a);
239 sess_init(&b);
240 a.w[OSH_S_EOI] = (uint64_t)eoi;
241 b.w[OSH_S_EOI] = (uint64_t)eoi;
242 uint64_t sa = lex_all(INTERP, &a, d, n, &ra);
243 uint64_t sb = lex_all(NATIVE, &b, d, n, &rb);
244 n_cases++;
245 n_engine_cmp++;
246 check(sa == sb && ra == rb && memcmp(a.w, b.w, WS * 8) == 0, "[%s] interp and native disagree (status %llu vs %llu, resumes %u vs %u, workspace %s)", tag,
247 (unsigned long long)sa, (unsigned long long)sb, ra, rb, memcmp(a.w, b.w, WS * 8) == 0 ? "same" : "differs");
248 cmp_ref(tag, d, n, eoi, &a, sa);
249 /* idempotence of a settled call */
250 if (sa == 0 || sa == 100 || sa >= 200) {
251 uint64_t sn = call(INTERP, &a, d, n);
252 uint64_t *snap = malloc(WS * 8);
253 memcpy(snap, a.w, WS * 8);
254 uint64_t sn2 = call(INTERP, &a, d, n);
255 check(sn == sa && sn2 == sa && memcmp(snap, a.w, WS * 8) == 0, "[%s] repeated call changed the outcome", tag);
256 free(snap);
257 }
258 /* chunked resumption, alternating the engine */
259 unsigned mode = (unsigned)(rng_next(rng) % 3);
260 if (mode == 0 && n > 48) mode = 1;
261 Engine ce = (iter & 1) ? INTERP : NATIVE;
262 sess_init(&c);
263 uint64_t sc = lex_chunked(ce, &c, d, n, mode, rng, rng_next);
264 if (eoi) {
265 c.w[OSH_S_EOI] = 1;
266 sc = lex_all(ce, &c, d, n, NULL);
267 }
268 check(sc == sa && memcmp(a.w, c.w, WS * 8) == 0, "[%s] chunked (mode %u) run differs from single shot (status %llu vs %llu)", tag, mode,
269 (unsigned long long)sc, (unsigned long long)sa);
270 if ((iter & 7) == 0) {
271 sess_init(&e);
272 uint64_t se = lex_chunked(ce == INTERP ? NATIVE : INTERP, &e, d, n, 1, rng, rng_next);
273 if (eoi) {
274 e.w[OSH_S_EOI] = 1;
275 se = lex_all(ce == INTERP ? NATIVE : INTERP, &e, d, n, NULL);
276 }
277 check(se == sa && memcmp(a.w, e.w, WS * 8) == 0, "[%s] chunked run on the other engine differs", tag);
278 sess_free(&e);
279 }
280 if (out) {
281 out->status = sa;
282 out->resumes = ra;
283 out->err_off = a.w[OSH_S_ERR_OFF];
284 out->ntok = a.w[OSH_LX_NTOK];
285 memcpy(out->w, a.w, sizeof out->w);
286 }
287 sess_free(&a);
288 sess_free(&b);
289 sess_free(&c);
290}
291
292/* each input with the end-of-input flag clear (the outcome returned) and then set */
293static void run_all(const char *tag, const uint8_t *d, size_t n, uint64_t *rng, unsigned long iter, Outcome *out)
294{
295 run_one(tag, d, n, 0, rng, iter, out);
296 run_one(tag, d, n, 1, rng, iter, NULL);
297}
298
299/* ---- hostile cases ---- */
300typedef struct {
301 const char *name;
302 const char *in;
303 size_t len;
304 uint64_t status;
305 uint64_t off; /* refusals only */
306 int ntok; /* -1 = do not check */
307} Hostile;
308
309#define H(name, s, status, off, ntok) { name, s, sizeof(s) - 1, status, off, ntok }
310
311static const Hostile HOSTILE[] = {
312 H("empty", "", 0, 0, 0),
313 H("only newline", "\n", 0, 0, 1),
314 H("only spaces and newline", " \t \n", 0, 0, 1),
315 H("only spaces no newline", " ", 100, 0, 0),
316 H("one word no newline", "ls", 100, 0, 0),
317 H("simple", "ls -l /tmp\n", 0, 0, 4),
318 H("unterminated double quote", "echo \"abc", 100, 0, 1),
319 H("unterminated double quote then newline", "echo \"abc\n", 100, 0, 1),
320 H("unterminated single quote", "echo 'abc\n", 100, 0, -1),
321 H("open brace parameter", "echo ${A", 100, 0, -1),
322 H("dollar at end", "echo $", 100, 0, -1),
323 H("operator at end", "a |", 100, 0, -1),
324 H("backslash at end", "echo a\\", 100, 0, -1),
325 H("backslash newline pending", "echo a\\\n", 100, 0, -1),
326 H("backslash newline at command start", "\\\n", 100, 0, 0),
327 H("continuation joins a word", "echo a\\\nb\n", 0, 0, 3),
328 H("continuation between words", "echo \\\n-l\n", 0, 0, 3),
329 H("comment", "ls # comment $(x) `y`\n", 0, 0, 2),
330 H("comment without newline", "ls # c", 100, 0, -1),
331 H("hash inside a word", "echo a#b\n", 0, 0, 3),
332 H("quoted newline", "echo 'a\nb'\n", 0, 0, 3),
333 H("invalid utf-8 passes through", "echo \xff\xfe\x80\xc0\n", 0, 0, 3),
334 H("cr is an ordinary byte", "echo a\r\n", 0, 0, 3),
335 H("glob inside double quotes", "echo \"*.c\"\n", 0, 0, 3),
336 H("glob inside single quotes", "echo '*.c' '?' '['\n", 0, 0, 5),
337 H("tilde inside a word", "echo a~b\n", 0, 0, 3),
338 H("tilde in quotes", "echo \"~\" '~'\n", 0, 0, 4),
339 H("dollar before blank", "echo $ x\n", 0, 0, 4),
340 H("dollar in double quotes at end of quote", "echo \"$\"\n", 0, 0, 3),
341 H("brace name", "echo \"a${B}c\" $1 $10 $_a $# $@ $* $?\n", 0, 0, 10),
342 H("dollar underscore is the last-argument parameter", "echo $_\n", 225, 6, -1),
343 H("dollar underscore name goes on", "echo $_9 $__ ${_a} ${_}x\n", 225, 21, -1),
344 H("append assignment", "echo x+=1\n", 249, 7, -1),
345 H("plus not after a name", "echo 1+=1 +=1 a-b+=1 x++=1 x+y=1\n", 0, 0, 7),
346 H("assignment words", "x=1 y=\"2 3\"\n", 0, 0, 3),
347 H("every operator", "a|b||c&&d;e<f>g>>h>&i<&j\n", 0, 0, 20),
348 H("io numbers", "ls nofile >o 2>&1\n", 0, 0, 7),
349 H("io number input and append", "cat 0<f 1>>g\n", 0, 0, 6),
350 H("digit word with space is an argument", "echo 2 >f\n", 0, 0, 5),
351 H("digit word touching a pipe is a word", "echo 2|cat\n", 0, 0, 5),
352 H("name digit word touching redirect", "echo a2>f\n", 0, 0, 5),
353 H("4096 byte line", "", 0, 0, -1), /* replaced at run time */
354 H("backtick", "echo `x`\n", 221, 5, -1),
355 H("backtick in double quotes", "echo \"`x`\"\n", 221, 6, -1),
356 H("command substitution", "echo $(x)\n", 226, 6, -1),
357 H("command substitution in double quotes", "echo \"x $(y)\"\n", 226, 9, -1),
358 H("arithmetic", "echo $((1+2))\n", 226, 6, -1),
359 H("glob star", "echo *.c\n", 222, 5, -1),
360 H("glob question", "echo a?b\n", 222, 6, -1),
361 H("glob bracket", "echo [a]\n", 222, 5, -1),
362 H("leading tilde", "~/x\n", 223, 0, -1),
363 H("tilde after redirect", "cat >~/x\n", 223, 5, -1),
364 H("tilde after assignment equals", "A=~/x\n", 223, 2, -1),
365 H("tilde after assignment colon", "A=b:~\n", 223, 4, -1),
366 H("parameter operator", "echo ${A:-b}\n", 224, 8, -1),
367 H("empty braces", "echo ${}\n", 224, 7, -1),
368 H("braces newline", "echo ${A\n", 224, 8, -1),
369 H("special parameter dollar", "echo $$\n", 225, 6, -1),
370 H("special parameter bang", "echo $!\n", 225, 6, -1),
371 H("special parameter dash", "echo $-\n", 225, 6, -1),
372 H("ansi-c quoting", "echo $'x'\n", 225, 6, -1),
373 H("locale quoting", "echo $\"x\"\n", 225, 6, -1),
374 H("background", "a & b\n", 227, 2, -1),
375 H("background at end of line", "a &\n", 227, 2, -1),
376 H("ampersand redirect", "a &> f\n", 227, 2, -1),
377 H("pipe ampersand", "a |& b\n", 227, 3, -1),
378 H("subshell open", "(a)\n", 228, 0, -1),
379 H("subshell close", "a )\n", 228, 2, -1),
380 H("process substitution", "cat <(x)\n", 228, 5, -1),
381 H("here document", "cat <<E\n", 229, 5, -1),
382 H("here string", "cat <<<x\n", 229, 5, -1),
383 H("case end", "a;;b\n", 230, 2, -1),
384 H("clobber redirect", "a >| f\n", 231, 3, -1),
385 H("read write redirect", "a <> f\n", 231, 3, -1),
386 H("fd range single digit", "echo 5>f\n", 232, 6, -1),
387 H("fd range two digits", "echo 12>f\n", 232, 7, -1),
388 H("fd range input", "echo 3<f\n", 232, 6, -1),
389 H("nul at start", "\0", 220, 0, -1),
390 H("nul in word", "echo a\0b\n", 220, 6, -1),
391 H("nul in single quotes", "echo 'a\0b'\n", 220, 7, -1),
392 H("nul in double quotes", "echo \"a\0b\"\n", 220, 7, -1),
393 H("nul in comment", "# c\0\n", 220, 3, -1),
394 H("nul after backslash", "a\\\0", 220, 2, -1),
395 H("nul after operator", "a |\0", 220, 3, -1),
396 H("nul after dollar", "echo $\0", 220, 6, -1),
397 H("nul in braces", "echo ${A\0}\n", 220, 8, -1),
398 H("nul after word before newline", "echo a\0\n", 220, 6, -1),
399 H("brace expansion list", "echo {a,b}\n", 246, 9, -1),
400 H("brace expansion sequence", "echo {1..3}\n", 246, 10, -1),
401 H("brace expansion char sequence", "echo {a..c}\n", 246, 10, -1),
402 H("brace expansion with prefix and suffix", "echo a{b,c}d\n", 246, 10, -1),
403 H("brace expansion empty items", "echo {,}\n", 246, 7, -1),
404 H("brace expansion after assignment equals", "echo x={a,b}\n", 246, 11, -1),
405 H("brace expansion with a quoted item", "echo {a,\"b\"}\n", 246, 11, -1),
406 H("brace expansion nested outer", "echo {{a},b}\n", 246, 11, -1),
407 H("brace expansion nested inner", "echo {{a,b}\n", 246, 10, -1),
408 H("brace expansion at command start", "{a,b}\n", 246, 4, -1),
409 H("brace expansion is decided before a later glob", "echo {a,b}*\n", 246, 9, -1),
410 H("glob before a brace expansion", "echo *{a,b}\n", 222, 5, -1),
411 H("lone open brace stays literal", "echo {\n", 0, 0, 3),
412 H("lone close brace stays literal", "echo }\n", 0, 0, 3),
413 H("braces around a blank stay literal", "echo { } {} }{\n", 0, 0, 6),
414 H("unclosed brace with comma stays literal", "echo {a,b\n", 0, 0, 3),
415 H("closing brace without opening stays literal", "echo a,b}\n", 0, 0, 3),
416 H("braces without comma or dots stay literal", "echo {a} {a.b} {1.2} a{b}c\n", 0, 0, 6),
417 H("quoted brace expansion stays literal", "echo '{a,b}' \"{a,b}\" {\"a,b\"} {'1..3'}\n", 0, 0, 6),
418 H("escaped brace expansion stays literal", "echo \\{a,b\\} {a\\,b} {1.\\.3}\n", 0, 0, 5),
419 H("parameter braces are not brace expansion", "echo ${A},{b} ${A}{b}\n", 0, 0, 4),
420 H("dollar before a brace pair", "echo $,{b}\n", 0, 0, 3),
421 H("lone group open at command start", "{ echo hi; }\n", 236, 0, -1),
422 H("lone group close after semicolon", "echo hi; }\n", 236, 9, -1),
423 H("group after and", "a && { b; }\n", 236, 5, -1),
424 H("group after pipe", "a | }\n", 236, 4, -1),
425 H("group after newline", "a\n{\n", 236, 2, -1),
426 H("group with continuation", "{\\\n x\n", 236, 0, -1),
427 H("group as an argument is a word", "echo {\n", 0, 0, 3),
428 H("group after an assignment is a word", "A=1 {\n", 0, 0, 3),
429 H("group-like word", "{a }b\n", 0, 0, 3),
430 H("quoted group is a word", "'{' x\n", 0, 0, 3),
431 H("escaped group is a word", "\\{ x\n", 0, 0, 3),
432 H("group open pending", "{", 100, 0, -1),
433 H("group before subshell paren", "{(\n", 236, 0, -1),
434 H("positional ten", "echo ${10}\n", 247, 8, -1),
435 H("positional double zero", "echo ${00}\n", 247, 8, -1),
436 H("positional in double quotes", "echo \"${10}\"\n", 247, 9, -1),
437 H("positional decided at the second digit", "echo ${12", 247, 8, -1),
438 H("positional digit then letter", "echo ${1a}\n", 224, 8, -1),
439 H("positional single digits", "echo ${1}${0}${9}\n", 0, 0, 3),
440 H("name with digits", "echo ${a1} ${a12} ${_9}\n", 0, 0, 5),
441};
442
443static void run_hostile(uint64_t *rng)
444{
445 for (size_t h = 0; h < sizeof HOSTILE / sizeof HOSTILE[0]; h++) {
446 const Hostile *c = &HOSTILE[h];
447 const uint8_t *d = (const uint8_t *)c->in;
448 size_t n = c->len;
449 uint8_t *big = NULL;
450 uint64_t status = c->status, off = c->off;
451 int ntok = c->ntok;
452 if (strcmp(c->name, "4096 byte line") == 0) {
453 n = 4096;
454 big = malloc(n);
455 memset(big, 'a', n);
456 memcpy(big, "echo ", 5);
457 big[n - 1] = '\n';
458 d = big;
459 status = 0;
460 ntok = 3;
461 }
462 Outcome o;
463 run_all(c->name, d, n, rng, h, &o);
464 n_hostile++;
465 check(o.status == status, "hostile '%s': status %llu, want %llu", c->name, (unsigned long long)o.status, (unsigned long long)status);
466 if (status >= 200) check(o.err_off == off, "hostile '%s': offset %llu, want %llu", c->name, (unsigned long long)o.err_off, (unsigned long long)off);
467 if (ntok >= 0 && status < 200) check(o.ntok == (uint64_t)ntok, "hostile '%s': %llu tokens, want %d", c->name, (unsigned long long)o.ntok, ntok);
468 free(big);
469 }
470 /* sizes around the line cap and the token cap */
471 for (int variant = 0; variant < 12; variant++) {
472 size_t n = 0;
473 uint8_t *b = NULL;
474 uint64_t want = 0, want_off = 0;
475 const char *nm = "";
476 switch (variant) {
477 case 0: nm = "4097 byte line"; n = 4097; b = malloc(n); memset(b, 'a', n); b[n - 1] = '\n'; want = 201; want_off = 4096; break;
478 case 1: nm = "5000 byte word"; n = 5000; b = malloc(n); memset(b, 'a', n); want = 201; want_off = 4096; break;
479 case 2: nm = "4096 bytes no newline"; n = 4096; b = malloc(n); memset(b, 'a', n); want = 100; break;
480 case 3: nm = "4096 spaces then more"; n = 4097; b = malloc(n); memset(b, ' ', n); want = 201; want_off = 4096; break;
481 case 4: nm = "refusal before the line cap wins"; n = 6000; b = malloc(n); memset(b, 'a', n); memcpy(b + 10, "$(", 2); want = 226; want_off = 11; break;
482 case 5: nm = "127 words and newline"; n = 254; b = malloc(n); for (size_t q = 0; q < 126; q++) { b[2 * q] = 'a'; b[2 * q + 1] = ' '; } b[252] = 'a'; b[253] = '\n'; want = 0; break;
483 case 6: nm = "128 words and newline (129 tokens)"; n = 128 * 2 + 1; b = malloc(n); for (size_t q = 0; q < 128; q++) { b[2 * q] = 'a'; b[2 * q + 1] = ' '; } b[256] = '\n'; want = 202; want_off = 256; break;
484 case 7: nm = "129th word"; n = 129 * 2 + 1; b = malloc(n); for (size_t q = 0; q < 129; q++) { b[2 * q] = 'a'; b[2 * q + 1] = ' '; } b[258] = '\n'; want = 202; want_off = 256; break;
485 case 8: nm = "64 words and semicolons"; n = 129; b = malloc(n); for (size_t q = 0; q < 64; q++) { b[2 * q] = 'a'; b[2 * q + 1] = ';'; } b[128] = '\n'; want = 202; want_off = 128; break;
486 case 9: nm = "129 newlines"; n = 129; b = malloc(n); memset(b, '\n', n); want = 202; want_off = 128; break;
487 case 10: nm = "digit word merge at full table"; n = 127 * 2 + 3; b = malloc(n); for (size_t q = 0; q < 127; q++) { b[2 * q] = 'a'; b[2 * q + 1] = ' '; } memcpy(b + 254, "2>\n", 3); want = 202; want_off = 256; break;
488 default: nm = "many redirects"; n = 3 * 40 + 1; b = malloc(n); for (size_t q = 0; q < 40; q++) memcpy(b + 3 * q, "2>f", 3); b[3 * 40] = '\n'; want = 0; break;
489 }
490 /* variant 8: semicolons are tokens too: token 129 is the 129th byte (index 128)? 128 tokens fill the table, the NL is the 129th */
491 if (variant == 8) want_off = 128;
492 if (variant == 10) { want = 0; } /* 127 words + "2>" merges into the 128th slot? see below */
493 Outcome o;
494 run_all(nm, b, n, rng, 100 + (unsigned long)variant, &o);
495 n_hostile++;
496 if (variant == 10) {
497 /* 127 words, then `2` is word 128, `>` merges into it, NL is token 129 */
498 want = 202;
499 want_off = 256;
500 }
501 check(o.status == want, "hostile '%s': status %llu, want %llu", nm, (unsigned long long)o.status, (unsigned long long)want);
502 if (want >= 200) check(o.err_off == want_off, "hostile '%s': offset %llu, want %llu", nm, (unsigned long long)o.err_off, (unsigned long long)want_off);
503 free(b);
504 }
505}
506
507static void run_brace_depth(uint64_t *rng)
508{
509 /* 62 nested braces with no comma are literal; the 63rd open brace is refused (the detector's depth cap) */
510 for (int open = 61; open <= 64; open++) {
511 uint8_t b[256];
512 size_t n = 0;
513 memcpy(b, "echo ", 5); n = 5;
514 for (int q = 0; q < open; q++) b[n++] = '{';
515 if (open <= 62) for (int q = 0; q < open; q++) b[n++] = '}';
516 b[n++] = '\n';
517 Outcome o;
518 run_all("brace depth", b, n, rng, 300 + (unsigned long)open, &o);
519 n_hostile++;
520 if (open <= 62) check(o.status == 0, "brace depth %d: status %llu", open, (unsigned long long)o.status);
521 else check(o.status == 246 && o.err_off == 67, "brace depth %d: %llu@%llu", open, (unsigned long long)o.status, (unsigned long long)o.err_off);
522 }
523}
524
525/* ---- end of input (S_EOI = 1): the pending word or operator is finished, an open construct is SYNTAX_EOF ---- */
526static void run_eoi_cases(uint64_t *rng)
527{
528 static const struct { const char *in; size_t n; uint64_t status; uint64_t off; int ntok; } T[] = {
529 { "ls", 2, 0, 0, 1 }, { "ls -l", 5, 0, 0, 2 }, { "ls ", 3, 0, 0, 1 }, { " ", 3, 0, 0, 0 }, { "", 0, 0, 0, 0 },
530 { "ls\n", 3, 0, 0, 2 }, { "# c", 3, 0, 0, 0 }, { "ls # c", 6, 0, 0, 1 }, { "a |", 3, 0, 0, 2 }, { "a ||", 4, 0, 0, 2 },
531 { "a &&", 4, 0, 0, 2 }, { "a ;", 3, 0, 0, 2 }, { "a <", 3, 0, 0, 2 }, { "a >", 3, 0, 0, 2 }, { "a >>", 4, 0, 0, 2 },
532 { "a >&", 4, 0, 0, 2 }, { "a 2>", 4, 0, 0, 2 }, { "a 2>&", 5, 0, 0, 2 }, { "echo $", 6, 0, 0, 2 }, { "echo a$", 7, 0, 0, 2 },
533 { "echo \"$", 7, 248, 7, -1 }, { "echo \"abc", 9, 248, 9, -1 }, { "echo 'abc", 9, 248, 9, -1 }, { "echo a\\", 7, 0, 0, 2 }, { "echo a|\\", 8, 0, 0, 4 }, { "echo a\\\n\\", 9, 0, 0, 2 }, { "echo $_", 7, 225, 6, -1 }, { "echo x+=", 8, 249, 7, -1 },
534 { "\\", 1, 0, 0, 1 }, { "\\\\", 2, 0, 0, 1 }, { "echo ${A", 8, 248, 8, -1 }, { "echo \"${A", 9, 248, 9, -1 }, { "echo \"a\\", 8, 248, 8, -1 },
535 { "a &", 3, 227, 2, -1 }, { "a (", 3, 228, 2, -1 }, { "a ~", 3, 223, 2, -1 }, { "a *", 3, 222, 2, -1 }, { "a `", 3, 221, 2, -1 },
536 { "a $(", 4, 226, 3, -1 }, { "a {", 3, 0, 0, 2 }, { "{", 1, 236, 0, -1 }, { "a ;;", 4, 230, 3, -1 }, { "echo a\\\n", 8, 0, 0, 2 },
537 };
538 for (size_t t = 0; t < sizeof T / sizeof T[0]; t++) {
539 Outcome o;
540 run_one("eoi case", (const uint8_t *)T[t].in, T[t].n, 1, rng, 700 + t, &o);
541 n_hostile++;
542 check(o.status == T[t].status, "eoi case %zu: status %llu, want %llu", t, (unsigned long long)o.status, (unsigned long long)T[t].status);
543 if (T[t].status >= 200) check(o.err_off == T[t].off, "eoi case %zu: offset %llu, want %llu", t, (unsigned long long)o.err_off, (unsigned long long)T[t].off);
544 else check(o.ntok == (uint64_t)T[t].ntok, "eoi case %zu: %llu tokens, want %d", t, (unsigned long long)o.ntok, T[t].ntok);
545 }
546 /* the flag above 1 is refused, and the done flag the parser relies on follows the status */
547 Sess s;
548 sess_init(&s);
549 s.w[OSH_S_EOI] = 2;
550 check(call(INTERP, &s, (const uint8_t *)"ls\n", 3) == 217 && s.w[OSH_LX_DONE] == 0, "eoi flag 2 is ABI_RESERVED");
551 s.w[OSH_S_EOI] = 0;
552 check(call(INTERP, &s, (const uint8_t *)"ls", 2) == 100 && s.w[OSH_LX_DONE] == 0, "pending word: not done");
553 check(call(INTERP, &s, (const uint8_t *)"ls\n", 3) == 0 && s.w[OSH_LX_DONE] == 1, "line complete: done");
554 check(call(INTERP, &s, (const uint8_t *)"ls\nb", 4) == 100 && s.w[OSH_LX_DONE] == 0, "new pending word: not done again");
555 s.w[OSH_S_EOI] = 1;
556 check(call(INTERP, &s, (const uint8_t *)"ls\nb", 4) == 0 && s.w[OSH_LX_DONE] == 1 && s.w[OSH_LX_NTOK] == 3, "flag flushes the word");
557 sess_free(&s);
558}
559
560/* ---- ABI header refusals ---- */
561static void run_abi(void)
562{
563 const uint8_t in[] = "ls\n";
564 static const struct { const char *name; size_t cells; int what; uint64_t want; } T[] = {
565 { "no header", 0, 0, 216 },
566 { "one cell", 1, 0, 216 },
567 { "bad magic", OSH_WS_CELLS, 1, 214 },
568 { "bad version", OSH_WS_CELLS, 2, 215 },
569 { "short workspace", OSH_WS_CELLS - 1, 0, 213 },
570 { "tiny workspace", 2, 0, 213 },
571 { "reserved cell 48", OSH_WS_CELLS, 3, 217 },
572 { "reserved cell 63", OSH_WS_CELLS, 4, 217 },
573 { "good", OSH_WS_CELLS, 0, 0 },
574 { "bigger workspace is fine", OSH_WS_CELLS + 5, 0, 0 },
575 };
576 for (size_t t = 0; t < sizeof T / sizeof T[0]; t++) {
577 for (int e = 0; e < 2; e++) {
578 size_t nc = T[t].cells;
579 uint64_t *w = NULL;
580 if (nc) {
581 w = calloc(nc, 8);
582 if (nc > 0) w[0] = OSH_ABI_MAGIC;
583 if (nc > 1) w[1] = OSH_ABI_VERSION;
584 if (T[t].what == 1) w[0] ^= 1;
585 if (T[t].what == 2) w[1] = 2;
586 if (T[t].what == 3) w[48] = 1;
587 if (T[t].what == 4) w[63] = 7;
588 }
589 uint64_t *snap = nc ? malloc(nc * 8) : NULL;
590 if (nc) memcpy(snap, w, nc * 8);
591 uint64_t st = call_raw(e ? NATIVE : INTERP, w, nc, in, sizeof in - 1);
592 check(st == T[t].want, "abi '%s': status %llu, want %llu", T[t].name, (unsigned long long)st, (unsigned long long)T[t].want);
593 if (T[t].want >= 213 && T[t].want <= 217 && nc) check(memcmp(snap, w, nc * 8) == 0, "abi '%s': wrote the workspace", T[t].name);
594 n_abi++;
595 free(w);
596 free(snap);
597 }
598 }
599 /* a consumed cursor past the buffer (the host shrank the input) is ABI_LENGTH, nothing written */
600 Sess s;
601 sess_init(&s);
602 s.w[OSH_S_CURSOR] = 9;
603 check(call(INTERP, &s, in, 3) == 216 && s.w[OSH_S_PHASE] == 0, "abi: shrunk input");
604 sess_free(&s);
605 /* a refusal is terminal and repeats */
606 sess_init(&s);
607 const uint8_t bad[] = "echo $(x)\n";
608 check(lex_all(INTERP, &s, bad, sizeof bad - 1, NULL) == 226, "terminal: first");
609 check(call(NATIVE, &s, bad, sizeof bad - 1) == 226 && call(INTERP, &s, (const uint8_t *)"", 0) == 226, "terminal: repeat");
610 sess_free(&s);
611 /* a corrupt lexer state byte is refused, not trapped */
612 sess_init(&s);
613 s.w[OSH_LX_STATE] = 77;
614 check(call(INTERP, &s, in, 3) == 217, "corrupt state is refused");
615 sess_free(&s);
616}
617
618/* ---- conformance vectors (lexer level) ---- */
619static char *slurp(const char *path, size_t *len)
620{
621 FILE *f = fopen(path, "rb");
622 if (!f) return NULL;
623 size_t cap = 4096, n = 0;
624 char *b = malloc(cap);
625 for (;;) {
626 size_t r = fread(b + n, 1, cap - n, f);
627 n += r;
628 if (n < cap) break;
629 cap *= 2;
630 b = realloc(b, cap);
631 }
632 fclose(f);
633 *len = n;
634 return b;
635}
636
637static void run_vectors(const char *dir, uint64_t *rng)
638{
639 char path[1024];
640 snprintf(path, sizeof path, "%s/expected.txt", dir);
641 size_t el;
642 char *exp = slurp(path, &el);
643 check(exp != NULL, "cannot read %s", path);
644 if (!exp) return;
645 exp = realloc(exp, el + 1);
646 exp[el] = 0;
647 for (char *line = strtok(exp, "\n"); line; line = strtok(NULL, "\n")) {
648 if (line[0] != 'v') continue;
649 char name[16];
650 if (sscanf(line, "%15s", name) != 1) continue;
651 snprintf(path, sizeof path, "%s/%s.in", dir, name);
652 size_t n;
653 char *in = slurp(path, &n);
654 check(in != NULL, "cannot read %s", path);
655 if (!in) continue;
656 Outcome o;
657 run_all(name, (const uint8_t *)in, n, rng, n_vec, &o);
658 n_vec++;
659 /* what the lexer owns: refusal codes 201..232; every other line means the lexer finishes the buffer */
660 unsigned code = 0, off = 0;
661 unsigned lex_resumes = 0;
662 int want_resumes = -1;
663 const char *p = strstr(line, " refuse ");
664 if (p) {
665 if (sscanf(p, " refuse %u %*s off=%u", &code, &off) != 2) check(0, "%s: bad refuse line", name);
666 }
667 if ((p = strstr(line, "lex_resumes="))) { lex_resumes = (unsigned)strtoul(p + 12, NULL, 10); want_resumes = (int)lex_resumes; }
668 if (strstr(line, " more")) {
669 check(o.status == 100, "vector %s: status %llu, want 100", name, (unsigned long long)o.status);
670 n_vec_lex++;
671 } else if ((code >= 201 && code <= 232) || code == 236 || code == 246 || code == 247 || code == 249) {
672 check(o.status == code && o.err_off == off, "vector %s: refusal %llu@%llu, want %u@%u", name, (unsigned long long)o.status,
673 (unsigned long long)o.err_off, code, off);
674 n_vec_lex++;
675 } else {
676 check(o.status == 0, "vector %s: status %llu, want 0 (lexer done)", name, (unsigned long long)o.status);
677 n_vec_lex++;
678 }
679 if (want_resumes >= 0) check(o.resumes == (unsigned)want_resumes, "vector %s: %u budget resumes, want %d", name, o.resumes, want_resumes);
680 free(in);
681 }
682 free(exp);
683 check(n_vec >= 20, "only %lu conformance vectors ran (an empty or missing list must fail)", n_vec);
684}
685
686
687/* ---- bash-verified vectors (tests/osh/vectors/bash_vectors.tsv; bash_verify.sh proves them against real bash) ---- */
688/* decode \n \t \\ \xHH; returns the length */
689static size_t unesc(const char *s, size_t sl, char *out)
690{
691 size_t n = 0;
692 for (size_t i = 0; i < sl; i++) {
693 if (s[i] != '\\' || i + 1 >= sl) { out[n++] = s[i]; continue; }
694 i++;
695 if (s[i] == 'n') out[n++] = '\n';
696 else if (s[i] == 't') out[n++] = '\t';
697 else if (s[i] == 'x' && i + 2 < sl + 0) { out[n++] = (char)strtoul((char[]){ s[i + 1], s[i + 2], 0 }, NULL, 16); i += 2; }
698 else out[n++] = s[i];
699 }
700 return n;
701}
702
703/* append the escaped form of byte c (the canonical spelling used in the expect column) */
704static void esc_put(char *o, size_t *n, uint8_t c)
705{
706 if (c == '\\') { o[(*n)++] = '\\'; o[(*n)++] = '\\'; }
707 else if (c == '\n') { o[(*n)++] = '\\'; o[(*n)++] = 'n'; }
708 else if (c == '\t') { o[(*n)++] = '\\'; o[(*n)++] = 't'; }
709 else if (c <= 0x20 || c >= 0x7f) *n += (size_t)sprintf(o + *n, "\\x%02x", c);
710 else o[(*n)++] = (char)c;
711}
712
713/* the bash view of one word: backslash-newline removed, quotes removed */
714static void word_text(const uint8_t *in, size_t s, size_t e, char *o, size_t *n)
715{
716 size_t i = s;
717 while (i < e) {
718 uint8_t c = in[i];
719 if (c == '\\' && i + 1 < e) {
720 if (in[i + 1] == '\n') { i += 2; continue; }
721 esc_put(o, n, in[i + 1]);
722 i += 2;
723 } else if (c == '\'') {
724 i++;
725 while (i < e && in[i] != '\'') esc_put(o, n, in[i++]);
726 i++;
727 } else if (c == '"') {
728 i++;
729 while (i < e && in[i] != '"') {
730 if (in[i] == '\\' && i + 1 < e) {
731 uint8_t d = in[i + 1];
732 if (d == '\n') { i += 2; continue; }
733 if (d == '\\' || d == '"' || d == '$' || d == '`') { esc_put(o, n, d); i += 2; continue; }
734 }
735 esc_put(o, n, in[i++]);
736 }
737 i++;
738 } else {
739 esc_put(o, n, c);
740 i++;
741 }
742 }
743}
744
745/* the lexer result of d as the expect-column text: "ok <tokens>", "more" or "refuse CODE@OFF" */
746static void render(const uint8_t *d, size_t n, char *o, size_t ocap)
747{
748 Sess s;
749 sess_init(&s);
750 uint64_t st = lex_all(INTERP, &s, d, n, NULL);
751 size_t k = 0;
752 static const char *const NAME[] = { "", "W", "PIPE", "OR", "AND", "SEMI", "LT", "GT", "APPEND", "NL", "DUPO", "DUPI" };
753 if (st >= 200) k = (size_t)sprintf(o, "refuse %llu@%llu", (unsigned long long)st, (unsigned long long)s.w[OSH_S_ERR_OFF]);
754 else if (st == 100) k = (size_t)sprintf(o, "more");
755 else {
756 k = (size_t)sprintf(o, "ok");
757 for (uint64_t t = 0; t < s.w[OSH_LX_NTOK] && k + 2048 < ocap; t++) {
758 const uint64_t *c = &s.w[OSH_TOKENS + 4 * t];
759 unsigned kind = (unsigned)(c[0] & 255);
760 o[k++] = ' ';
761 if (kind == 1) {
762 o[k++] = 'W'; o[k++] = ':';
763 word_text(d, c[1], c[1] + c[2], o, &k);
764 } else if (kind >= 2 && kind <= 11) {
765 k += (size_t)sprintf(o + k, "%s", NAME[kind]);
766 if (kind == 6 || kind == 7 || kind == 8 || kind == 10 || kind == 11) k += (size_t)sprintf(o + k, ":%llu", (unsigned long long)c[3]);
767 } else k += (size_t)sprintf(o + k, "?%u", kind);
768 }
769 }
770 o[k] = 0;
771 sess_free(&s);
772}
773
774static void run_bash_vectors(const char *dir, uint64_t *rng)
775{
776 char path[1024];
777 snprintf(path, sizeof path, "%s/bash_vectors.tsv", dir);
778 size_t el;
779 char *txt = slurp(path, &el);
780 check(txt != NULL, "cannot read %s", path);
781 if (!txt) return;
782 txt = realloc(txt, el + 1);
783 txt[el] = 0;
784 char *sp = NULL;
785 for (char *line = strtok_r(txt, "\n", &sp); line; line = strtok_r(NULL, "\n", &sp)) {
786 if (line[0] != 'c') continue;
787 char *f[4] = { 0 };
788 char *p = line;
789 for (int q = 0; q < 4; q++) {
790 f[q] = p;
791 char *t = strchr(p, '\t');
792 if (!t) { if (q < 3) check(0, "bash vector line has %d fields: %.20s", q + 1, line); break; }
793 *t = 0;
794 p = t + 1;
795 }
796 if (!f[3]) continue;
797 char *inb = malloc(strlen(f[1]) + 1), *eqb = malloc(strlen(f[3]) + 1);
798 size_t inl = unesc(f[1], strlen(f[1]), inb);
799 char got[8192], want[8192];
800 /* the expect column keeps its own escapes, so compare against the raw text */
801 snprintf(want, sizeof want, "%s", f[2]);
802 Outcome o;
803 run_all(f[0], (const uint8_t *)inb, inl, rng, n_bvec, &o);
804 render((const uint8_t *)inb, inl, got, sizeof got);
805 n_bvec++;
806 check(strcmp(got, want) == 0, "bash vector %s: got '%s', want '%s'", f[0], got, want);
807 /* the continuation-free form lexes the same way (offsets of a refusal may differ) */
808 if (strcmp(f[3], "-") != 0) {
809 size_t eql = unesc(f[3], strlen(f[3]), eqb);
810 char got2[8192];
811 run_all(f[0], (const uint8_t *)eqb, eql, rng, n_bvec, NULL);
812 render((const uint8_t *)eqb, eql, got2, sizeof got2);
813 if (strncmp(want, "refuse ", 7) == 0) {
814 char *at = strchr(want, '@');
815 check(at && strncmp(got2, want, (size_t)(at - want)) == 0, "bash vector %s: equiv script gave '%s', want the code of '%s'", f[0], got2, want);
816 } else {
817 check(strcmp(got2, want) == 0, "bash vector %s: equiv script gave '%s', want '%s'", f[0], got2, want);
818 }
819 }
820 free(inb);
821 free(eqb);
822 }
823 free(txt);
824}
825
826/* ---- fuzz ---- */
827static const char *FRAG[] = {
828 "ls", "echo", " ", " ", " ", "\t", "\n", "\n", "-l", "/tmp", "a", "b", "x=1", "A=", "_n", "0", "1", "2", "3", "10", "12",
829 "'x y'", "\"a b\"", "\"$B c\"", "\"$(x)\"", "'", "\"", "\\", "\\\n", "\\\"", "\\$", "$", "$1", "$?", "$#", "$@", "$*", "$$", "$!", "$-",
830 "${V}", "${", "}", "${A:-b}", "$(", "$((", ")", "(", "`", "*", "?", "[", "]", "~", "~/x", "{a,b}", "!", "#", "# c\n", "a#b",
831 "|", "||", "&&", "&", ";", ";;", "<", ">", ">>", ">&", "<&", "<<", "<<<", ">|", "<>", "&>", "|&", "2>", "2>&1", "1>>", "0<", "5>", "12>", "<(", ">(",
832 "=", ":", ":~", "\r", "\xff", "\x80", "\xc3\xa9", "\xe2\x82", "\x01", "\x7f",
833 "|\\\n", "2\\\n", "$\\\n", ">\\\n", "&\\\n", "x+=1", "x+", "$_", "${_}", "_", "+", "\\\n#", "~\\\n~",
834 "{1..3}", "${10}", "${1a}", "${0}", "${a1}", "{ }", "{}", ",", ".", "..", "{x}", "a{b,c}d", "x={a,b}", "\\{", "\\,", "{\\\n",
835};
836
837/* fragments that mostly lex clean, so the token records get exercised */
838static const char *SAFE[] = {
839 "ls", "echo", " ", " ", " ", "\t", "\n", "-l", "/tmp", "a", "x=1", "A=", "_n", "0", "1", "2", "10", "{", "}", "{x}", ",", ".", "a.b", "${0}", "\\{", "'x y'", "\"a b\"", "\"$B c\"",
840 "\\\n", "|\\\n", "2\\\n", ">\\\n", "\\\"", "$1", "$?", "$#", "$@", "${V}", "#", "# c\n", "a#b", "|", "||", "&&", ";", "<", ">", ">>", ">&", "<&", "2>", "2>&1", "1>>", "0<", "=", ":", "\xff", "\xc3\xa9",
841};
842
843static size_t gen(uint8_t *buf, size_t cap, uint64_t *rng)
844{
845 size_t n = 0;
846 unsigned mode = (unsigned)(rng_next(rng) % 8);
847 if (mode == 0) { /* raw bytes, any value, NUL included */
848 size_t len = rng_next(rng) % 40;
849 for (size_t i = 0; i < len; i++) buf[n++] = (uint8_t)rng_next(rng);
850 } else if (mode == 1) { /* bytes from a hostile alphabet */
851 static const char AL[] = "ab 1 2\t\n'\"\\$`|&;<>()#{}*?[]~=:!-_\r\x80\xff.,@%^";
852 size_t len = rng_next(rng) % 48;
853 for (size_t i = 0; i < len; i++) buf[n++] = (uint8_t)AL[rng_next(rng) % (sizeof AL - 1)];
854 } else if (mode == 2 || mode == 3) { /* clean fragments */
855 size_t nf = 1 + rng_next(rng) % 30;
856 for (size_t i = 0; i < nf; i++) {
857 const char *f = SAFE[rng_next(rng) % (sizeof SAFE / sizeof SAFE[0])];
858 size_t fl = strlen(f);
859 memcpy(buf + n, f, fl);
860 n += fl;
861 }
862 if (rng_next(rng) % 4 != 0) buf[n++] = '\n';
863 } else { /* fragments */
864 size_t nf = 1 + rng_next(rng) % (mode == 7 ? 120 : 14);
865 for (size_t i = 0; i < nf; i++) {
866 const char *f = FRAG[rng_next(rng) % (sizeof FRAG / sizeof FRAG[0])];
867 size_t fl = strlen(f);
868 if (n + fl > cap) break;
869 memcpy(buf + n, f, fl);
870 n += fl;
871 }
872 if (rng_next(rng) % 4 != 0 && n < cap) buf[n++] = '\n';
873 if (rng_next(rng) % 6 == 0 && n) buf[rng_next(rng) % n] = (uint8_t)rng_next(rng); /* one byte mutation, NUL possible */
874 if (rng_next(rng) % 40 == 0) { /* a very long line */
875 size_t extra = 4000 + rng_next(rng) % 300;
876 if (n + extra < cap) {
877 memset(buf + n, 'a' + (int)(rng_next(rng) % 3), extra);
878 n += extra;
879 buf[n++] = '\n';
880 }
881 }
882 }
883 return n;
884}
885
886static void run_fuzz(unsigned long count, uint64_t *rng)
887{
888 uint8_t *buf = malloc(8192);
889 for (unsigned long i = 0; i < count; i++) {
890 size_t n = gen(buf, 8000, rng);
891 Outcome o;
892 run_all("fuzz", buf, n, rng, i, &o);
893 n_fuzz++;
894 if (o.status == 0) n_status[0]++;
895 else if (o.status == 100) n_status[1]++;
896 else if (o.status >= 200) { n_status[2]++; n_code[o.status & 255]++; }
897 else n_status[3]++;
898 }
899 free(buf);
900}
901
902/* ---- unit statistics ---- */
903static void unit_stats(void)
904{
905 unsigned maxv = 0, maxi = 0;
906 const char *vn = "", *in = "";
907 for (int f = 0; f < U->nfuncs; f++) {
908 const OscFunc *fn = &U->funcs[f];
909 printf("fn %-10s params=%u vregs=%u/%u insns=%u/%u\n", fn->name, fn->nparams, fn->nvregs, OSC_MAX_VREGS, fn->ninsns, OSC_MAX_INSNS);
910 if (fn->nvregs > maxv) { maxv = fn->nvregs; vn = fn->name; }
911 if (fn->ninsns > maxi) { maxi = fn->ninsns; in = fn->name; }
912 check(fn->nparams <= OSC_MAX_PARAMS, "%s has %u param registers", fn->name, fn->nparams);
913 }
914 printf("unit: %u functions (max %u); biggest vregs %s %u (headroom %u of %u); biggest insns %s %u (headroom %u of %u)\n", U->nfuncs,
915 OSC_MAX_FUNCS, vn, maxv, OSC_MAX_VREGS - maxv, OSC_MAX_VREGS, in, maxi, OSC_MAX_INSNS - maxi, OSC_MAX_INSNS);
916 check(U->nfuncs <= OSC_MAX_FUNCS, "too many functions");
917}
918
919int main(int argc, char **argv)
920{
921 if (argc < 3) {
922 fprintf(stderr, "usage: test_osh_lex OSH_LEX_OSC VECTORS_DIR [FUZZ_COUNT]\n");
923 return 2;
924 }
925 unsigned long fuzz = argc > 3 ? strtoul(argv[3], NULL, 10) : 100000;
926 /* the generated layout agrees with the numbers the ABI draft fixes (section 6.1, 6.2) */
927 check(OSH_WS_CELLS == 11456 && OSH_TOKENS == 64 && OSH_CMDS == 576 && OSH_PIPES == 832 && OSH_STAGING == 896 && OSH_REQUEST == 1928 &&
928 OSH_OUT == 3264 && OSH_ABI_MAGIC == 0x4F534857ULL && OSH_S_ERR_CODE == 4 && OSH_S_ERR_OFF == 5 && OSH_S_CURSOR == 6 &&
929 OSH_S_RESERVED == 48 && OSH_TOKEN_CAP == 128 && OSH_LINE_CAP == 4096 && OSH_LEX_BUDGET == 1024,
930 "generated layout differs from the ABI draft numbers");
931 size_t sl;
932 char *src = slurp(argv[1], &sl);
933 if (!src) { fprintf(stderr, "cannot read %s\n", argv[1]); return 2; }
934 U = calloc(1, sizeof *U);
935 RI = calloc(1, sizeof *RI);
936 RN = calloc(1, sizeof *RN);
937 OscDiag d;
938 if (osc_compile(src, sl, U, &d, NULL) != 0) {
939 fprintf(stderr, "osh_lex.osc refused: %s line %u: %s\n", osc_diag_kind_name(d.kind), d.line, d.message);
940 return 1;
941 }
942 char err[256];
943 check(osc_ir_validate(U, err, sizeof err) == 0, "validate: %s", err);
944 for (int f = 0; f < U->nfuncs; f++)
945 if (strcmp(U->funcs[f].name, "lex_run") == 0) FI = f;
946 check(FI >= 0, "no lex_run");
947 memset(&CODE, 0, sizeof CODE);
948 int cg = osc_cg_compile(U, &CODE, err, sizeof err);
949 check(cg == 0, "codegen: %s", err);
950 if (cg || FI < 0) { printf("OSH_LEX_FAIL\n"); return 1; }
951 int nm = osc_native_map(&NM, CODE.code, CODE.len);
952 check(nm == 0, "native map %d", nm);
953 if (nm) { printf("OSH_LEX_FAIL\n"); return 1; }
954 ENTRY = osc_native_at(&NM, CODE.entry[FI]);
955 osc_rt_init(RI);
956 osc_rt_init(RN);
957 unit_stats();
958
959 uint64_t seed = 0x05a1e0c0ffee0004ULL;
960 const char *se = getenv("OSH_FUZZ_SEED");
961 if (se && *se) seed = strtoull(se, NULL, 0);
962 if (seed == 0) seed = 1;
963 printf("fuzz seed: 0x%016llx (override with OSH_FUZZ_SEED)\n", (unsigned long long)seed);
964 uint64_t rng = seed;
965 run_abi();
966 run_hostile(&rng);
967 run_brace_depth(&rng);
968 run_eoi_cases(&rng);
969 run_vectors(argv[2], &rng);
970 run_bash_vectors(argv[2], &rng);
971 check(n_bvec >= 40, "only %lu bash-verified vectors ran, want at least 40", n_bvec);
972 run_fuzz(fuzz, &rng);
973
974 printf("abi header cases: %lu\n", n_abi);
975 printf("hostile cases: %lu (each: interp, native, reference, chunked)\n", n_hostile);
976 printf("vectors: %lu run, %lu lexer-level checks; bash-verified vectors: %lu\n", n_vec, n_vec_lex, n_bvec);
977 printf("fuzz: %lu inputs (seed above): done=%lu more=%lu refused=%lu\n", n_fuzz, n_status[0], n_status[1], n_status[2]);
978 printf("refusal codes seen in fuzz:");
979 for (int c = 0; c < 256; c++) if (n_code[c]) printf(" %d:%lu", c, n_code[c]);
980 printf("\n");
981 printf("cases %lu; interp calls %lu; native calls %lu; interp==native workspace compares %lu; reference compares %lu (%lu tokens); chunked calls %lu; traps %lu\n",
982 n_cases, n_interp_calls, n_native_calls, n_engine_cmp, n_ref_cmp, n_ref_tok, n_chunk_runs, n_traps);
983 printf("checks %lu, failures %lu\n", n_checks, n_fail);
984 osc_native_unmap(&NM);
985 osc_cg_free(&CODE);
986 free(src);
987 int ok = n_fail == 0;
988 printf(ok ? "OSH_LEX_PASS\n" : "OSH_LEX_FAIL\n");
989 return ok ? 0 : 1;
990}