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_parse.c

998 lines · 45676 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_parse.c -- host driver for the osh parser unit (src/osh/osh_parse.osc), aien-architecture#158 cut 4b.
19 *
20 * Compiles osh_lex.osc and osh_parse.osc, then runs the host sequence (lex_run until done, then parse_run) in the
21 * reference interpreter AND as native AArch64, with exact-size heap buffers (under ASan every out-of-range byte is a
22 * report), against:
23 * - the independent C reference tokenizer and parser (osh_lex_ref.c, osh_parse_ref.c), table for table;
24 * - itself, with the input fed in random chunk splits (resumption of both units), tables byte for byte;
25 * - the conformance vectors (aien-protocols specs/osh-platform/vectors, vendored in tests/osh/vectors, plus the
26 * local parser vectors in tests/osh/parse_vectors) at parser level;
27 * - a table of hostile cases and a fixed-seed fragment fuzz, each with the end-of-input flag clear and set.
28 * Usage: test_osh_parse OSH_LEX_OSC OSH_PARSE_OSC VECTORS_DIR PARSE_VECTORS_DIR [FUZZ_COUNT]
29 * Final line: OSH_PARSE_PASS or OSH_PARSE_FAIL.
30 */
31#include <stdarg.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35
36#include "osc_cg.h"
37#include "osc_front.h"
38#include "osc_interp.h"
39#include "osc_native.h"
40#include "osc_rt.h"
41#include "osh_layout.h"
42#include "osh_lex_ref.h"
43#include "osh_parse_ref.h"
44
45#define WS ((size_t)OSH_WS_CELLS)
46
47static unsigned long n_checks, n_fail;
48static unsigned long n_cases, n_ref_cmp, n_chunk_runs, n_engine_cmp, n_traps, n_calls_i, n_calls_n;
49static unsigned long n_vec, n_vec_parse, n_hostile, n_fuzz, n_idem;
50static unsigned long n_outcome[4]; /* fuzz: list done, need more, lexer refusal, parser refusal */
51static unsigned long n_code[256];
52static unsigned long n_cmds_cmp, n_pipes_cmp;
53
54static void check(int cond, const char *fmt, ...)
55{
56 n_checks++;
57 if (cond) return;
58 n_fail++;
59 if (n_fail <= 40) {
60 va_list ap;
61 va_start(ap, fmt);
62 fprintf(stderr, "FAIL: ");
63 vfprintf(stderr, fmt, ap);
64 fprintf(stderr, "\n");
65 va_end(ap);
66 }
67}
68
69/* ---- the two units ---- */
70typedef struct {
71 const char *entry;
72 OscUnit *U;
73 OscRt *RI, *RN;
74 OscCode code;
75 OscNative nm;
76 int fi;
77} Unit;
78
79typedef enum { INTERP = 0, NATIVE = 1 } Engine;
80
81static Unit LEX = { .entry = "lex_run" }, PARSE = { .entry = "parse_run" };
82
83static char *slurp(const char *path, size_t *len)
84{
85 FILE *f = fopen(path, "rb");
86 if (!f) return NULL;
87 size_t cap = 4096, n = 0;
88 char *b = malloc(cap);
89 for (;;) {
90 size_t r = fread(b + n, 1, cap - n, f);
91 n += r;
92 if (n < cap) break;
93 cap *= 2;
94 b = realloc(b, cap);
95 }
96 fclose(f);
97 *len = n;
98 return b;
99}
100
101static int unit_load(Unit *u, const char *path, char **srcp)
102{
103 size_t sl;
104 char *src = slurp(path, &sl);
105 if (!src) { fprintf(stderr, "cannot read %s\n", path); return 2; }
106 u->U = calloc(1, sizeof *u->U);
107 u->RI = calloc(1, sizeof *u->RI);
108 u->RN = calloc(1, sizeof *u->RN);
109 OscDiag d;
110 if (osc_compile(src, sl, u->U, &d, NULL) != 0) {
111 fprintf(stderr, "%s refused: %s line %u: %s\n", path, osc_diag_kind_name(d.kind), d.line, d.message);
112 return 1;
113 }
114 char err[256];
115 check(osc_ir_validate(u->U, err, sizeof err) == 0, "validate %s: %s", path, err);
116 u->fi = -1;
117 for (int f = 0; f < u->U->nfuncs; f++)
118 if (strcmp(u->U->funcs[f].name, u->entry) == 0) u->fi = f;
119 check(u->fi >= 0, "no %s", u->entry);
120 memset(&u->code, 0, sizeof u->code);
121 int cg = osc_cg_compile(u->U, &u->code, err, sizeof err);
122 check(cg == 0, "codegen %s: %s", path, err);
123 if (cg || u->fi < 0) return 1;
124 int nm = osc_native_map(&u->nm, u->code.code, u->code.len);
125 check(nm == 0, "native map %d", nm);
126 if (nm) return 1;
127 osc_rt_init(u->RI);
128 osc_rt_init(u->RN);
129 *srcp = src;
130 return 0;
131}
132
133static void unit_stats(const char *label, const Unit *u)
134{
135 unsigned maxv = 0, maxi = 0;
136 const char *vn = "", *in = "";
137 for (int f = 0; f < u->U->nfuncs; f++) {
138 const OscFunc *fn = &u->U->funcs[f];
139 printf("%s fn %-10s params=%u vregs=%u/%u insns=%u/%u\n", label, fn->name, fn->nparams, fn->nvregs, OSC_MAX_VREGS, fn->ninsns, OSC_MAX_INSNS);
140 if (fn->nvregs > maxv) { maxv = fn->nvregs; vn = fn->name; }
141 if (fn->ninsns > maxi) { maxi = fn->ninsns; in = fn->name; }
142 check(fn->nparams <= OSC_MAX_PARAMS, "%s has %u param registers", fn->name, fn->nparams);
143 }
144 printf("%s unit: %u functions (max %u); biggest vregs %s %u (headroom %u of %u); biggest insns %s %u (headroom %u of %u)\n", label, u->U->nfuncs,
145 OSC_MAX_FUNCS, vn, maxv, OSC_MAX_VREGS - maxv, OSC_MAX_VREGS, in, maxi, OSC_MAX_INSNS - maxi, OSC_MAX_INSNS);
146 check(u->U->nfuncs <= OSC_MAX_FUNCS, "too many functions");
147}
148
149/* one entry call on an exact-size copy of data[0..len): the return value, or ~0 on a trap */
150static uint64_t ucall(Unit *u, Engine e, uint64_t *w, size_t wn, const uint8_t *data, size_t len)
151{
152 uint8_t *b = NULL;
153 if (len) {
154 b = malloc(len);
155 if (!b) { fprintf(stderr, "oom\n"); exit(2); }
156 memcpy(b, data, len);
157 }
158 uint64_t args[4] = { (uint64_t)(uintptr_t)b, len, (uint64_t)(uintptr_t)w, wn };
159 uint64_t ret = 0;
160 int trap;
161 check(osc_ir_slice_args_ok(&u->U->funcs[u->fi], args, 4) == 0, "host entry refused valid buffers");
162 if (e == INTERP) {
163 osc_rt_reset(u->RI);
164 trap = osc_interp_run_prevalidated(u->U, u->fi, args, 4, u->RI, &ret);
165 n_calls_i++;
166 } else {
167 osc_rt_reset(u->RN);
168 trap = osc_native_call(u->U, u->fi, &u->nm, u->code.entry[u->fi], u->RN, args, 4, &ret);
169 n_calls_n++;
170 }
171 free(b);
172 if (trap != 0) {
173 n_traps++;
174 check(0, "%s %s trap %d (len %zu)", u->entry, e == INTERP ? "interp" : "native", trap, len);
175 return ~0ULL;
176 }
177 return ret;
178}
179
180static uint64_t *sess_new(void)
181{
182 uint64_t *w = calloc(WS, sizeof(uint64_t));
183 if (!w) { fprintf(stderr, "oom\n"); exit(2); }
184 w[OSH_S_MAGIC] = OSH_ABI_MAGIC;
185 w[OSH_S_VERSION] = OSH_ABI_VERSION;
186 w[OSH_S_WS_CELLS] = OSH_WS_CELLS;
187 return w;
188}
189
190/* run an entry, repeating on 101 (budget) with no new input */
191static uint64_t run_entry(Unit *u, Engine e, uint64_t *w, const uint8_t *d, size_t n)
192{
193 for (int r = 0; r < 12; r++) {
194 uint64_t st = ucall(u, e, w, WS, d, n);
195 if (st != 101) return st;
196 }
197 check(0, "%s: more than 12 budget resumes for %zu bytes", u->entry, n);
198 return ~0ULL;
199}
200
201/* the host sequence over d[0..n): lex until it settles, then parse. Returns the final status; *from_lexer says which. */
202static uint64_t host_run(Engine e, uint64_t *w, const uint8_t *d, size_t n, int *from_lexer)
203{
204 uint64_t st = run_entry(&LEX, e, w, d, n);
205 *from_lexer = 1;
206 if (st != 0) return st;
207 *from_lexer = 0;
208 return run_entry(&PARSE, e, w, d, n);
209}
210
211static uint64_t rng_next(uint64_t *s)
212{
213 uint64_t x = *s;
214 x ^= x >> 12;
215 x ^= x << 25;
216 x ^= x >> 27;
217 *s = x;
218 return x * 0x2545F4914F6CDD1DULL;
219}
220
221/* feed d[0..n) as the host would: random chunks (mode 0 one byte, 1 random 1..16, 2 random up to the rest); after
222 * each chunk, if the lexer is done run the parser; stop when the list is complete or a refusal comes. Then, if eoi,
223 * set the flag and run both again. Returns the final status. */
224static uint64_t host_chunked(Engine e, uint64_t *w, const uint8_t *d, size_t n, int eoi, unsigned mode, uint64_t *rng, int *from_lexer)
225{
226 size_t cur = 0;
227 uint64_t st = 0;
228 *from_lexer = 1;
229 if (n == 0) return host_run(e, w, d, 0, from_lexer);
230 while (cur < n) {
231 size_t ch = 1;
232 if (mode == 1) ch = 1 + rng_next(rng) % 16;
233 else if (mode == 2) ch = 1 + rng_next(rng) % (n - cur);
234 if (ch > n - cur) ch = n - cur;
235 cur += ch;
236 st = host_run(e, w, d, cur, from_lexer);
237 n_chunk_runs++;
238 if (st >= 200) return st;
239 if (st == 0 && !*from_lexer) return st; /* the list is complete: the host would start a new session */
240 }
241 if (eoi) {
242 w[OSH_S_EOI] = 1;
243 st = host_run(e, w, d, n, from_lexer);
244 }
245 return st;
246}
247
248/* ---- comparison against the references ---- */
249static void dump_input(const uint8_t *d, size_t n)
250{
251 fprintf(stderr, " input:");
252 for (size_t q = 0; q < n && q < 100; q++) fprintf(stderr, " %02x", d[q]);
253 fprintf(stderr, "\n");
254}
255
256/* the workspace after the host sequence vs the reference outcome */
257static void cmp_ref(const char *tag, const uint8_t *d, size_t n, int eoi, const uint64_t *w, uint64_t st)
258{
259 OshRefLex *lx = malloc(sizeof *lx);
260 OshRefParse *pr = calloc(1, sizeof *pr);
261 osh_lex_ref(d, n, eoi, lx);
262 int ok = 1;
263 uint64_t want = lx->status, woff = lx->err_off;
264 if (lx->status == 0) {
265 osh_parse_ref(d, n, lx, eoi, pr);
266 want = pr->status;
267 woff = pr->err_off;
268 }
269 n_ref_cmp++;
270 if (st != want) ok = 0;
271 if (want >= 200) {
272 if (w[OSH_S_ERR_CODE] != want || w[OSH_S_ERR_OFF] != woff || w[OSH_S_PHASE] != 255) ok = 0;
273 } else if (lx->status == 0) {
274 /* parser outcome 0 or 100: the tables written so far, and for 0 the cursor */
275 if (w[OSH_PX_NCMD] != pr->ncmd || w[OSH_PX_NPIPE] != pr->npipe) ok = 0;
276 for (unsigned c = 0; c < pr->ncmd && ok; c++)
277 for (int j = 0; j < 8; j++) {
278 n_cmds_cmp++;
279 if (w[OSH_CMDS + 8 * c + j] != pr->cmd[c][j]) ok = 0;
280 }
281 for (unsigned p = 0; p < pr->npipe && ok; p++)
282 for (int j = 0; j < 4; j++) {
283 n_pipes_cmp++;
284 if (w[OSH_PIPES + 4 * p + j] != pr->pipe[p][j]) ok = 0;
285 }
286 if (want == 0 && w[OSH_PX_TOK] != pr->next_tok) ok = 0;
287 if (w[OSH_PX_STATE] > 4) ok = 0;
288 }
289 /* the parser never writes the staging, request or out regions */
290 for (size_t q = OSH_STAGING; q < OSH_STAGING + 64 && ok; q++)
291 if (w[q] != 0) ok = 0;
292 if (!ok) {
293 fprintf(stderr, " ref mismatch [%s] eoi=%d len %zu: osc status %llu err %llu@%llu ncmd %llu npipe %llu tok %llu | ref lex %u parse %u err@%llu ncmd %u npipe %u next %u\n",
294 tag, eoi, n, (unsigned long long)st, (unsigned long long)w[OSH_S_ERR_CODE], (unsigned long long)w[OSH_S_ERR_OFF],
295 (unsigned long long)w[OSH_PX_NCMD], (unsigned long long)w[OSH_PX_NPIPE], (unsigned long long)w[OSH_PX_TOK], lx->status,
296 pr->status, (unsigned long long)woff, pr->ncmd, pr->npipe, pr->next_tok);
297 dump_input(d, n);
298 for (unsigned c = 0; c < pr->ncmd && lx->status == 0; c++) {
299 int diff = 0;
300 for (int j = 0; j < 8; j++) if (w[OSH_CMDS + 8 * c + j] != pr->cmd[c][j]) diff = 1;
301 if (diff) {
302 fprintf(stderr, " cmd %u osc:", c);
303 for (int j = 0; j < 8; j++) fprintf(stderr, " %llu", (unsigned long long)w[OSH_CMDS + 8 * c + j]);
304 fprintf(stderr, " | ref:");
305 for (int j = 0; j < 8; j++) fprintf(stderr, " %llu", (unsigned long long)pr->cmd[c][j]);
306 fprintf(stderr, "\n");
307 break;
308 }
309 }
310 }
311 check(ok, "reference mismatch [%s] eoi=%d", tag, eoi);
312 free(lx);
313 free(pr);
314}
315
316typedef struct {
317 uint64_t status;
318 int from_lexer;
319 uint64_t err_off;
320 uint64_t npipe, ncmd;
321} Outcome;
322
323/* One input, one eoi setting, through everything. */
324static void run_one(const char *tag, const uint8_t *d, size_t n, int eoi, uint64_t *rng, unsigned long iter, Outcome *out)
325{
326 uint64_t *a = sess_new(), *b = sess_new(), *c = sess_new();
327 int fla, flb, flc;
328 a[OSH_S_EOI] = (uint64_t)eoi;
329 b[OSH_S_EOI] = (uint64_t)eoi;
330 uint64_t sa = host_run(INTERP, a, d, n, &fla);
331 uint64_t sb = host_run(NATIVE, b, d, n, &flb);
332 n_cases++;
333 n_engine_cmp++;
334 int same = memcmp(a, b, WS * 8) == 0;
335 check(sa == sb && fla == flb && same, "[%s] eoi=%d interp and native disagree (status %llu vs %llu, workspace %s)", tag, eoi,
336 (unsigned long long)sa, (unsigned long long)sb, same ? "same" : "differs");
337 cmp_ref(tag, d, n, eoi, a, sa);
338 /* idempotence of a settled call */
339 if (sa == 0 || sa == 100 || sa >= 200) {
340 uint64_t *snap = malloc(WS * 8);
341 memcpy(snap, a, WS * 8);
342 uint64_t s1 = fla ? ucall(&LEX, INTERP, a, WS, d, n) : ucall(&PARSE, INTERP, a, WS, d, n);
343 uint64_t s2 = fla ? ucall(&LEX, NATIVE, a, WS, d, n) : ucall(&PARSE, NATIVE, a, WS, d, n);
344 n_idem++;
345 /* a settled lexer call may rewrite its done flag identically; the whole workspace must be unchanged */
346 check(s1 == sa && s2 == sa && memcmp(snap, a, WS * 8) == 0, "[%s] eoi=%d repeated call changed the outcome (%llu %llu vs %llu)", tag, eoi,
347 (unsigned long long)s1, (unsigned long long)s2, (unsigned long long)sa);
348 free(snap);
349 }
350 /* chunked resumption, alternating the engine; only when the whole buffer lexes clean (otherwise the host may
351 * legitimately stop at a list end before it reaches a later lexer refusal) */
352 OshRefLex *lx = malloc(sizeof *lx);
353 osh_lex_ref(d, n, eoi, lx);
354 int lex_clean = lx->status == 0;
355 free(lx);
356 if (lex_clean) {
357 unsigned mode = (unsigned)(rng_next(rng) % 3);
358 if (mode == 0 && n > 48) mode = 1;
359 Engine ce = (iter & 1) ? INTERP : NATIVE;
360 uint64_t sc = host_chunked(ce, c, d, n, eoi, mode, rng, &flc);
361 cmp_ref(tag, d, n, eoi, c, sc);
362 check(sc == sa, "[%s] eoi=%d chunked (mode %u) status %llu differs from single shot %llu", tag, eoi, mode, (unsigned long long)sc,
363 (unsigned long long)sa);
364 if ((iter & 7) == 0) {
365 uint64_t *e2 = sess_new();
366 int fle;
367 uint64_t se = host_chunked(ce == INTERP ? NATIVE : INTERP, e2, d, n, eoi, 1, rng, &fle);
368 check(se == sa, "[%s] eoi=%d chunked run on the other engine differs", tag, eoi);
369 cmp_ref(tag, d, n, eoi, e2, se);
370 free(e2);
371 }
372 }
373 if (out) {
374 out->status = sa;
375 out->from_lexer = fla;
376 out->err_off = a[OSH_S_ERR_OFF];
377 out->npipe = a[OSH_PX_NPIPE];
378 out->ncmd = a[OSH_PX_NCMD];
379 }
380 free(a);
381 free(b);
382 free(c);
383}
384
385static void run_all(const char *tag, const uint8_t *d, size_t n, uint64_t *rng, unsigned long iter, Outcome *o0, Outcome *o1)
386{
387 run_one(tag, d, n, 0, rng, iter, o0);
388 run_one(tag, d, n, 1, rng, iter, o1);
389}
390
391/* ---- hostile cases ---- */
392typedef struct {
393 const char *name;
394 const char *in;
395 size_t len;
396 int eoi;
397 uint64_t status;
398 uint64_t off; /* refusals only */
399 int npipe; /* -1 = do not check */
400 int ncmd;
401} Hostile;
402
403#define H(name, s, eoi, status, off, np, nc) { name, s, sizeof(s) - 1, eoi, status, off, np, nc }
404
405static const Hostile HOSTILE[] = {
406 H("simple", "ls -l /tmp\n", 0, 0, 0, 1, 1),
407 H("empty buffer", "", 0, 0, 0, 0, 0),
408 H("empty buffer eoi", "", 1, 0, 0, 0, 0),
409 H("blank line", "\n", 0, 0, 0, 0, 0),
410 H("blank lines: the first is a complete empty list", "\n\n \nls\n", 0, 0, 0, 0, 0),
411 H("comment only", "# note\n", 0, 0, 0, 0, 0),
412 H("list", "a && b || c; d | e\n", 0, 0, 0, 4, 5),
413 H("trailing semicolon", "a;\n", 0, 0, 0, 1, 1),
414 H("trailing semicolon with blank", "a ; \n", 0, 0, 0, 1, 1),
415 H("semicolon then command", "a; b\n", 0, 0, 0, 2, 2),
416 H("end of input after semicolon", "a;", 1, 0, 0, 1, 1),
417 H("end of input after a command", "ls", 1, 0, 0, 1, 1),
418 H("no newline without the flag is lexer pending", "ls", 0, 100, 0, -1, -1),
419 H("assignments only", "x=1 y=2\n", 0, 0, 0, 1, 1),
420 H("redirection only", "> f\n", 0, 0, 0, 1, 1),
421 H("redirections interleaved with words", "cat <in a >out b 2>&1 c\n", 0, 0, 0, 1, 1),
422 H("append and input", "a >>o <i\n", 0, 0, 0, 1, 1),
423 H("pipeline of eight", "a|a|a|a|a|a|a|a\n", 0, 0, 0, 1, 8),
424 H("pipeline of nine", "a|a|a|a|a|a|a|a|a\n", 0, 205, 16, -1, -1),
425 H("assignment after a word is a word", "A=1 cmd B=2\n", 0, 0, 0, 1, 1),
426 H("equals word is a word", "=x y\n", 0, 0, 0, 1, 1),
427 H("leading semicolon", ";a\n", 0, 241, 0, -1, -1),
428 H("semicolon after semicolon", "a; ;b\n", 0, 241, 3, -1, -1),
429 H("leading pipe", "|a\n", 0, 241, 0, -1, -1),
430 H("leading and", "&&a\n", 0, 241, 0, -1, -1),
431 H("leading or", "|| a\n", 0, 241, 0, -1, -1),
432 H("pipe pipe", "a | | b\n", 0, 241, 4, -1, -1),
433 H("pipe semicolon", "a |;\n", 0, 241, 3, -1, -1),
434 H("and semicolon", "a && ; b\n", 0, 241, 5, -1, -1),
435 H("semicolon and", "a ; && b\n", 0, 241, 4, -1, -1),
436 H("or pipe", "a || | b\n", 0, 241, 5, -1, -1),
437 H("trailing and", "a &&\n", 0, 100, 0, 1, 1),
438 H("trailing or", "a ||\n", 0, 100, 0, 1, 1),
439 H("trailing pipe", "a |\n", 0, 100, 0, 1, 1),
440 H("trailing and at end of input", "a &&\n", 1, 248, 5, -1, -1),
441 H("trailing pipe at end of input", "a |\n", 1, 248, 4, -1, -1),
442 H("trailing pipe pending operator at end of input", "a |", 1, 248, 3, -1, -1),
443 H("continuation after and", "a &&\n\n b\n", 0, 0, 0, 2, 2),
444 H("continuation after pipe", "a |\nb\n", 0, 0, 0, 1, 2),
445 H("continuation after or then comment line", "a ||\n# c\nb\n", 0, 0, 0, 2, 2),
446 H("newline after semicolon ends the list", "a;\nb\n", 0, 0, 0, 1, 1),
447 H("two lines: the second is left", "a\nb\n", 0, 0, 0, 1, 1),
448 H("redirect without target", "cat >\n", 0, 242, 5, -1, -1),
449 H("redirect target is an operator", "cat > | x\n", 0, 242, 6, -1, -1),
450 H("append target is a semicolon", "cat >>;\n", 0, 242, 6, -1, -1),
451 H("input target missing", "cat <\n", 0, 242, 5, -1, -1),
452 H("dup target missing", "cat <&\n", 0, 242, 6, -1, -1),
453 H("redirect target missing at end of input", "cat >", 1, 242, 5, -1, -1),
454 H("redirect target missing pending without flag", "cat >", 0, 100, 0, -1, -1),
455 H("redirect target missing after a word end of input", "cat > f >", 1, 242, 9, -1, -1),
456 H("dup ok 2>&1", "a 2>&1\n", 0, 0, 0, 1, 1),
457 H("dup ok >&2", "a >&2\n", 0, 0, 0, 1, 1),
458 H("dup ok <&0", "a <&0\n", 0, 0, 0, 1, 1),
459 H("dup ok then file", "a 2>&1 >o\n", 0, 0, 0, 1, 1),
460 H("dup source 3", "a >&3\n", 0, 232, 4, -1, -1),
461 H("dup source 10", "a >&10\n", 0, 232, 4, -1, -1),
462 H("dup source 00", "a <&00\n", 0, 232, 4, -1, -1),
463 H("dup name", "a >&f\n", 0, 231, 4, -1, -1),
464 H("dup close", "a >&-\n", 0, 231, 4, -1, -1),
465 H("dup quoted digit", "a >&'1'\n", 0, 231, 4, -1, -1),
466 H("dup variable", "a >&$X\n", 0, 231, 4, -1, -1),
467 H("dup digit then name", "a >&1x\n", 0, 231, 4, -1, -1),
468 H("dup operator target", "a >& ;\n", 0, 242, 5, -1, -1),
469 H("reserved if", "if x\n", 0, 233, 0, -1, -1),
470 H("reserved then", "then\n", 0, 233, 0, -1, -1),
471 H("reserved elif", "elif x\n", 0, 233, 0, -1, -1),
472 H("reserved else", "else\n", 0, 233, 0, -1, -1),
473 H("reserved fi", "fi\n", 0, 233, 0, -1, -1),
474 H("reserved for", "for x\n", 0, 234, 0, -1, -1),
475 H("reserved while", "while x\n", 0, 234, 0, -1, -1),
476 H("reserved until", "until x\n", 0, 234, 0, -1, -1),
477 H("reserved do", "do\n", 0, 234, 0, -1, -1),
478 H("reserved done", "done\n", 0, 234, 0, -1, -1),
479 H("reserved in", "in x\n", 0, 234, 0, -1, -1),
480 H("reserved select", "select x\n", 0, 234, 0, -1, -1),
481 H("reserved case", "case x\n", 0, 235, 0, -1, -1),
482 H("reserved esac", "esac\n", 0, 235, 0, -1, -1),
483 H("reserved function", "function f\n", 0, 237, 0, -1, -1),
484 H("reserved negation", "! x\n", 0, 238, 0, -1, -1),
485 H("reserved time", "time ls\n", 0, 239, 0, -1, -1),
486 H("reserved coproc", "coproc x\n", 0, 239, 0, -1, -1),
487 H("reserved after an assignment", "A=1 if\n", 0, 233, 4, -1, -1),
488 H("reserved after a redirection", ">f for\n", 0, 234, 3, -1, -1),
489 H("reserved after a pipe", "a | if\n", 0, 233, 4, -1, -1),
490 H("reserved after a semicolon", "a; done\n", 0, 234, 3, -1, -1),
491 H("reserved after and", "a && case x\n", 0, 235, 5, -1, -1),
492 H("reserved with a continuation", "i\\\nf x\n", 0, 233, 0, -1, -1),
493 H("reserved as an argument", "echo if then fi\n", 0, 0, 0, 1, 1),
494 H("reserved as a redirect target", "a > if\n", 0, 0, 0, 1, 1),
495 H("reserved in quotes", "'if' x\n", 0, 0, 0, 1, 1),
496 H("reserved escaped", "\\if x\n", 0, 0, 0, 1, 1),
497 H("reserved with a suffix", "iff ifx fi2 done1 !x a!\n", 0, 0, 0, 1, 1),
498 H("reserved prefix longer than eight bytes", "functionx\n", 0, 0, 0, 1, 1),
499 H("ifs assignment", "IFS=: ls\n", 0, 240, 0, -1, -1),
500 H("ifs assignment empty", "IFS= \n", 0, 240, 0, -1, -1),
501 H("ifs assignment quoted", "IFS=\"x\" a\n", 0, 240, 0, -1, -1),
502 H("ifs assignment second", "A=1 IFS=2\n", 0, 240, 4, -1, -1),
503 H("ifs assignment with a continuation", "IF\\\nS=1 x\n", 0, 240, 0, -1, -1),
504 H("ifs lookalikes", "IFSX=1 xIFS=1 _IFS=1 a\n", 0, 0, 0, 1, 1),
505 H("ifs as an argument", "echo IFS=x\n", 0, 0, 0, 1, 1),
506 H("quoted ifs name is a word", "\"IFS\"=x\n", 0, 0, 0, 1, 1),
507 H("open quote at end of input", "echo \"abc", 1, 248, 9, -1, -1),
508 H("open quote without the flag", "echo \"abc", 0, 100, 0, -1, -1),
509 H("trailing backslash at end of input is a literal (bash)", "echo a\\", 1, 0, 0, 1, 1),
510 H("trailing backslash without the flag waits", "echo a\\", 0, 100, 0, -1, -1),
511 H("open brace parameter at end of input", "echo ${A", 1, 248, 8, -1, -1),
512 H("dollar at end of input", "echo $", 1, 0, 0, 1, 1),
513 H("background at end of input", "a &", 1, 227, 2, -1, -1),
514 H("redirect operator at end of input", "a <", 1, 242, 3, -1, -1),
515 H("comment at end of input", "a # c", 1, 0, 0, 1, 1),
516 H("blank at end of input", " ", 1, 0, 0, 0, 0),
517 H("lexer refusal wins", "a | | $(x)\n", 0, 226, 7, -1, -1),
518 H("lexer cap line", "", 0, 0, 0, 0, 0), /* replaced at run time */
519};
520
521static void build_cap(const char *name, int which, uint8_t *buf, size_t *len, uint64_t *status, uint64_t *off, int *np, int *nc)
522{
523 (void)name;
524 size_t n = 0;
525 *np = *nc = -1;
526 *off = 0;
527 *status = 0;
528 switch (which) {
529 case 0: /* 32 words: ok */
530 buf[n++] = 'a'; for (int q = 0; q < 31; q++) { buf[n++] = ' '; buf[n++] = 'b'; } *np = 1; *nc = 1; break;
531 case 1: /* 33 words */
532 buf[n++] = 'a'; for (int q = 0; q < 32; q++) { buf[n++] = ' '; buf[n++] = 'b'; } *status = 206; *off = 64; break;
533 case 2: /* 16 assignments then a word: ok */
534 for (int q = 0; q < 16; q++) { memcpy(buf + n, "a=1 ", 4); n += 4; } buf[n++] = 'x'; *np = 1; *nc = 1; break;
535 case 3: /* 17 assignments */
536 for (int q = 0; q < 17; q++) { memcpy(buf + n, "a=1 ", 4); n += 4; } *status = 207; *off = 64; break;
537 case 4: /* 8 redirections: ok */
538 for (int q = 0; q < 8; q++) { memcpy(buf + n, ">f ", 3); n += 3; } *np = 1; *nc = 1; break;
539 case 5: /* 9 redirections */
540 for (int q = 0; q < 9; q++) { memcpy(buf + n, ">f ", 3); n += 3; } *status = 208; *off = 24; break;
541 case 6: /* 16 pipelines: ok */
542 for (int q = 0; q < 16; q++) { memcpy(buf + n, "a;", 2); n += 2; } *np = 16; *nc = 16; break;
543 case 7: /* 17 pipelines */
544 for (int q = 0; q < 17; q++) { memcpy(buf + n, "a;", 2); n += 2; } *status = 204; *off = 32; break;
545 case 8: /* 16 pipelines of two: 32 commands ok */
546 for (int q = 0; q < 16; q++) { memcpy(buf + n, "a|a;", 4); n += 4; } *np = 16; *nc = 32; break;
547 case 9: /* 17 pipelines of two: pipelines first */
548 for (int q = 0; q < 17; q++) { memcpy(buf + n, "a|a;", 4); n += 4; } *status = 204; *off = 64; break;
549 case 10: /* 4 pipelines of 8 = 32 commands, then a fifth with one: the 33rd command */
550 for (int q = 0; q < 4; q++) { for (int r = 0; r < 8; r++) { buf[n++] = 'a'; buf[n++] = (r == 7) ? ';' : '|'; } } buf[n++] = 'a'; *status = 203; *off = 64; break;
551 case 11: /* 4 pipelines of 8 = 32 commands: ok */
552 for (int q = 0; q < 4; q++) { for (int r = 0; r < 8; r++) { buf[n++] = 'a'; buf[n++] = (r == 7) ? ';' : '|'; } } *np = 4; *nc = 32; break;
553 case 12: /* 9 commands in one pipeline after an and: the pipe cap is per pipeline */
554 memcpy(buf, "a&&", 3); n = 3; for (int r = 0; r < 8; r++) { buf[n++] = 'a'; buf[n++] = '|'; } buf[n++] = 'a'; *status = 205; *off = 3 + 16; break;
555 default: /* redirect target words do not count as words */
556 buf[n++] = 'a'; for (int q = 0; q < 31; q++) { buf[n++] = ' '; buf[n++] = 'b'; } for (int q = 0; q < 8; q++) { memcpy(buf + n, " >f", 3); n += 3; } *np = 1; *nc = 1; break;
557 }
558 buf[n++] = '\n';
559 *len = n;
560}
561
562#define NCAP 14
563
564static void run_hostile(uint64_t *rng)
565{
566 for (size_t h = 0; h < sizeof HOSTILE / sizeof HOSTILE[0]; h++) {
567 const Hostile *c = &HOSTILE[h];
568 const uint8_t *d = (const uint8_t *)c->in;
569 size_t n = c->len;
570 uint8_t *big = NULL;
571 uint64_t status = c->status, off = c->off;
572 int np = c->npipe, nc = c->ncmd;
573 if (strcmp(c->name, "lexer cap line") == 0) {
574 n = 4097;
575 big = malloc(n);
576 memset(big, 'a', n);
577 big[n - 1] = '\n';
578 d = big;
579 status = 201;
580 off = 4096;
581 np = nc = -1;
582 }
583 Outcome o0, o1;
584 run_all(c->name, d, n, rng, h, &o0, &o1);
585 n_hostile++;
586 const Outcome *o = c->eoi ? &o1 : &o0;
587 check(o->status == status, "hostile '%s': status %llu, want %llu", c->name, (unsigned long long)o->status, (unsigned long long)status);
588 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);
589 if (np >= 0 && (status == 0 || status == 100)) check(o->npipe == (uint64_t)np && o->ncmd == (uint64_t)nc, "hostile '%s': %llu pipelines %llu commands, want %d %d", c->name, (unsigned long long)o->npipe, (unsigned long long)o->ncmd, np, nc);
590 free(big);
591 }
592 /* capacity cases: every one also runs with the flag set (a complete line behaves the same) */
593 for (int which = 0; which < NCAP; which++) {
594 uint8_t buf[1024];
595 size_t n;
596 uint64_t status, off;
597 int np, nc;
598 build_cap("cap", which, buf, &n, &status, &off, &np, &nc);
599 Outcome o0, o1;
600 char tag[32];
601 snprintf(tag, sizeof tag, "capacity %d", which);
602 run_all(tag, buf, n, rng, 500 + (unsigned long)which, &o0, &o1);
603 n_hostile++;
604 check(o0.status == status && o1.status == status, "%s: status %llu/%llu, want %llu", tag, (unsigned long long)o0.status, (unsigned long long)o1.status, (unsigned long long)status);
605 if (status >= 200) check(o0.err_off == off, "%s: offset %llu, want %llu", tag, (unsigned long long)o0.err_off, (unsigned long long)off);
606 if (np >= 0) check(o0.npipe == (uint64_t)np && o0.ncmd == (uint64_t)nc, "%s: %llu pipelines %llu commands, want %d %d", tag, (unsigned long long)o0.npipe, (unsigned long long)o0.ncmd, np, nc);
607 }
608}
609
610/* ---- ABI-level refusals of the parser entry ---- */
611static void run_abi(void)
612{
613 const uint8_t in[] = "ls\n";
614 for (int e = 0; e < 2; e++) {
615 Engine en = e ? NATIVE : INTERP;
616 uint64_t *w = sess_new();
617 /* the parser before the lexer: refused, nothing written */
618 uint64_t *snap = malloc(WS * 8);
619 memcpy(snap, w, WS * 8);
620 check(ucall(&PARSE, en, w, WS, in, 3) == 217 && memcmp(snap, w, WS * 8) == 0, "parse before lex is refused 217 and writes nothing");
621 n_vec_parse++;
622 /* header refusals */
623 check(ucall(&PARSE, en, w, 1, in, 3) == 216, "parse: one cell");
624 w[OSH_S_MAGIC] ^= 1;
625 check(ucall(&PARSE, en, w, WS, in, 3) == 214, "parse: bad magic");
626 w[OSH_S_MAGIC] ^= 1;
627 w[OSH_S_VERSION] = 2;
628 check(ucall(&PARSE, en, w, WS, in, 3) == 215, "parse: bad version");
629 w[OSH_S_VERSION] = 1;
630 check(ucall(&PARSE, en, w, WS - 1, in, 3) == 213, "parse: short workspace");
631 w[48] = 1;
632 check(ucall(&PARSE, en, w, WS, in, 3) == 217, "parse: reserved cell");
633 w[48] = 0;
634 w[OSH_S_EOI] = 2;
635 check(ucall(&PARSE, en, w, WS, in, 3) == 217 && ucall(&LEX, en, w, WS, in, 3) == 217, "eoi flag above 1 is ABI_RESERVED in both units");
636 w[OSH_S_EOI] = 0;
637 /* a corrupt parser state is refused */
638 check(ucall(&LEX, en, w, WS, in, 3) == 0, "lex ok");
639 w[OSH_PX_STATE] = 9;
640 check(ucall(&PARSE, en, w, WS, in, 3) == 217, "corrupt parser state is refused");
641 w[OSH_PX_STATE] = 0;
642 w[OSH_PX_TOK] = 99;
643 check(ucall(&PARSE, en, w, WS, in, 3) == 217, "parser cursor past the tokens is refused");
644 w[OSH_PX_TOK] = 0;
645 check(ucall(&PARSE, en, w, WS, in, 3) == 0, "parse ok after the refusals");
646 free(snap);
647 free(w);
648 }
649 /* a refusal is terminal and repeats; the parser reports the lexer's refusal too */
650 uint64_t *w = sess_new();
651 const uint8_t bad[] = "a | | b\n";
652 int fl;
653 check(host_run(INTERP, w, bad, sizeof bad - 1, &fl) == 241 && !fl, "terminal: first");
654 check(ucall(&PARSE, NATIVE, w, WS, bad, sizeof bad - 1) == 241 && ucall(&PARSE, INTERP, w, WS, (const uint8_t *)"", 0) == 241, "terminal: repeat");
655 free(w);
656 w = sess_new();
657 const uint8_t lbad[] = "echo $(x)\n";
658 check(host_run(INTERP, w, lbad, sizeof lbad - 1, &fl) == 226, "lexer refusal");
659 check(ucall(&PARSE, INTERP, w, WS, lbad, sizeof lbad - 1) == 226, "parser repeats the lexer refusal");
660 free(w);
661 /* the parser sees a lexer that is not done: a half line */
662 w = sess_new();
663 const uint8_t half[] = "echo \"abc";
664 check(run_entry(&LEX, INTERP, w, half, sizeof half - 1) == 100, "half line is 100");
665 check(ucall(&PARSE, INTERP, w, WS, half, sizeof half - 1) == 217, "parser refuses a lexer that is not done");
666 free(w);
667 /* incremental: a trailing && resumes after the next line is appended and re-lexed */
668 for (int e = 0; e < 2; e++) {
669 Engine en = e ? NATIVE : INTERP;
670 w = sess_new();
671 const uint8_t l1[] = "a &&\n";
672 const uint8_t l2[] = "a &&\nb | \nc\nignored\n";
673 check(host_run(en, w, l1, sizeof l1 - 1, &fl) == 100 && !fl, "resume: first line 100");
674 check(host_run(en, w, l2, 11, &fl) == 100 && fl, "resume: second line still open (pipe)");
675 check(host_run(en, w, l2, sizeof l2 - 1, &fl) == 0 && !fl, "resume: done");
676 check(w[OSH_PX_NPIPE] == 2 && w[OSH_PX_NCMD] == 3, "resume: tables %llu %llu", (unsigned long long)w[OSH_PX_NPIPE], (unsigned long long)w[OSH_PX_NCMD]);
677 check(w[OSH_PX_TOK] < w[OSH_LX_NTOK], "resume: tokens of the next line are left");
678 free(w);
679 }
680}
681
682/* ---- conformance vectors at parser level ---- */
683static void put_q(char **o, const uint8_t *s, size_t len)
684{
685 *o += sprintf(*o, "\"");
686 for (size_t i = 0; i < len; i++) {
687 uint8_t c = s[i];
688 if (c == '"' || c == '\\') *o += sprintf(*o, "\\%c", c);
689 else if (c < 0x20 || c > 0x7e) *o += sprintf(*o, "\\x%02X", c);
690 else *o += sprintf(*o, "%c", c);
691 }
692 *o += sprintf(*o, "\"");
693}
694
695/* a word's text with backslash-newline pairs removed, when it has no quote, escape or expansion */
696static int literal_word(const uint8_t *in, const uint64_t *tok, uint8_t *out, size_t *olen)
697{
698 uint64_t flags = (tok[0] >> 8) & 0xffff;
699 if (flags & ~32ULL & ~16ULL) return 0;
700 size_t k = 0;
701 for (uint64_t q = 0; q < tok[2]; q++) {
702 if (in[tok[1] + q] == '\\' && q + 1 < tok[2] && in[tok[1] + q + 1] == '\n') { q++; continue; }
703 out[k++] = in[tok[1] + q];
704 }
705 *olen = k;
706 return 1;
707}
708
709/* render the parse tables in the vector grammar; `?` stands for an item the parser cannot know (an expanded or
710 * quoted word), `*` for a whole argv list when an expansion could change its length */
711static void render(const uint8_t *in, const uint64_t *w, char *out)
712{
713 char *o = out;
714 uint8_t tmp[4200];
715 size_t tl;
716 for (uint64_t p = 0; p < w[OSH_PX_NPIPE]; p++) {
717 const uint64_t *pe = &w[OSH_PIPES + 4 * p];
718 if (p) o += sprintf(o, " | ");
719 o += sprintf(o, "P%llu conn=%llu", (unsigned long long)p, (unsigned long long)pe[2]);
720 for (uint64_t j = 0; j < pe[1]; j++) {
721 const uint64_t *ce = &w[OSH_CMDS + 8 * (pe[0] + j)];
722 o += sprintf(o, " | C%llu b=? argv=", (unsigned long long)j);
723 int dollar = 0;
724 for (uint64_t t = ce[0]; t < ce[1]; t++) if (((w[OSH_TOKENS + 4 * t] >> 8) & 8) && (w[OSH_TOKENS + 4 * t] & 255) == 1) dollar = 1;
725 char argv[40000], as[40000], rd[40000];
726 char *oa = argv, *os = as, *orr = rd;
727 int any = 0;
728 for (uint64_t t = ce[0]; t < ce[1];) {
729 const uint64_t *tk = &w[OSH_TOKENS + 4 * t];
730 uint64_t kind = tk[0] & 255, flags = (tk[0] >> 8) & 0xffff;
731 if (kind == 1) {
732 if ((flags & 16) && !any) {
733 uint64_t eq = tk[3] - 1;
734 if (os != as) *os++ = ',';
735 os += snprintf(os, 4096, "%.*s=", (int)(eq - tk[1]), in + tk[1]);
736 if (literal_word(in, tk, tmp, &tl) && !(flags & 32)) put_q(&os, in + eq + 1, tk[1] + tk[2] - eq - 1);
737 else os += sprintf(os, "?");
738 } else {
739 any = 1;
740 if (oa != argv) *oa++ = ',';
741 if (literal_word(in, tk, tmp, &tl)) put_q(&oa, tmp, tl);
742 else oa += sprintf(oa, "?");
743 }
744 t++;
745 } else {
746 static const char *KN[12] = { "", "", "", "", "", "", "IN", "OUT", "APPEND", "", "DUP", "DUP" };
747 const uint64_t *tg = &w[OSH_TOKENS + 4 * (t + 1)];
748 if (orr != rd) *orr++ = ',';
749 orr += sprintf(orr, "%s%llu:", KN[kind], (unsigned long long)tk[3]);
750 if (kind == 10 || kind == 11) orr += sprintf(orr, "%c", in[tg[1]]);
751 else if (literal_word(in, tg, tmp, &tl)) put_q(&orr, tmp, tl);
752 else orr += sprintf(orr, "?");
753 t += 2;
754 }
755 }
756 *oa = *os = *orr = 0;
757 o += sprintf(o, "%s as=%s rd=%s", dollar ? "*" : argv, as, rd);
758 }
759 }
760 *o = 0;
761}
762
763/* match the rendered form against an expected line tail; `?` skips one expected item, `*` skips an argv list, and
764 * `b=?` skips the builtin id */
765static int item_end(const char *e)
766{
767 int i = 0;
768 if (e[0] == '"') {
769 i = 1;
770 while (e[i] && e[i] != '"') i += e[i] == '\\' ? 2 : 1;
771 return e[i] ? i + 1 : i;
772 }
773 while (e[i] && e[i] != ',' && e[i] != ' ') i++;
774 return i;
775}
776
777/* the vector grammar's `"c"*N` shorthand: N repetitions of c inside quotes */
778static void expand_rep(const char *e, char *out)
779{
780 while (*e) {
781 if (e[0] == '"' && e[1] && e[1] != '\\' && e[2] == '"' && e[3] == '*' && e[4] >= '0' && e[4] <= '9') {
782 char ch = e[1];
783 char *end;
784 unsigned long cnt = strtoul(e + 4, &end, 10);
785 *out++ = '"';
786 memset(out, ch, cnt);
787 out += cnt;
788 *out++ = '"';
789 e = end;
790 continue;
791 }
792 *out++ = *e++;
793 }
794 *out = 0;
795}
796
797static int match(const char *r, const char *e)
798{
799 while (*r) {
800 if (r[0] == 'b' && r[1] == '=' && r[2] == '?') {
801 if (strncmp(e, "b=", 2) != 0) return 0;
802 r += 3;
803 e += 3;
804 while (*e >= '0' && *e <= '9') e++;
805 } else if (r[0] == '*') {
806 r++;
807 while (*e && strncmp(e, " as=", 4) != 0) e++;
808 } else if (r[0] == '?') {
809 r++;
810 e += item_end(e);
811 } else {
812 if (*r != *e) return 0;
813 r++;
814 e++;
815 }
816 }
817 return *e == 0;
818}
819
820static void run_vector_dir(const char *dir, uint64_t *rng)
821{
822 char path[1024];
823 snprintf(path, sizeof path, "%s/expected.txt", dir);
824 size_t el;
825 char *exp = slurp(path, &el);
826 check(exp != NULL, "cannot read %s", path);
827 if (!exp) return;
828 exp = realloc(exp, el + 1);
829 exp[el] = 0;
830 for (char *line = strtok(exp, "\n"); line; line = strtok(NULL, "\n")) {
831 if (line[0] != 'v') continue;
832 char name[16];
833 if (sscanf(line, "%15s", name) != 1) continue;
834 snprintf(path, sizeof path, "%s/%s.in", dir, name);
835 size_t n;
836 char *in = slurp(path, &n);
837 check(in != NULL, "cannot read %s", path);
838 if (!in) continue;
839 Outcome o0, o1;
840 run_all(name, (const uint8_t *)in, n, rng, n_vec, &o0, &o1);
841 n_vec++;
842 uint64_t *w = sess_new();
843 int fl;
844 uint64_t st = host_run(INTERP, w, (const uint8_t *)in, n, &fl);
845 const char *p;
846 if (strstr(line, " more")) {
847 check(st == 100 && o0.status == 100, "vector %s: status %llu, want 100", name, (unsigned long long)st);
848 check(o1.status >= 200, "vector %s: with end of input the status is %llu, want a refusal", name, (unsigned long long)o1.status);
849 } else if ((p = strstr(line, " refuse "))) {
850 unsigned code = 0, off = 0;
851 if (sscanf(p, " refuse %u %*s off=%u", &code, &off) != 2) check(0, "%s: bad refuse line", name);
852 if (code >= 244 && code <= 245) { /* the expander's: the parser must finish the list */
853 check(st == 0, "vector %s: parser status %llu, want 0 (expander refusal %u)", name, (unsigned long long)st, code);
854 } else {
855 check(st == code && w[OSH_S_ERR_OFF] == off, "vector %s: refusal %llu@%llu, want %u@%u", name, (unsigned long long)st,
856 (unsigned long long)w[OSH_S_ERR_OFF], code, off);
857 }
858 } else if ((p = strstr(line, " | P0"))) {
859 check(st == 0 && !fl, "vector %s: status %llu, want 0 (list complete)", name, (unsigned long long)st);
860 if (st == 0) {
861 char *r = malloc(1 << 16);
862 render((const uint8_t *)in, w, r);
863 char *exp_tail = malloc(1 << 16);
864 expand_rep(p + 3, exp_tail);
865 int m = match(r, exp_tail);
866 if (!m) fprintf(stderr, " vector %s:\n rendered %s\n expected %s\n", name, r, exp_tail);
867 check(m, "vector %s: parse tables do not match the expected line", name);
868 free(exp_tail);
869 free(r);
870 }
871 } else {
872 check(st == 0, "vector %s: status %llu, want 0", name, (unsigned long long)st);
873 }
874 n_vec_parse++;
875 free(w);
876 free(in);
877 }
878 free(exp);
879}
880
881/* ---- fuzz ---- */
882static const char *FRAG[] = {
883 "ls", "echo", " ", " ", " ", "\t", "\n", "\n", "-l", "/tmp", "a", "b", "x=1", "A=", "_n", "0", "1", "2", "3",
884 "'x y'", "\"a b\"", "\"$B c\"", "\"$(x)\"", "'", "\"", "\\", "\\\n", "$", "$1", "$?", "$@", "$$", "${V}", "${", "}", "{", "$(", ")", "(", "`", "*",
885 "~", "{a,b}", "!", "#", "# c\n", "|", "||", "&&", "&", ";", ";;", "<", ">", ">>", ">&", "<&", "<<", ">|", "<>", "2>", "2>&1", "1>>", "0<",
886 "5>", "=", ":", "\xff", "if", "then", "fi", "for", "do", "done", "case", "esac", "while", "until", "in", "function", "!", "time", "select",
887 "coproc", "elif", "else", "IFS=", "IFS=x", "IF\\\nS=1", "i\\\nf", "{ ", " }", ">&1", ">&2", "<&0", ">&3", ">&-", ">&f", ">&10",
888};
889
890/* fragments that mostly parse clean, so the tables get exercised */
891static const char *SAFE[] = {
892 "ls", "echo", "cat", " ", " ", " ", " ", "\t", "\n", "-l", "/tmp", "a", "b", "x=1", "A=", "_n", "0", "1", "10", "'x y'", "\"a b\"", "\"$B c\"", "$1",
893 "$?", "$@", "${V}", "|", "|", "||", "&&", ";", ";", "<", ">", ">>", ">&", "<&", "2>", "2>&1", "1>>", "0<", "2", "1", "0", "f", "out", "# c\n", "\\\n",
894 "iff", "ifx", "'if'", "IFSx=1",
895};
896
897/* well-formed pieces for the capacity edges */
898static size_t gen(uint8_t *buf, size_t cap, uint64_t *rng)
899{
900 size_t n = 0;
901 unsigned mode = (unsigned)(rng_next(rng) % 10);
902 if (mode == 0) { /* raw bytes */
903 size_t len = rng_next(rng) % 40;
904 for (size_t i = 0; i < len; i++) buf[n++] = (uint8_t)rng_next(rng);
905 } else if (mode <= 4) { /* mostly clean fragments */
906 size_t nf = 1 + rng_next(rng) % 40;
907 for (size_t i = 0; i < nf; i++) {
908 const char *f = SAFE[rng_next(rng) % (sizeof SAFE / sizeof SAFE[0])];
909 size_t fl = strlen(f);
910 memcpy(buf + n, f, fl);
911 n += fl;
912 }
913 if (rng_next(rng) % 4 != 0) buf[n++] = '\n';
914 } else if (mode == 5 || mode == 6) { /* a repeated unit: reaches the capacity edges */
915 static const char *UNIT[] = { "a ", "A=1 ", ">f ", "a|", "a;", "a&&", "a||", "a|a;", "b ", "2>&1 ", "a\n" };
916 const char *u = UNIT[rng_next(rng) % (sizeof UNIT / sizeof UNIT[0])];
917 size_t reps = 1 + rng_next(rng) % 40;
918 size_t ul = strlen(u);
919 if (rng_next(rng) % 3 == 0) { const char *pre = "cmd "; memcpy(buf + n, pre, 4); n += 4; }
920 for (size_t i = 0; i < reps && n + ul < cap - 8; i++) { memcpy(buf + n, u, ul); n += ul; }
921 if (rng_next(rng) % 3 != 0) { buf[n++] = 'z'; }
922 if (rng_next(rng) % 4 != 0) buf[n++] = '\n';
923 } else { /* hostile fragments */
924 size_t nf = 1 + rng_next(rng) % (mode == 9 ? 60 : 14);
925 for (size_t i = 0; i < nf; i++) {
926 const char *f = FRAG[rng_next(rng) % (sizeof FRAG / sizeof FRAG[0])];
927 size_t fl = strlen(f);
928 if (n + fl > cap) break;
929 memcpy(buf + n, f, fl);
930 n += fl;
931 }
932 if (rng_next(rng) % 4 != 0 && n < cap) buf[n++] = '\n';
933 if (rng_next(rng) % 8 == 0 && n) buf[rng_next(rng) % n] = (uint8_t)rng_next(rng);
934 }
935 return n;
936}
937
938static void run_fuzz(unsigned long count, uint64_t *rng)
939{
940 uint8_t *buf = malloc(8192);
941 for (unsigned long i = 0; i < count; i++) {
942 size_t n = gen(buf, 8000, rng);
943 Outcome o0, o1;
944 run_all("fuzz", buf, n, rng, i, &o0, &o1);
945 n_fuzz++;
946 for (int k = 0; k < 2; k++) {
947 const Outcome *o = k ? &o1 : &o0;
948 if (o->status == 0) n_outcome[0]++;
949 else if (o->status == 100) n_outcome[1]++;
950 else if (o->status >= 200) { n_outcome[o->from_lexer ? 2 : 3]++; n_code[o->status & 255]++; }
951 }
952 }
953 free(buf);
954}
955
956int main(int argc, char **argv)
957{
958 if (argc < 5) {
959 fprintf(stderr, "usage: test_osh_parse OSH_LEX_OSC OSH_PARSE_OSC VECTORS_DIR PARSE_VECTORS_DIR [FUZZ_COUNT]\n");
960 return 2;
961 }
962 unsigned long fuzz = argc > 5 ? strtoul(argv[5], NULL, 10) : 100000;
963 check(OSH_WS_CELLS == 11456 && OSH_TOKENS == 64 && OSH_CMDS == 576 && OSH_PIPES == 832 && OSH_STAGING == 896 && OSH_REQUEST == 1928 &&
964 OSH_OUT == 3264 && OSH_ABI_MAGIC == 0x4F534857ULL && OSH_S_ERR_CODE == 4 && OSH_S_ERR_OFF == 5 && OSH_S_RESERVED == 48 &&
965 OSH_CAP_CMDS == 32 && OSH_CAP_PIPES == 16 && OSH_CAP_PIPE_LEN == 8 && OSH_CAP_WORDS == 32 && OSH_CAP_ASSIGNS == 16 &&
966 OSH_CAP_REDIRS == 8 && OSH_PARSE_BUDGET == 64 && OSH_CMDS + 8 * OSH_CAP_CMDS == OSH_PIPES && OSH_PIPES + 4 * OSH_CAP_PIPES == OSH_STAGING,
967 "generated layout differs from the ABI draft numbers");
968 char *src1 = NULL, *src2 = NULL;
969 if (unit_load(&LEX, argv[1], &src1) || unit_load(&PARSE, argv[2], &src2)) { printf("OSH_PARSE_FAIL\n"); return 1; }
970 unit_stats("lex ", &LEX);
971 unit_stats("parse", &PARSE);
972
973 uint64_t rng = 0x05a1e0c0ffee0005ULL;
974 run_abi();
975 run_hostile(&rng);
976 run_vector_dir(argv[3], &rng);
977 run_vector_dir(argv[4], &rng);
978 run_fuzz(fuzz, &rng);
979
980 printf("hostile cases: %lu (each: interp, native, reference, chunked, with the end-of-input flag clear and set)\n", n_hostile);
981 printf("vectors: %lu run, %lu parser-level checks (plus ABI checks)\n", n_vec, n_vec_parse);
982 printf("fuzz: %lu inputs x 2 flag settings (seed fixed): list done=%lu need more=%lu lexer refused=%lu parser refused=%lu\n", n_fuzz, n_outcome[0], n_outcome[1], n_outcome[2], n_outcome[3]);
983 printf("refusal codes seen in fuzz:");
984 for (int c = 0; c < 256; c++) if (n_code[c]) printf(" %d:%lu", c, n_code[c]);
985 printf("\n");
986 printf("cases %lu; interp calls %lu; native calls %lu; interp==native workspace compares %lu; reference compares %lu (%lu command rows, %lu pipeline rows); idempotence repeats %lu; chunked host runs %lu; traps %lu\n",
987 n_cases, n_calls_i, n_calls_n, n_engine_cmp, n_ref_cmp, n_cmds_cmp, n_pipes_cmp, n_idem, n_chunk_runs, n_traps);
988 printf("checks %lu, failures %lu\n", n_checks, n_fail);
989 osc_native_unmap(&LEX.nm);
990 osc_native_unmap(&PARSE.nm);
991 osc_cg_free(&LEX.code);
992 osc_cg_free(&PARSE.code);
993 free(src1);
994 free(src2);
995 int ok = n_fail == 0;
996 printf(ok ? "OSH_PARSE_PASS\n" : "OSH_PARSE_FAIL\n");
997 return ok ? 0 : 1;
998}