nish 0.20.0 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +23 -59
  2. package/docs/AI.md +74 -9
  3. package/docs/INSTALL.md +52 -10
  4. package/llms.txt +1 -1
  5. package/package.json +20 -5
  6. package/runtime/browser.d.ts +6 -0
  7. package/runtime/browser.mjs +77 -0
  8. package/runtime/core/arrays.d.ts +36 -0
  9. package/runtime/core/arrays.mjs +153 -0
  10. package/runtime/core/checks.mjs +20 -0
  11. package/runtime/core/host.d.ts +80 -0
  12. package/runtime/core/host.mjs +325 -0
  13. package/runtime/core/numbers.d.ts +66 -0
  14. package/runtime/core/numbers.mjs +343 -0
  15. package/runtime/core/result.d.ts +45 -0
  16. package/runtime/core/result.mjs +140 -0
  17. package/runtime/core/strings.d.ts +14 -0
  18. package/runtime/core/strings.mjs +169 -0
  19. package/runtime/core.d.ts +9 -0
  20. package/runtime/core.mjs +55 -0
  21. package/runtime/host.d.ts +6 -0
  22. package/runtime/nish.d.ts +46 -2
  23. package/runtime/nish.h +75 -2
  24. package/runtime/nish.mjs +23 -3
  25. package/runtime/node.mjs +386 -0
  26. package/runtime/runtime-bytes.c +401 -0
  27. package/runtime/runtime-cross.c +1 -1
  28. package/runtime/runtime-host.c +1 -1
  29. package/runtime/runtime-net.c +12 -1
  30. package/runtime/runtime-os.c +1 -1
  31. package/runtime/runtime-parallel.c +1 -1
  32. package/runtime/runtime-simd.c +231 -7
  33. package/runtime/runtime-term.c +504 -0
  34. package/runtime/runtime-wasm.c +0 -11
  35. package/runtime/runtime.c +190 -6
  36. package/runtime/shim.mjs +6 -985
  37. package/runtime/sqlite/LICENSE.md +85 -0
  38. package/runtime/sqlite/README.md +45 -0
  39. package/runtime/sqlite/nish-sqlite.c +359 -0
  40. package/runtime/sqlite/sqlite3.c +271131 -0
  41. package/runtime/sqlite/sqlite3.h +14447 -0
  42. package/scripts/build.sh +311 -59
  43. package/scripts/check-hardening.mjs +202 -0
  44. package/scripts/fuzz.sh +218 -0
  45. package/scripts/gen-json-pow5.mjs +130 -0
  46. package/scripts/platform-package.mjs +3 -1
  47. package/scripts/security-scope.mjs +139 -0
  48. package/scripts/smoke.sh +3 -2
  49. package/std/LICENSE-fast-float +23 -0
  50. package/std/LICENSE-fdlibm +8 -0
  51. package/std/README.md +32 -12
  52. package/std/base64.ts +116 -0
  53. package/std/bytes.ts +256 -0
  54. package/std/cli.ts +344 -0
  55. package/std/collections.ts +6 -5
  56. package/std/crypto/LICENSE-crypt_blowfish +26 -0
  57. package/std/crypto/base64url.ts +125 -0
  58. package/std/crypto/bcrypt.ts +1557 -0
  59. package/std/crypto/hmac.ts +138 -2
  60. package/std/crypto/x509.ts +11 -122
  61. package/std/json-tokenizer.ts +2998 -57
  62. package/std/json-value.ts +22 -3
  63. package/std/json.ts +87 -8
  64. package/std/math.ts +608 -0
  65. package/std/net/http1-server.ts +282 -40
  66. package/std/net/http1.ts +40 -21
  67. package/std/net/http3-server.ts +50 -12
  68. package/std/net/postgres.ts +2294 -0
  69. package/std/net/prefork.ts +23 -3
  70. package/std/net/quic-listener.ts +20 -4
  71. package/std/random.ts +66 -4
  72. package/std/regex.ts +4274 -0
  73. package/std/sqlite.ts +391 -0
  74. package/std/term-io.ts +978 -0
  75. package/std/term-pixels.ts +874 -0
  76. package/std/term-probe.ts +459 -0
  77. package/std/term-rate.ts +993 -0
  78. package/std/term.ts +2453 -0
  79. package/std/text.ts +90 -7
  80. package/std/yaml-lines.ts +141 -0
  81. package/std/yaml.ts +4675 -0
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env node
2
+ // Reads the hardening a native binary carries, from its headers rather than
3
+ // from the flags that should have put it there.
4
+ //
5
+ // node scripts/check-hardening.mjs <binary> [--imports name,name,...]
6
+ //
7
+ // An ELF binary must be position independent (DYN), carry GNU_RELRO, bind now
8
+ // (DF_BIND_NOW or DF_1_NOW), have a GNU_STACK header without E, and carry
9
+ // control-flow protection: the x86 feature note naming IBT and SHSTK, or on
10
+ // AArch64 the feature note naming BTI and PAC, or failing that `bti` and
11
+ // `paciasp` in its code. The note is the linker's AND over every object, the C
12
+ // library's start files included, so the instructions are what show that the
13
+ // objects scripts/build.sh compiled carry the protection when a start file
14
+ // does not. A Mach-O binary must be MH_PIE and must not be
15
+ // MH_ALLOW_STACK_EXECUTION.
16
+ //
17
+ // `--imports` names undefined symbols the binary must import, without
18
+ // Mach-O's leading underscore: `__stack_chk_fail` shows the stack protector
19
+ // reached it, and a `__*_chk` function shows _FORTIFY_SOURCE did. Whether one
20
+ // appears depends on the code linked, so the caller names them. Exits 0 when
21
+ // every property holds, 1 naming the ones that do not, and 2 when no tool to
22
+ // read the binary is installed. tests/run.js ("hardening") and CI's
23
+ // `bootstrap` job call it (docs/security/runtime.md, RT-HARDEN).
24
+
25
+ import { spawnSync } from "node:child_process"
26
+ import fs from "node:fs"
27
+ import path from "node:path"
28
+
29
+ /** The first of `names` that runs, or null. */
30
+ const firstTool = (names) =>
31
+ names.find((name) => spawnSync(name, ["--version"], { encoding: "utf8" }).status === 0) ?? null
32
+
33
+ const run = (tool, args) => {
34
+ const r = spawnSync(tool, args, { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 })
35
+ return r.status === 0 ? r.stdout : null
36
+ }
37
+
38
+ const ELF_MAGIC = "7f454c46"
39
+ const MACHO_MAGICS = ["cffaedfe", "cefaedfe", "feedfacf", "feedface"]
40
+
41
+ const magicOf = (file) => {
42
+ const fd = fs.openSync(file, "r")
43
+ const buf = Buffer.alloc(4)
44
+ fs.readSync(fd, buf, 0, 4, 0)
45
+ fs.closeSync(fd)
46
+ return buf.toString("hex")
47
+ }
48
+
49
+ const elfProblems = (file, imports) => {
50
+ const readelf = firstTool(["llvm-readelf", "llvm-readelf-18", "readelf"])
51
+ if (readelf === null) {
52
+ return { skip: "no llvm-readelf or readelf on PATH", problems: [] }
53
+ }
54
+ const out = run(readelf, ["-W", "-h", "-l", "-d", "-n", "--dyn-syms", file])
55
+ if (out === null) {
56
+ return { skip: null, problems: [`${readelf} could not read ${file}`] }
57
+ }
58
+ const problems = []
59
+ const type = /^\s*Type:\s+(\S+)/m.exec(out)
60
+ if (type === null || type[1] !== "DYN") {
61
+ problems.push(`not position independent: Type is ${type === null ? "missing" : type[1]}, not DYN`)
62
+ }
63
+ if (!/^\s*GNU_RELRO\s/m.test(out)) {
64
+ problems.push("no GNU_RELRO program header (-z relro)")
65
+ }
66
+ const flags = /\(FLAGS\)\s+(.*)$/m.exec(out)
67
+ const flags1 = /\(FLAGS_1\)\s+(.*)$/m.exec(out)
68
+ const bindNow =
69
+ (flags !== null && /\bBIND_NOW\b/.test(flags[1])) || (flags1 !== null && /\bNOW\b/.test(flags1[1]))
70
+ if (!bindNow) {
71
+ problems.push("does not bind now: no BIND_NOW in FLAGS or NOW in FLAGS_1 (-z now), so RELRO is partial")
72
+ }
73
+ const stack = /^\s*GNU_STACK\s+(?:0x[0-9a-f]+\s+){5}([RWE ]{3})/m.exec(out)
74
+ if (stack === null) {
75
+ problems.push("no GNU_STACK program header, so the stack may be executable (-z noexecstack)")
76
+ } else if (stack[1].includes("E")) {
77
+ problems.push(`the stack is executable: GNU_STACK flags are "${stack[1].trim()}"`)
78
+ }
79
+ const machine = /^\s*Machine:\s+(.*)$/m.exec(out)
80
+ const machineName = machine === null ? "" : machine[1]
81
+ if (/X86-64/.test(machineName)) {
82
+ const note = /x86 feature:\s*(.*)$/m.exec(out)
83
+ if (note === null || !/\bIBT\b/.test(note[1]) || !/\bSHSTK\b/.test(note[1])) {
84
+ problems.push(
85
+ `no control-flow protection: the x86 feature note is ${note === null ? "missing" : `"${note[1].trim()}"`}, not IBT, SHSTK (-fcf-protection=full)`
86
+ )
87
+ }
88
+ } else if (/AArch64/.test(machineName)) {
89
+ const note = /AArch64 feature:\s*(.*)$/m.exec(out)
90
+ if (note === null || !/\bBTI\b/.test(note[1]) || !/\bPAC\b/.test(note[1])) {
91
+ problems.push(...aarch64CodeProblems(file))
92
+ }
93
+ }
94
+ const undefinedNames = new Set(
95
+ out
96
+ .split("\n")
97
+ .filter((line) => /\sUND\s/.test(line))
98
+ .map((line) => line.trim().split(/\s+/).at(-1).replace(/@.*$/, ""))
99
+ )
100
+ for (const name of imports) {
101
+ if (!undefinedNames.has(name)) {
102
+ problems.push(`does not import ${name}`)
103
+ }
104
+ }
105
+ return { skip: null, problems }
106
+ }
107
+
108
+ /** Without the feature note, the protection shown in the instructions themselves. */
109
+ const aarch64CodeProblems = (file) => {
110
+ const objdump = firstTool(["llvm-objdump", "llvm-objdump-18", "objdump"])
111
+ if (objdump === null) {
112
+ return ["no AArch64 feature note naming BTI and PAC, and no llvm-objdump to look for the instructions"]
113
+ }
114
+ const code = run(objdump, ["-d", "--no-show-raw-insn", file]) ?? ""
115
+ const problems = []
116
+ if (!/\sbti\b/.test(code)) {
117
+ problems.push(
118
+ "no BTI: neither the AArch64 feature note nor a `bti` instruction (-mbranch-protection=standard)"
119
+ )
120
+ }
121
+ if (!/\spaciasp\b/.test(code)) {
122
+ problems.push(
123
+ "no return-address signing: neither the AArch64 feature note nor a `paciasp` instruction (-mbranch-protection=standard)"
124
+ )
125
+ }
126
+ return problems
127
+ }
128
+
129
+ const machoProblems = (file, imports) => {
130
+ const readobj = firstTool(["llvm-readobj", "llvm-readobj-18"])
131
+ if (readobj === null) {
132
+ return { skip: "no llvm-readobj on PATH", problems: [] }
133
+ }
134
+ const header = run(readobj, ["--file-headers", file])
135
+ if (header === null) {
136
+ return { skip: null, problems: [`${readobj} could not read ${file}`] }
137
+ }
138
+ const problems = []
139
+ if (!/\bMH_PIE\b/.test(header)) {
140
+ problems.push("not position independent: no MH_PIE flag")
141
+ }
142
+ if (/\bMH_ALLOW_STACK_EXECUTION\b/.test(header)) {
143
+ problems.push("the stack is executable: MH_ALLOW_STACK_EXECUTION is set")
144
+ }
145
+ if (imports.length > 0) {
146
+ const nm = firstTool(["llvm-nm", "llvm-nm-18", "nm"])
147
+ const names = new Set(
148
+ (nm === null ? "" : (run(nm, ["-u", file]) ?? ""))
149
+ .split("\n")
150
+ .map((line) => line.trim().split(/\s+/).at(-1) ?? "")
151
+ .map((name) => (name.startsWith("_") ? name.slice(1) : name))
152
+ )
153
+ for (const name of imports) {
154
+ if (!names.has(name)) {
155
+ problems.push(`does not import ${name}`)
156
+ }
157
+ }
158
+ }
159
+ return { skip: null, problems }
160
+ }
161
+
162
+ /**
163
+ * What `file` lacks of the hardening, or why it could not be read: `skip` is
164
+ * the missing tool, and `problems` is empty when every property holds.
165
+ */
166
+ export const hardeningProblems = (file, imports = []) => {
167
+ const magic = magicOf(file)
168
+ if (magic === ELF_MAGIC) {
169
+ return elfProblems(file, imports)
170
+ }
171
+ if (MACHO_MAGICS.includes(magic)) {
172
+ return machoProblems(file, imports)
173
+ }
174
+ return { skip: null, problems: [`${file} is neither ELF nor Mach-O (magic ${magic})`] }
175
+ }
176
+
177
+ const main = () => {
178
+ const args = process.argv.slice(2)
179
+ const at = args.indexOf("--imports")
180
+ const imports = at < 0 ? [] : (args[at + 1] ?? "").split(",").filter((name) => name !== "")
181
+ const files = at < 0 ? args : args.filter((_, i) => i !== at && i !== at + 1)
182
+ if (files.length !== 1 || (at >= 0 && imports.length === 0)) {
183
+ process.stderr.write("usage: node scripts/check-hardening.mjs <binary> [--imports name,name,...]\n")
184
+ process.exit(2)
185
+ }
186
+ const result = hardeningProblems(files[0], imports)
187
+ if (result.skip !== null) {
188
+ process.stderr.write(`check-hardening: ${result.skip}\n`)
189
+ process.exit(2)
190
+ }
191
+ if (result.problems.length > 0) {
192
+ for (const problem of result.problems) {
193
+ process.stderr.write(`check-hardening: ${files[0]}: ${problem}\n`)
194
+ }
195
+ process.exit(1)
196
+ }
197
+ process.stdout.write(`check-hardening: ${files[0]}: hardened\n`)
198
+ }
199
+
200
+ if (path.resolve(process.argv[1] ?? "") === import.meta.filename) {
201
+ main()
202
+ }
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env bash
2
+ # Build, run and replay the libFuzzer targets in tests/fuzz/targets/.
3
+ #
4
+ # scripts/fuzz.sh --build <name> build/fuzz/bin/<name>
5
+ # scripts/fuzz.sh --run <name> [-- <libFuzzer args>]
6
+ # fuzz it, growing its corpus
7
+ # scripts/fuzz.sh --replay [<name>] every corpus and regression
8
+ # input once; a crash fails
9
+ # scripts/fuzz.sh --smoke every target: build, replay,
10
+ # then a short fixed-seed run
11
+ #
12
+ # A target is `tests/fuzz/targets/<name>.ts` exporting
13
+ # `export const fuzzOne = (data: u8[]): void` (tests/fuzz/README.md). It is
14
+ # compiled to a library .ll with the repository's compiler and std, and linked
15
+ # with tests/fuzz/harness.c and the runtime under
16
+ # `-fsanitize=fuzzer,address,undefined`, with the runtime built
17
+ # `-DNISH_FUZZ_ABORT` so a panic, a failed bounds or division check and an
18
+ # out-of-memory are crashes. The runtime units are linked from source, so a
19
+ # change to runtime/ needs nothing but a rebuild.
20
+ #
21
+ # Environment:
22
+ # NISH the compiler (default build/nish; `npm run build`). It
23
+ # must be one built from this checkout: a compiler finds
24
+ # std/ beside itself, so the seed would fuzz its own std.
25
+ # FUZZ_SMOKE_SECONDS --smoke's fuzzing time per target (default 20)
26
+ # FUZZ_SEED --smoke's libFuzzer -seed (default 1)
27
+ # FUZZ_OUT where binaries, scratch corpora and artifacts go
28
+ # (default build/fuzz)
29
+ #
30
+ # Every libFuzzer run is given `-timeout=1` (an input over a second is a crash,
31
+ # as the target interface says) and `-rss_limit_mb=2048`, before the caller's
32
+ # own arguments, which may override them.
33
+ set -euo pipefail
34
+
35
+ root="$(cd "$(dirname "$0")/.." && pwd)"
36
+ cd "$root"
37
+
38
+ NISH="${NISH:-build/nish}"
39
+ FUZZ_OUT="${FUZZ_OUT:-build/fuzz}"
40
+ FUZZ_SMOKE_SECONDS="${FUZZ_SMOKE_SECONDS:-20}"
41
+ FUZZ_SEED="${FUZZ_SEED:-1}"
42
+ CC="${CC:-clang}"
43
+
44
+ # The runtime's C units: tests/run.js's RUNTIME_C, which its `fuzz` section
45
+ # checks this list against. runtime-wasm.c is wasm32's alone.
46
+ RUNTIME_C=(
47
+ runtime/runtime.c
48
+ runtime/runtime-os.c
49
+ runtime/runtime-parallel.c
50
+ runtime/runtime-cross.c
51
+ runtime/runtime-host.c
52
+ runtime/runtime-net.c
53
+ runtime/runtime-simd.c
54
+ runtime/runtime-aes.c
55
+ runtime/runtime-term.c
56
+ runtime/runtime-bytes.c
57
+ )
58
+
59
+ SAN_FLAGS=(-g -O1 "-fsanitize=fuzzer,address,undefined" -fno-sanitize-recover=undefined)
60
+ LIBFUZZER_DEFAULTS=(-timeout=1 -rss_limit_mb=2048)
61
+
62
+ die() {
63
+ echo "fuzz.sh: $*" >&2
64
+ exit 2
65
+ }
66
+
67
+ usage() {
68
+ sed -n '2,11p' "$0" | sed 's/^# \{0,1\}//' >&2
69
+ exit "${1:-2}"
70
+ }
71
+
72
+ targets() {
73
+ local f
74
+ for f in tests/fuzz/targets/*.ts; do
75
+ [ -e "$f" ] || continue
76
+ basename "$f" .ts
77
+ done
78
+ }
79
+
80
+ need_target() {
81
+ [ -f "tests/fuzz/targets/$1.ts" ] || die "no target tests/fuzz/targets/$1.ts"
82
+ }
83
+
84
+ # The runtime objects, compiled once per invocation of this script: every
85
+ # target links the same ones.
86
+ runtime_objs=()
87
+ build_runtime() {
88
+ [ ${#runtime_objs[@]} -eq 0 ] || return 0
89
+ [ -x "$NISH" ] || die "no compiler at $NISH: run \`npm run build\`, or set NISH"
90
+ command -v "$CC" >/dev/null || die "no $CC on PATH"
91
+ mkdir -p "$FUZZ_OUT/obj"
92
+ local src obj
93
+ for src in "${RUNTIME_C[@]}"; do
94
+ obj="$FUZZ_OUT/obj/$(basename "$src" .c).o"
95
+ "$CC" "${SAN_FLAGS[@]}" -DNISH_FUZZ_ABORT -Iruntime -c "$src" -o "$obj" \
96
+ || die "compiling $src under the sanitizers failed (is libclang-rt-18-dev installed?)"
97
+ runtime_objs+=("$obj")
98
+ done
99
+ "$CC" "${SAN_FLAGS[@]}" -DNISH_FUZZ_ABORT -Iruntime -c tests/fuzz/harness.c \
100
+ -o "$FUZZ_OUT/obj/harness.o"
101
+ runtime_objs+=("$FUZZ_OUT/obj/harness.o")
102
+ }
103
+
104
+ build() {
105
+ local name="$1"
106
+ need_target "$name"
107
+ build_runtime
108
+ local ir="$FUZZ_OUT/ir/$name"
109
+ rm -rf "$ir"
110
+ mkdir -p "$ir" "$FUZZ_OUT/bin"
111
+ if ! "$NISH" "tests/fuzz/targets/$name.ts" -o "$ir/" >"$ir.log" 2>&1; then
112
+ cat "$ir.log" >&2
113
+ die "$name: compile failed"
114
+ fi
115
+ # clang instruments only functions carrying `sanitize_address`, which the
116
+ # compiler never emits, so every definition is given it here; without it the
117
+ # compiled Nish code links under ASan uninstrumented. Every `define` line
118
+ # ends `) {` or `) #N {` (an attribute group), and `#N sanitize_address` is a
119
+ # valid mixed list. UBSan instruments in clang's frontend, so it never
120
+ # reaches a .ll: the compiled code's own bounds and division checks stand
121
+ # in for it. A define this misses fails the build rather than going quiet.
122
+ sed -i -E 's/^(define .*\) (#[0-9]+ )?)\{$/\1sanitize_address {/' "$ir"/*.ll
123
+ if grep -h '^define ' "$ir"/*.ll | grep -qv ' sanitize_address {$'; then
124
+ die "$name: a define in $ir/ was not given sanitize_address"
125
+ fi
126
+ # A library build writes one module per source module, the std modules the
127
+ # target imports included, and the link takes them all.
128
+ "$CC" "${SAN_FLAGS[@]}" -Wno-override-module "$ir"/*.ll "${runtime_objs[@]}" -lm \
129
+ -o "$FUZZ_OUT/bin/$name" || die "$name: link failed"
130
+ echo "fuzz.sh: built $FUZZ_OUT/bin/$name"
131
+ }
132
+
133
+ # The directories of inputs a target is replayed over: its seed corpus and its
134
+ # regressions, those that exist.
135
+ input_dirs() {
136
+ local d
137
+ for d in "tests/fuzz/corpus/$1" "tests/fuzz/regressions/$1"; do
138
+ [ -d "$d" ] && echo "$d"
139
+ done
140
+ return 0
141
+ }
142
+
143
+ replay() {
144
+ local name="$1" dirs
145
+ mapfile -t dirs < <(input_dirs "$name")
146
+ if [ ${#dirs[@]} -eq 0 ]; then
147
+ die "$name: no tests/fuzz/corpus/$name/ to replay"
148
+ fi
149
+ mkdir -p "$FUZZ_OUT/artifacts/$name"
150
+ # -runs=0 runs each input once and fuzzes nothing; nothing is written to the
151
+ # corpus directories.
152
+ "$FUZZ_OUT/bin/$name" "${LIBFUZZER_DEFAULTS[@]}" -runs=0 \
153
+ -artifact_prefix="$FUZZ_OUT/artifacts/$name/" "${dirs[@]}"
154
+ }
155
+
156
+ # Fuzz `name` with a scratch copy of its corpus as the first (written)
157
+ # directory, so the checked-in corpus only grows when someone copies inputs
158
+ # back by hand (tests/fuzz/README.md).
159
+ run() {
160
+ local name="$1"
161
+ shift
162
+ local work="$FUZZ_OUT/work/$name" dirs
163
+ mkdir -p "$work" "$FUZZ_OUT/artifacts/$name"
164
+ mapfile -t dirs < <(input_dirs "$name")
165
+ "$FUZZ_OUT/bin/$name" "${LIBFUZZER_DEFAULTS[@]}" \
166
+ -artifact_prefix="$FUZZ_OUT/artifacts/$name/" "$@" "$work" "${dirs[@]}"
167
+ }
168
+
169
+ [ $# -ge 1 ] || usage
170
+ mode="$1"
171
+ shift
172
+ case "$mode" in
173
+ --build)
174
+ [ $# -eq 1 ] || usage
175
+ build "$1"
176
+ ;;
177
+ --run)
178
+ [ $# -ge 1 ] || usage
179
+ name="$1"
180
+ shift
181
+ if [ $# -ge 1 ]; then
182
+ [ "$1" = "--" ] || usage
183
+ shift
184
+ fi
185
+ build "$name"
186
+ run "$name" "$@"
187
+ ;;
188
+ --replay)
189
+ if [ $# -eq 1 ]; then
190
+ names=("$1")
191
+ else
192
+ [ $# -eq 0 ] || usage
193
+ mapfile -t names < <(targets)
194
+ fi
195
+ for name in "${names[@]}"; do
196
+ build "$name"
197
+ replay "$name"
198
+ done
199
+ ;;
200
+ --smoke)
201
+ [ $# -eq 0 ] || usage
202
+ mapfile -t names < <(targets)
203
+ [ ${#names[@]} -gt 0 ] || die "no targets in tests/fuzz/targets/"
204
+ for name in "${names[@]}"; do
205
+ build "$name"
206
+ replay "$name"
207
+ rm -rf "$FUZZ_OUT/work/$name"
208
+ run "$name" -seed="$FUZZ_SEED" -max_total_time="$FUZZ_SMOKE_SECONDS" -print_final_stats=1
209
+ done
210
+ echo "fuzz.sh: smoke passed over ${#names[@]} targets"
211
+ ;;
212
+ -h | --help)
213
+ usage 0
214
+ ;;
215
+ *)
216
+ usage
217
+ ;;
218
+ esac
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Generate the power-of-five table of `std/json-tokenizer.ts`.
4
+ *
5
+ * node scripts/gen-json-pow5.mjs rewrite the table in std/json-tokenizer.ts
6
+ * node scripts/gen-json-pow5.mjs --check exit 1 if the table there differs by a byte
7
+ *
8
+ * The table is the region of `json-tokenizer.ts` between the
9
+ * `gen-json-pow5:begin` and `gen-json-pow5:end` lines: `jsonTokPowerOfFive`,
10
+ * which answers the 128-bit truncation of 5^q for q from -342 to 308 as two
11
+ * 64-bit words, high first, so 1,302 words. For q ≥ 0 it is 5^q shifted left
12
+ * or right until its top bit is bit 127, truncated. For q < 0 it is
13
+ * 2^b / 5^-q rounded up, for the b that puts its top bit there; while 5^-q
14
+ * fits in 64 bits (q ≥ -27) that b is z + 127, with z the bit length of 5^-q,
15
+ * and past it the quotient of 2^(2z + 128) is halved down to 128 bits.
16
+ *
17
+ * This is fast_float's `script/table_generation.py`, at commit 0de7a21,
18
+ * written again with BigInt: the table is computed with exact integer
19
+ * arithmetic, so a reader can check it rather than trust a transcription. The
20
+ * region lives inside `json-tokenizer.ts` rather than in a module of its own
21
+ * because a file under `std/` is a public `nish/` module.
22
+ *
23
+ * Adapted from fast_float (https://github.com/fastfloat/fast_float),
24
+ * include/fast_float/decimal_to_binary.h and script/table_generation.py.
25
+ * Copyright 2021 The fast_float authors. Used under the Boost Software License,
26
+ * Version 1.0; see std/LICENSE-fast-float.
27
+ */
28
+ import fs from "node:fs"
29
+ import path from "node:path"
30
+ import { fileURLToPath } from "node:url"
31
+
32
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
33
+ const target = path.join(root, "std", "json-tokenizer.ts")
34
+
35
+ /** `JSON_TOK_SMALLEST_POWER` and `JSON_TOK_LARGEST_POWER`. */
36
+ const SMALLEST = -342
37
+ const LARGEST = 308
38
+
39
+ const TOP = 1n << 127n
40
+ const LIMIT = 1n << 128n
41
+ const WORD = (1n << 64n) - 1n
42
+
43
+ /** The bit length of a positive BigInt. */
44
+ const bits = (n) => n.toString(2).length
45
+
46
+ const entries = []
47
+ for (let q = SMALLEST; q < 0; q++) {
48
+ const p = 5n ** BigInt(-q)
49
+ const z = BigInt(bits(p))
50
+ let c
51
+ if (q >= -27) {
52
+ c = (1n << (z + 127n)) / p + 1n
53
+ } else {
54
+ c = (1n << (2n * z + 128n)) / p + 1n
55
+ while (c >= LIMIT) {
56
+ c /= 2n
57
+ }
58
+ }
59
+ entries.push(c)
60
+ }
61
+ for (let q = 0; q <= LARGEST; q++) {
62
+ let p = 5n ** BigInt(q)
63
+ while (p < TOP) {
64
+ p *= 2n
65
+ }
66
+ while (p >= LIMIT) {
67
+ p /= 2n
68
+ }
69
+ entries.push(p)
70
+ }
71
+ for (const [i, c] of entries.entries()) {
72
+ if (c < TOP || c >= LIMIT) {
73
+ throw new Error(`gen-json-pow5: the entry for q = ${i + SMALLEST} does not have its top bit at bit 127`)
74
+ }
75
+ }
76
+
77
+ const words = entries.flatMap((c) => [c >> 64n, c & WORD])
78
+ const half = (w) => `0x${w.toString(16).padStart(8, "0")}`
79
+ const cases = words.flatMap((w, i) => [
80
+ ` case ${i}:`,
81
+ ` return jsonTokW64(${half(w >> 32n)}, ${half(w & 0xffffffffn)})`,
82
+ ])
83
+
84
+ const BEGIN = "// gen-json-pow5:begin"
85
+ const END = "// gen-json-pow5:end"
86
+ const region = [
87
+ `${BEGIN} -- generated by scripts/gen-json-pow5.mjs; edit that, not this.`,
88
+ "/**",
89
+ ` * The 128-bit truncation of 5^q, high word at \`2 × (q + ${-SMALLEST})\` and low word`,
90
+ ` * after it, for q from ${SMALLEST} to ${LARGEST}: for q ≥ 0, 5^q shifted until its top bit`,
91
+ " * is bit 127; for q < 0, 2^b / 5^-q rounded up, for the b that puts its top",
92
+ " * bit there. Upstream's `power_of_five_128`.",
93
+ " *",
94
+ " * A function over a `switch` rather than an array for `std/crypto/sha512.ts`'s",
95
+ " * reason: a module constant cannot be an array, and LLVM turns a `switch`",
96
+ " * whose every arm is a constant into one read-only table. `index` is computed",
97
+ " * from the exponent, which `numberF64` has bounded.",
98
+ " */",
99
+ "const jsonTokPowerOfFive = (index: i32): u64 => {",
100
+ " switch (index) {",
101
+ ...cases,
102
+ ` // Unreachable: \`jsonTokEiselLemire\` asks only for 0 to ${words.length - 1}.`,
103
+ " default:",
104
+ " return toU64(0)",
105
+ " }",
106
+ "}",
107
+ END,
108
+ ].join("\n")
109
+
110
+ const source = fs.readFileSync(target, "utf8")
111
+ const from = source.indexOf(BEGIN)
112
+ const to = source.indexOf(END)
113
+ if (from < 0 || to < from) {
114
+ console.error(`gen-json-pow5: no ${BEGIN} ... ${END} region in ${path.relative(root, target)}`)
115
+ process.exit(1)
116
+ }
117
+ const next = source.slice(0, from) + region + source.slice(to + END.length)
118
+
119
+ if (process.argv.includes("--check")) {
120
+ if (next !== source) {
121
+ console.error(
122
+ `gen-json-pow5: the table in ${path.relative(root, target)} is not what the generator writes; run node scripts/gen-json-pow5.mjs`
123
+ )
124
+ process.exit(1)
125
+ }
126
+ console.log(`gen-json-pow5: ${words.length} words, as generated`)
127
+ } else {
128
+ fs.writeFileSync(target, next)
129
+ console.log(`gen-json-pow5: wrote ${words.length} words to ${path.relative(root, target)}`)
130
+ }
@@ -80,7 +80,9 @@ const manifest = {
80
80
  // MAIN package, which has carried `std` in its own `files` all along --
81
81
  // so the fallback to `dist/` worked and the path a user actually gets did
82
82
  // not. See docs/wp12-release.md and wp19 §5a.
83
- files: ["bin", "runtime", "scripts", "std", "LICENSE", "INSTALL.md"],
83
+ // `docs` carries `AI.md`, which `nish --help` names to a coding agent by its
84
+ // absolute path, found under this package rather than the main one.
85
+ files: ["bin", "runtime", "scripts", "std", "docs", "LICENSE", "INSTALL.md"],
84
86
  repository: main.repository,
85
87
  bugs: main.bugs,
86
88
  homepage: main.homepage,