@amritk/nish-aarch64-linux 0.40.1 → 0.42.0

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.
package/runtime/runtime.c CHANGED
@@ -21,6 +21,12 @@
21
21
  * both use `-flto`, and the cold paths that lost the inlining are cold.
22
22
  */
23
23
  #define _POSIX_C_SOURCE 200809L
24
+ #ifdef NISH_ARENA_DEBUG
25
+ /* The debug arena's `madvise`, which POSIX leaves out (its `posix_madvise`
26
+ gives nothing back on glibc). */
27
+ #define _DEFAULT_SOURCE
28
+ #define _DARWIN_C_SOURCE
29
+ #endif
24
30
  #include <errno.h>
25
31
  #include <inttypes.h>
26
32
  #include <math.h>
@@ -197,11 +203,140 @@ NISH_TLS uint64_t nish_region_chunk;
197
203
  single allocation larger than this still gets a chunk of its own size. */
198
204
  #define NISH_REGION_CHUNK_MAX ((uint64_t)1 << 20)
199
205
 
206
+ #ifdef NISH_ARENA_DEBUG
207
+ /* ---- The debug arena (`--debug-arena`, `-DNISH_ARENA_DEBUG`;
208
+ docs/security/runtime.md, "The debug arena")
209
+ Every arena block is a chunk of its own, as under ASan: its pages are cut
210
+ from one address range reserved at the first allocation and never handed
211
+ out twice, with the header at the start of its first page and `cap` exact,
212
+ so the inline bump never fits again and every block, and every release,
213
+ comes through this file. A release or reset that frees a chunk retires it
214
+ instead: its pages go `PROT_NONE` and back to the system, but stay
215
+ reserved, so a stale reference faults at the read rather than reading what
216
+ the next allocation wrote there. The handler below names that fault before
217
+ the program dies of it. The bytes past the mark in the mark's own chunk
218
+ are not retired; with exact chunks there are none, as every mark but a
219
+ region's 0 sits at a chunk's end. A chunk C code malloc'd and linked in
220
+ (runtime-cross.c's) lies outside the range and is freed as always.
221
+ Memory only grows, since no address is reused: this is for tests and
222
+ fuzzing, never a release build. */
223
+ #include <signal.h>
224
+ #include <sys/mman.h>
225
+ static char *nish_debug_base; /* the reservation, PROT_NONE until a block is cut from it */
226
+ static uint64_t nish_debug_size;
227
+ static uint64_t nish_debug_next; /* the next unused byte's offset, taken atomically */
228
+ static uint64_t nish_debug_page;
229
+ static int nish_debug_state; /* 0 none, 1 reserving, 2 reserved */
230
+ static struct sigaction nish_debug_old_segv, nish_debug_old_bus;
231
+
232
+ /* A fault in the part of the reservation handed out so far is a stale arena
233
+ reference: say so, then put the default back and return, so the access
234
+ faults once more and the program dies of the signal, as its parent expects.
235
+ Any other fault, pages never handed out included, goes to the handler that
236
+ was there before. It runs on an alternate stack when the thread has one
237
+ (runtime-term.c's), so a stack overflow still reaches that handler. */
238
+ static void nish_debug_on_fault(int sig, siginfo_t *info, void *ctx) {
239
+ (void)ctx;
240
+ uintptr_t a = (uintptr_t)info->si_addr, base = (uintptr_t)nish_debug_base;
241
+ struct sigaction *old = sig == SIGSEGV ? &nish_debug_old_segv : &nish_debug_old_bus;
242
+ if (a >= base && a - base < __atomic_load_n(&nish_debug_next, __ATOMIC_RELAXED)) {
243
+ char msg[] = "nish: --debug-arena: stale arena reference at 0x0000000000000000: "
244
+ "the memory was released by the scope that allocated it\n";
245
+ char *hex = msg + sizeof "nish: --debug-arena: stale arena reference at 0x" - 1;
246
+ for (int i = 15; i >= 0; i--, a >>= 4) hex[i] = "0123456789abcdef"[a & 15];
247
+ nish_write_all(2, msg, sizeof msg - 1);
248
+ void (*hook)(void) = __atomic_load_n(&nish_fatal_hook, __ATOMIC_ACQUIRE);
249
+ if (hook) hook();
250
+ signal(sig, SIG_DFL);
251
+ return;
252
+ }
253
+ sigaction(sig, old, 0);
254
+ }
255
+
256
+ /* Reserve the range, once for every thread: as much address space as the
257
+ system lets a process have without committing it, from 1 TiB down to 1 GiB. */
258
+ static void nish_debug_reserve(void) {
259
+ int want = 0;
260
+ if (!__atomic_compare_exchange_n(&nish_debug_state, &want, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
261
+ while (__atomic_load_n(&nish_debug_state, __ATOMIC_ACQUIRE) != 2) {}
262
+ return;
263
+ }
264
+ long page = sysconf(_SC_PAGESIZE);
265
+ nish_debug_page = page > 0 ? (uint64_t)page : 4096;
266
+ for (uint64_t size = (uint64_t)1 << 40; size >= (uint64_t)1 << 30; size >>= 1) {
267
+ void *p = mmap(0, (size_t)size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
268
+ if (p != MAP_FAILED) {
269
+ nish_debug_base = p;
270
+ nish_debug_size = size;
271
+ break;
272
+ }
273
+ }
274
+ if (!nish_debug_base) nish_die("nish: --debug-arena: cannot reserve address space for the arena\n");
275
+ struct sigaction sa;
276
+ memset(&sa, 0, sizeof sa);
277
+ sa.sa_sigaction = nish_debug_on_fault;
278
+ sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK;
279
+ sigemptyset(&sa.sa_mask);
280
+ sigaction(SIGSEGV, &sa, &nish_debug_old_segv);
281
+ sigaction(SIGBUS, &sa, &nish_debug_old_bus);
282
+ __atomic_store_n(&nish_debug_state, 2, __ATOMIC_RELEASE);
283
+ }
284
+
285
+ static uint64_t nish_debug_span(uint64_t cap) {
286
+ return (sizeof(nish_chunk) + cap + nish_debug_page - 1) & ~(nish_debug_page - 1);
287
+ }
288
+
289
+ /* A chunk of `cap` bytes, header included, on pages no block had before. */
290
+ static nish_chunk *nish_debug_chunk(uint64_t cap) {
291
+ if (__atomic_load_n(&nish_debug_state, __ATOMIC_ACQUIRE) != 2) nish_debug_reserve();
292
+ if (cap > nish_debug_size - sizeof(nish_chunk) - nish_debug_page) nish_oom();
293
+ uint64_t span = nish_debug_span(cap);
294
+ uint64_t at = __atomic_fetch_add(&nish_debug_next, span, __ATOMIC_RELAXED);
295
+ if (at > nish_debug_size - span)
296
+ nish_die("nish: --debug-arena: the arena's address space is used up (no address is reused)\n");
297
+ char *p = nish_debug_base + at;
298
+ if (mprotect(p, (size_t)span, PROT_READ | PROT_WRITE) != 0) nish_oom();
299
+ return (nish_chunk *)p;
300
+ }
301
+
302
+ /* Whether `c` is one of the debug arena's chunks, not one C code malloc'd. */
303
+ static int nish_debug_owns(const void *c) {
304
+ uintptr_t a = (uintptr_t)c, base = (uintptr_t)nish_debug_base;
305
+ return nish_debug_base && a >= base && a - base < nish_debug_size;
306
+ }
307
+
308
+ /* Retire a chunk: every page of it unreadable and given back, its addresses
309
+ kept. A process at its limit of mappings (each retired run splits one) is
310
+ refused the `mprotect`; the chunk is then filled with 0xDB instead, which
311
+ reads as a pointer no system maps and a length no bounds check passes. */
312
+ static void nish_debug_retire(nish_chunk *c) {
313
+ uint64_t span = nish_debug_span(NISH_CHUNK_CAP(c));
314
+ if (mprotect(c, (size_t)span, PROT_NONE) == 0) madvise(c, (size_t)span, MADV_DONTNEED);
315
+ else memset(c, 0xDB, (size_t)span);
316
+ }
317
+
318
+ /* runtime-region.c's adopt drops an empty chunk through this. */
319
+ void nish_debug_drop(void *c) {
320
+ if (nish_debug_owns(c)) nish_debug_retire(c);
321
+ else free(c);
322
+ }
323
+ #endif
324
+
200
325
  /* Slow path (size 8-byte rounded): push a chunk (>= 64 KB, or a region's
201
326
  next size), bump from it. A region's chunks double from its first, up to
202
327
  NISH_REGION_CHUNK_MAX. */
203
328
  void *nish_arena_grow(uint64_t size) {
204
- #ifdef NISH_ASAN
329
+ #if defined NISH_ARENA_DEBUG
330
+ /* An exact chunk, as under ASan, of pages no block had before. `off` is the
331
+ whole chunk, so even a block the rounding left room after is alone in it. */
332
+ uint64_t cap = (size + 7) & ~(uint64_t)7;
333
+ if (cap < size) nish_oom();
334
+ nish_chunk *d = nish_debug_chunk(cap);
335
+ d->next = nish_arena.chunks;
336
+ d->cap = cap;
337
+ nish_arena = (struct nish_arena){ (char *)(d + 1), cap, cap, d };
338
+ return nish_arena.buf;
339
+ #elif defined NISH_ASAN
205
340
  /* An exact chunk leaves off == cap, so the inline bump never fits again and
206
341
  every block comes through here: one malloc, one redzone, per block. */
207
342
  uint64_t cap = size;
@@ -327,13 +462,17 @@ static void nish_free_until(nish_chunk *c, const nish_chunk *end) {
327
462
  between: what frees the older chunk frees the memory under it. */
328
463
  while (c != end) {
329
464
  nish_chunk *n = c->next;
465
+ #ifdef NISH_ARENA_DEBUG
466
+ if (!(c->cap & NISH_CHUNK_CARVED)) nish_debug_drop(c);
467
+ #else
330
468
  if (!(c->cap & NISH_CHUNK_CARVED)) free(c);
469
+ #endif
331
470
  c = n;
332
471
  }
333
472
  }
334
473
 
335
474
  void nish_reset_arena(void) {
336
- #ifdef NISH_ASAN
475
+ #if defined NISH_ASAN || defined NISH_ARENA_DEBUG
337
476
  /* Free everything, so a value read after the reset is a use after free. */
338
477
  nish_free_arena();
339
478
  return;
@@ -383,6 +522,10 @@ void nish_arena_release(uint64_t mark) {
383
522
  if (!c) return;
384
523
  nish_free_until(nish_arena.chunks, c);
385
524
  nish_arena = (struct nish_arena){ (char *)(c + 1), mark - (uintptr_t)(c + 1), NISH_CHUNK_CAP(c), c };
525
+ #ifdef NISH_ARENA_DEBUG
526
+ /* Never bump into what the mark gave back: the next block gets a chunk. */
527
+ nish_arena.cap = nish_arena.off;
528
+ #endif
386
529
  }
387
530
 
388
531
  /* Release back to `mark` while keeping the newest allocation; returns where it
@@ -414,6 +557,9 @@ void *nish_arena_keep(uint64_t mark, void *p) {
414
557
  memmove((void *)mark, p, size);
415
558
  nish_free_until(pc, c);
416
559
  nish_arena = (struct nish_arena){ (char *)(c + 1), mark + size - (uintptr_t)(c + 1), NISH_CHUNK_CAP(c), c };
560
+ #ifdef NISH_ARENA_DEBUG
561
+ nish_arena.cap = nish_arena.off;
562
+ #endif
417
563
  return (void *)mark;
418
564
  }
419
565
  /* Keeping a carved `pc` while the chunks under it go could free the one it
package/scripts/build.sh CHANGED
@@ -3,7 +3,7 @@
3
3
  #
4
4
  # scripts/build.sh <module.ll> [more .ll/.c files...] -o <out> [--profile debug|speed|size|wasm|wasm-host|wasi|napi]
5
5
  #
6
- # The C runtime is seventeen translation units and is named as one: an input
6
+ # The C runtime is eighteen translation units and is named as one: an input
7
7
  # <dir>/runtime.c also compiles <dir>/runtime-text.c, the strings and the digits
8
8
  # of numbers, <dir>/runtime-os.c, the half that wraps the
9
9
  # system calls (files, directories, subprocesses, the environment, the clock),
@@ -11,6 +11,7 @@
11
11
  # threads, <dir>/runtime-cross.c, the copies that carry a string or an array
12
12
  # from one thread's arena to another's, <dir>/runtime-host.c, the wall clock, entropy, file times and
13
13
  # signals, <dir>/runtime-net.c, the sockets of `nish:net`,
14
+ # <dir>/runtime-uring.c, the io_uring rings that will hold them past RLIMIT_NOFILE,
14
15
  # <dir>/runtime-simd.c, the byte searches that read a vector at a time and
15
16
  # the SSE4.1 rounding of `Math.floor` and its kin,
16
17
  # <dir>/runtime-aes.c, AES-GCM on the CPU's AES instructions,
@@ -93,6 +94,12 @@
93
94
  # thread-local global, and ELF will not link that against a non-TLS definition,
94
95
  # so a half-threaded build fails at the link rather than at run time.
95
96
  #
97
+ # Debug arena: `--debug-arena` compiles the runtime with -DNISH_ARENA_DEBUG, so
98
+ # every arena block gets pages of its own, never reused, and a release turns
99
+ # them PROT_NONE: a stale reference past its scope faults at the read and the
100
+ # runtime names it (docs/security/runtime.md, "The debug arena"). The IR is the
101
+ # same either way; `nish --debug-arena` passes it through. Native profiles only.
102
+ #
96
103
  # Debug info (WP10): `-g` compiles every input with -g and skips the strip
97
104
  # step of the speed/size/napi profiles, so the DWARF that `nish -g`
98
105
  # put in the .ll (line table, variables) reaches the binary. `nish
@@ -127,7 +134,7 @@
127
134
  #
128
135
  # The runtime compiled once (the debug, speed and size profiles only; `nish
129
136
  # --link` and `nish run` use these through their runtime cache, src/compile.ts):
130
- # --runtime-objects <dir> compile the runtime.c input, its sixteen halves and runtime-async.c,
137
+ # --runtime-objects <dir> compile the runtime.c input, its seventeen halves and runtime-async.c,
131
138
  # one $CC -c each and all at once, into
132
139
  # <dir>/<unit>.o with the profile's compile flags,
133
140
  # and link nothing. speed and size store LTO bitcode,
@@ -161,6 +168,7 @@ inputs=()
161
168
  pgo=() # -fprofile-generate / -fprofile-use=<file>
162
169
  debug=0 # -g: keep DWARF (nish -g emits it in the IR; runtime.c gets it here)
163
170
  threads=0 # --threads: -DNISH_THREADS, the thread-local arena (WP20 T0)
171
+ debug_arena=0 # --debug-arena: -DNISH_ARENA_DEBUG, the arena that traps a stale reference
164
172
  objects_to="" # --runtime-objects <dir>: compile the runtime alone, into <dir>
165
173
  objects_from="" # --runtime-from <dir>: link against the runtime compiled there
166
174
  cpu="" # --cpu x86-64-v3: the one CPU level above the baseline (WP38 S2)
@@ -176,6 +184,7 @@ while [ $# -gt 0 ]; do
176
184
  --profile) profile="$2"; shift 2 ;;
177
185
  -g) debug=1; shift ;;
178
186
  --threads) threads=1; shift ;;
187
+ --debug-arena) debug_arena=1; shift ;;
179
188
  --cpu)
180
189
  [ -n "${2-}" ] || { echo "error: --cpu needs a level; the one taken is x86-64-v3" >&2; exit 2; }
181
190
  cpu="$2"; shift 2 ;;
@@ -205,6 +214,11 @@ if [ -n "$cpu" ]; then
205
214
  wasm|wasm-host|wasi) echo "error: --cpu x86-64-v3 is an x86-64 level, so the $profile profile does not take it" >&2; exit 2 ;;
206
215
  esac
207
216
  fi
217
+ if [ "$debug_arena" = 1 ]; then
218
+ case "$profile" in
219
+ wasm|wasm-host|wasi|napi) echo "error: --debug-arena maps pages and catches SIGSEGV, so the $profile profile does not take it" >&2; exit 2 ;;
220
+ esac
221
+ fi
208
222
  if [ -n "$memory_mib" ] || [ -n "$inline_to" ]; then
209
223
  [ "$profile" = wasm-host ] || { echo "error: --memory and --inline take the wasm-host profile, not '$profile'" >&2; exit 2; }
210
224
  fi
@@ -272,9 +286,9 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
272
286
  fi
273
287
  [ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
274
288
 
275
- # The runtime is seventeen translation units, and a caller names one: whoever passes
289
+ # The runtime is eighteen translation units, and a caller names one: whoever passes
276
290
  # <dir>/runtime.c gets <dir>/runtime-text.c, <dir>/runtime-os.c, <dir>/runtime-parallel.c,
277
- # <dir>/runtime-cross.c, <dir>/runtime-host.c, <dir>/runtime-net.c, <dir>/runtime-simd.c,
291
+ # <dir>/runtime-cross.c, <dir>/runtime-host.c, <dir>/runtime-net.c, <dir>/runtime-uring.c, <dir>/runtime-simd.c,
278
292
  # <dir>/runtime-aes.c, <dir>/runtime-sha256.c, <dir>/runtime-chacha20.c, <dir>/runtime-checksum.c, <dir>/runtime-term.c,
279
293
  # <dir>/runtime-bytes.c, <dir>/runtime-sandbox.c, <dir>/runtime-shm.c and <dir>/runtime-region.c compiled beside it, on every profile,
280
294
  # wasi included: runtime-simd.c and runtime-bytes.c take their scalar paths there
@@ -283,7 +297,7 @@ fi
283
297
  # stubs that nothing calls, because the compiler emits no call to their kernels for wasm32, and
284
298
  # runtime-term.c reads stdin and answers "not a terminal", and runtime-sandbox.c
285
299
  # compiles to two functions that refuse to run, which no wasm build calls, and
286
- # runtime-shm.c answers -95 for every region. They were one file until the
300
+ # runtime-shm.c answers -95 for every region, and runtime-uring.c compiles to nothing. They were one file until the
287
301
  # operating-system half was split out for its own size budget, and the parallel
288
302
  # and text halves followed for the same reason (each file's header comment says why), and
289
303
  # a link line is where those splits
@@ -293,7 +307,7 @@ fi
293
307
  # here keeps every one of those correct, and keeps "the runtime" one thing to
294
308
  # name from the outside. A caller that names one itself is left alone, because
295
309
  # naming one object twice is a duplicate-symbol error.
296
- halves="runtime-text.c runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
310
+ halves="runtime-text.c runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-uring.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
297
311
  for i in ${inputs[@]+"${inputs[@]}"}; do
298
312
  case "$i" in
299
313
  */runtime.c|runtime.c)
@@ -518,6 +532,7 @@ if [ "$threads" = 1 ]; then
518
532
  common+=(-DNISH_THREADS=1 -ftls-model=initial-exec -pthread)
519
533
  tls=(-DNISH_THREADS=1 -ftls-model=initial-exec)
520
534
  fi
535
+ if [ "$debug_arena" = 1 ]; then common+=(-DNISH_ARENA_DEBUG=1); fi
521
536
 
522
537
  # What the speed and size profiles compile every input with, beside `common`.
523
538
  # One list per profile, because the runtime cache below compiles with exactly
package/std/README.md CHANGED
@@ -35,6 +35,7 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
35
35
  | [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#map-and-set)) |
36
36
  | [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-runs-skipblank-skipdigits-skipjsontext-skipjsonplain-and-copybytes-in-nishbytes)). The runs are variable-time. `tests/link/std_bytes*` are its programs |
37
37
  | [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string, `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array panics before a byte is written. It indexes its alphabet by the sextet, so it is not constant-time: it is for pixels, not secrets. A strict decoder, and an encoder for key material, are `crypto/base64url.ts`'s `base64StdPadDecode` and `base64StdPadEncode` (`tests/link/std_base64`, `std_base64_f64`, `std_base64_negative_*`; the two modules in one program: `tests/link/std_base64_two_modules`; [guide](../docs/guide/using-nish/standard-library.md#nishbase64)) |
38
+ | [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin. There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
38
39
  | [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, written with `nish:unsafe`'s `wrappingAdd`, `wrappingSub` and `wrappingMul` so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
39
40
  | [`cli.ts`](https://github.com/amritk/nish/blob/main/std/cli.ts) | a command-line tool's `--help`. `HelpMenu` builds it a line at a time — `header`, `usage`, `section`, `row(flag, placeholder, description)`, `note`, `value` — with descriptions lined up at the caller's columns, counted on the plain text, and answers it with `text()`. `Style` paints it in the basic ANSI colours, bold and faint, which the terminal's theme defines, or in bold and underline alone when `TERM` declares no colours; each role it paints (`heading`, `name`, `flag`, `meta`, `dim`) is a pair of SGR lists, `<role>Themed` and `<role>Mono`, a program may set. `Style` also paints any text: the sixteen colours (`red`, `brightBlack`, ...), their backgrounds (`bgRed`, `bgBrightRed`, ...), the attributes (`bold`, `faint`, `italic`, `underline`, `inverse`, `strikethrough`, which the failsafe keeps) and `sgr(text, codes)` for any parameter list, with the `SGR_` constants spelling the codes. `styleFor(fd, agent)` is the policy `nish --help` follows: plain unless the descriptor is a terminal, `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE`, `CLICOLOR` and `TERM=dumb` honoured, plain for an agent (`agentDriven`), forced colour always the theme's; it reads the environment and, for the terminal check, forks `/bin/sh` once, which runs `tput` by absolute path. `HelpMenu` and `Style` reach no capability. The compiler's own help is built with it through a relative import, so the module may use only what the last release compiles (`tests/link/std_cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli)) |
40
41
  | [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle and every mistake a panic at its call. `parse(argv, start)` walks the arguments once and answers a `ParseResult`: the reached command's id and path, each flag's value with its `source` (the command line, its default or unset), the positionals and what follows `--`, or the first error with a did-you-mean. `finish` prints help (laid out by `HelpMenu`), the version or the error and exits 0 or 2. `parse` reaches no capability (`tests/link/std_cli_args`, `examples/api-cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli-args)) |
package/std/net/fetch.ts CHANGED
@@ -492,6 +492,8 @@ export class FetchSyncClient {
492
492
  private rbuf: u8[]
493
493
  /** Where TLS application data is read before the parser takes it; empty until the first https connection. */
494
494
  private plain: u8[]
495
+ /** Where a redirect's body is read and thrown away; empty until the first redirect that has one. */
496
+ private sink: u8[]
495
497
  /** The fetch's end in monotonic nanoseconds; `HTTP_CLIENT_NEVER` for none. */
496
498
  private deadline: i64 = 0
497
499
  /** The last failure's `HTTP_E_*` code; `HTTP_E_NONE` after a fetch that answered. */
@@ -530,6 +532,7 @@ export class FetchSyncClient {
530
532
  this.ready = new Array<i32>(8)
531
533
  this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
532
534
  this.plain = []
535
+ this.sink = []
533
536
  const proxies: string[] = httpClientEnvProxies(options)
534
537
  this.httpProxy = proxies[0]
535
538
  this.httpsProxy = proxies[1]
@@ -1192,9 +1195,14 @@ export class FetchSyncClient {
1192
1195
  /**
1193
1196
  * Reads past a redirect's body so the connection can carry the next
1194
1197
  * request; a body too long to be worth reading, or any failure, closes it.
1198
+ * The sink is the client's, kept for the next hop: one built per call would
1199
+ * stay in the caller's memory for every redirect the fetch follows.
1195
1200
  */
1196
1201
  private drain(): void {
1197
- const sink: u8[] = new Array<u8>(HTTP_CLIENT_DRAIN_CHUNK)
1202
+ if (toI32(this.sink.length) === 0) {
1203
+ this.sink = new Array<u8>(HTTP_CLIENT_DRAIN_CHUNK)
1204
+ }
1205
+ const sink: u8[] = this.sink
1198
1206
  let left: i32 = HTTP_CLIENT_DRAIN_BYTES
1199
1207
  while (this.bodyOpen && left > 0) {
1200
1208
  const n: i32 = this.readBody(this.generation, sink, HTTP_CLIENT_ZERO, HTTP_CLIENT_DRAIN_CHUNK)
@@ -105,7 +105,15 @@ import {
105
105
  routerDecode,
106
106
  } from "nish/net/router"
107
107
  import { URL_DECODE_ALLOW_NUL, URL_DECODE_ERR_SPACE, URL_DECODE_FORM, percentDecode } from "nish/net/url"
108
- import { pollAdd, pollCreate, pollModify, pollRemove, pollWait } from "nish:net"
108
+ import {
109
+ NET_LISTEN_RING,
110
+ pollAdd,
111
+ pollCreate,
112
+ pollModify,
113
+ pollRemove,
114
+ pollWait,
115
+ tcpListenFlags,
116
+ } from "nish:net"
109
117
 
110
118
  /** An answer sent, or queued to be sent. */
111
119
  export const HANDLER_SENT: i32 = 0
@@ -142,7 +150,10 @@ const HANDLER_ONE_MIB: i32 = 1048576
142
150
  /** `tcpAccept`: none is waiting (EAGAIN), or the one that was left before it was taken (ECONNABORTED). */
143
151
  const HANDLER_ACCEPT_NONE: i32 = -11
144
152
  const HANDLER_ACCEPT_ABORTED: i32 = -103
145
- /** How long the listener rests after an accept fails for want of descriptors or memory: 100 ms. */
153
+ /**
154
+ * How long, at most, the listener rests after an accept fails for want of
155
+ * descriptors, ring slots or memory: 100 ms, or until a connection closes.
156
+ */
146
157
  const HANDLER_ACCEPT_REST: i64 = 100000000
147
158
  /** How often, at most, `wait` looks for a body past `bodyTimeout`: a second, in nanoseconds. */
148
159
  const HANDLER_BODY_SWEEP: i64 = 1000000000
@@ -160,8 +171,21 @@ const HANDLER_TOOK_THREE: i32 = 768
160
171
  export class HandlerLimits {
161
172
  /** The carrier's caps and timeouts; `http.maxBody` is the body cap, past which a request is answered 413. */
162
173
  http: Http1Config
163
- /** The most connections at once. */
174
+ /**
175
+ * The most connections at once. It is the handler's own cap, not
176
+ * `RLIMIT_NOFILE`: with `ring` set the connections live in io_uring slots
177
+ * and may outnumber the descriptor limit. Past it a connection is accepted
178
+ * and closed at once.
179
+ */
164
180
  slots: i32 = 256
181
+ /**
182
+ * Whether `listen` opens its listener with `NET_LISTEN_RING`, so each
183
+ * connection is accepted into an io_uring slot rather than a descriptor.
184
+ * Off by default. Where the kernel refuses rings, the listener serves
185
+ * descriptors and `netRingState` says why. A connection is then a slot
186
+ * handle, which `sendFd` and a C library through `nish:ffi` cannot take.
187
+ */
188
+ ring: boolean = false
165
189
  /**
166
190
  * Bytes in the JSON scratch buffer: the largest body `json` and `problem`
167
191
  * can write. A value past it makes `sendJson` answer 500. At least 256.
@@ -188,6 +212,19 @@ export class HandlerLimits {
188
212
  this.http = new Http1Config()
189
213
  this.http.maxBody = HANDLER_ONE_MIB
190
214
  }
215
+
216
+ /**
217
+ * Opens a TCP listener for an `HttpHandler` with these limits:
218
+ * `tcpListenFlags` with `flags`, plus `NET_LISTEN_RING` when `ring` is set.
219
+ * @param host the address to bind, such as "0.0.0.0"
220
+ * @param port the port to bind, or 0 for one the kernel picks
221
+ * @param backlog the kernel's queue of connections not yet accepted
222
+ * @param flags `tcpListenFlags`' other bits: 1 for `SO_REUSEPORT`, 2 for `TCP_NODELAY`
223
+ * @returns the listener, or a negative errno
224
+ */
225
+ listen(host: string, port: i32, backlog: i32, flags: i32): i32 {
226
+ return tcpListenFlags(host, port, backlog, this.ring ? flags | NET_LISTEN_RING : flags)
227
+ }
191
228
  }
192
229
 
193
230
  /**
@@ -523,9 +560,10 @@ export class HttpHandler {
523
560
  private problemType: u8[]
524
561
  private noFields: u8[][]
525
562
  /**
526
- * When an accept failed for want of a resource (EMFILE, ENFILE, ENOMEM):
527
- * the listener is out of the loop until then, which it would otherwise wake
528
- * every turn while its connection waits. 0 while it is in the loop.
563
+ * When an accept failed for want of a resource (EMFILE for descriptors,
564
+ * ENFILE for ring slots, ENOMEM): the listener is out of the loop until
565
+ * then, or until a connection closes (`forget`), which it would otherwise
566
+ * wake every turn while its connection waits. 0 while it is in the loop.
529
567
  */
530
568
  private acceptRestUntil: i64 = 0
531
569
  /** `bodyTimeout` in nanoseconds. */
@@ -559,7 +597,9 @@ export class HttpHandler {
559
597
  * A handler over `listener`, a listening socket the program made
560
598
  * (`tcpListen`, or `tcpListenFlags` with SO_REUSEPORT for a worker of
561
599
  * `nish/net/prefork`), routing through `router`, whose routes are added
562
- * before the first `wait`.
600
+ * before the first `wait`. `limits.ring` acts only through the listener:
601
+ * open it with `limits.listen`, since a listener from `tcpListen` stays on
602
+ * descriptors whatever `ring` says.
563
603
  * @param limits the caps and timeouts. `slots`, `jsonBytes`, `maxEvents`
564
604
  * and `bodyTimeout` are read once here, so changing them later has no
565
605
  * effect; `http` is kept by the carrier, which reads its timeouts and
@@ -652,10 +692,7 @@ export class HttpHandler {
652
692
  this.watchedFired[id] = false
653
693
  }
654
694
  if (this.acceptRestUntil > 0 && monotonicNanos() >= this.acceptRestUntil) {
655
- this.acceptRestUntil = 0
656
- if (!this.draining) {
657
- pollAdd(this.loop, this.listener, H1_WANT_READ, HANDLER_LISTENER)
658
- }
695
+ this.endAcceptRest()
659
696
  }
660
697
  let timeout: i32 = timeoutMs
661
698
  if (this.acceptRestUntil > 0 && !this.draining) {
@@ -759,8 +796,9 @@ export class HttpHandler {
759
796
  slot = this.server.accept()
760
797
  }
761
798
  if (slot !== HANDLER_ACCEPT_NONE) {
762
- // Out of descriptors or memory: the connection stays in the backlog
763
- // and the listener stays readable, so rest it rather than spin.
799
+ // Out of descriptors (-24), ring slots (-23) or memory: the connection
800
+ // stays in the backlog and the listener stays readable, so rest it
801
+ // rather than spin, until a close frees one or the rest ends.
764
802
  pollRemove(this.loop, this.listener)
765
803
  this.acceptRestUntil = monotonicNanos() + HANDLER_ACCEPT_REST
766
804
  }
@@ -1088,8 +1126,22 @@ export class HttpHandler {
1088
1126
  this.forget(slot)
1089
1127
  }
1090
1128
 
1091
- /** The bookkeeping of a slot the carrier has closed. */
1129
+ /** Ends the listener's rest: it is back in the loop unless the handler is draining. */
1130
+ private endAcceptRest(): void {
1131
+ this.acceptRestUntil = 0
1132
+ if (!this.draining) {
1133
+ pollAdd(this.loop, this.listener, H1_WANT_READ, HANDLER_LISTENER)
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * The bookkeeping of a slot the carrier has closed. Its descriptor or ring
1139
+ * slot is free again, so a listener resting for want of one comes back.
1140
+ */
1092
1141
  private forget(slot: i32): void {
1142
+ if (this.acceptRestUntil > 0 && !this.draining) {
1143
+ this.endAcceptRest()
1144
+ }
1093
1145
  this.open[slot] = false
1094
1146
  this.slotGen[slot] = this.slotGen[slot] + 1
1095
1147
  const at: i32 = this.current[slot]
@@ -1191,6 +1243,18 @@ export class HttpHandler {
1191
1243
  return this.server.busy()
1192
1244
  }
1193
1245
 
1246
+ /**
1247
+ * Whether the listener is resting: an accept failed for want of a resource
1248
+ * (EMFILE for descriptors, ENFILE for ring slots, ENOMEM), so the handler
1249
+ * takes no connection until one closes or the 100 ms rest ends. During
1250
+ * `drain()` a close does not end the rest, so it stays true until the
1251
+ * 100 ms pass.
1252
+ * @returns true while the listener is out of the loop for such a rest
1253
+ */
1254
+ resting(): boolean {
1255
+ return this.acceptRestUntil > 0
1256
+ }
1257
+
1194
1258
  // ---- Responses ------------------------------------------------------------------
1195
1259
 
1196
1260
  /**
@@ -1230,6 +1230,19 @@ export class Http1Connection {
1230
1230
  )
1231
1231
  }
1232
1232
 
1233
+ /**
1234
+ * Whether the connection is between requests, so that a server draining
1235
+ * gracefully may close it without cutting a request short: it speaks HTTP,
1236
+ * not upgraded or closing, no request is open, no next head has begun to
1237
+ * arrive (its `headTimeout` clock has not started), and every byte of the
1238
+ * last response is sent.
1239
+ *
1240
+ * @returns true while closing the connection loses nothing its client sent or is owed
1241
+ */
1242
+ betweenRequests(): boolean {
1243
+ return this.state === H1_S_HTTP && !this.requestOpen && !this.headTimed && !this.wantsWrite()
1244
+ }
1245
+
1233
1246
  /** The room at the end of the output, once what was sent is moved out of the way. */
1234
1247
  private room(): i32 {
1235
1248
  // Tested here, so that the usual case, an output already held, is no call.