nish 0.41.0 → 0.44.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.
Files changed (47) hide show
  1. package/README.md +16 -4
  2. package/bin/nish-skills.js +233 -0
  3. package/docs/AI.md +282 -126
  4. package/llms.txt +4 -0
  5. package/package.json +14 -11
  6. package/runtime/core.d.ts +16 -0
  7. package/runtime/core.mjs +5 -0
  8. package/runtime/nish.d.ts +204 -33
  9. package/runtime/nish.h +19 -3
  10. package/runtime/nish.mjs +5 -1
  11. package/runtime/runtime-cross.c +15 -0
  12. package/runtime/runtime-net.c +876 -10
  13. package/runtime/runtime-region.c +21 -0
  14. package/runtime/runtime-sandbox.c +112 -15
  15. package/runtime/runtime-text.c +11 -0
  16. package/runtime/runtime-uring.c +533 -77
  17. package/runtime/runtime-wasm.c +3 -0
  18. package/runtime/runtime.c +474 -5
  19. package/runtime/sqlite/README.md +16 -3
  20. package/runtime/sqlite/nish-sqlite.c +940 -29
  21. package/scripts/build.sh +125 -29
  22. package/scripts/link-skills.mjs +1039 -0
  23. package/scripts/postinstall.mjs +43 -0
  24. package/skills/writing-nish/SKILL.md +144 -0
  25. package/std/README.md +3 -3
  26. package/std/crypto/base64url.ts +102 -1
  27. package/std/crypto/scram.ts +142 -0
  28. package/std/crypto/sha1.ts +99 -41
  29. package/std/host/ring.ts +1 -1
  30. package/std/host/text.ts +1 -1
  31. package/std/net/fetch.ts +9 -1
  32. package/std/net/handler.ts +79 -15
  33. package/std/net/http-server.ts +2 -3
  34. package/std/net/http1-server.ts +294 -51
  35. package/std/net/http3-server.ts +26 -15
  36. package/std/net/http3.ts +2 -2
  37. package/std/net/oidc.ts +1107 -0
  38. package/std/net/postgres-async.ts +64 -33
  39. package/std/net/postgres.ts +65 -76
  40. package/std/net/quic-conn-ack.ts +57 -7
  41. package/std/net/quic-frame.ts +104 -2
  42. package/std/net/quic-listener.ts +9 -2
  43. package/std/net/quic.ts +16 -1
  44. package/std/net/serve.ts +10 -8
  45. package/std/net/websocket.ts +188 -49
  46. package/std/sqlite.ts +325 -0
  47. package/std/text.ts +80 -11
@@ -78,6 +78,9 @@ extern unsigned char __heap_base;
78
78
  * past 2^32 truncated to the `uintptr_t` `memory.grow` takes: a request of
79
79
  * 2^48 bytes grew nothing, claimed 2^48 bytes of capacity, and the next block
80
80
  * landed at `buf + off` reduced mod 2^32, on top of live data. */
81
+ /* No compact-class range here (`NISH_ARENA_RANGE`, runtime.c): a wasm
82
+ module's memory is one 32-bit space already, so this allocator and its
83
+ bump are unchanged and build.sh never passes the define to this file. */
81
84
  void *nish_arena_grow(uint64_t size) {
82
85
  if (!nish_arena.buf) {
83
86
  uintptr_t base = ((uintptr_t)&__heap_base + 7) & ~(uintptr_t)7;
package/runtime/runtime.c CHANGED
@@ -21,6 +21,13 @@
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
+ #if defined NISH_ARENA_DEBUG || defined NISH_ARENA_RANGE
25
+ /* The debug arena's `madvise`, which POSIX leaves out (its `posix_madvise`
26
+ gives nothing back on glibc), and the compact-class range's `MAP_ANONYMOUS`,
27
+ `MAP_NORESERVE` and `MAP_FIXED_NOREPLACE`. */
28
+ #define _DEFAULT_SOURCE
29
+ #define _DARWIN_C_SOURCE
30
+ #endif
24
31
  #include <errno.h>
25
32
  #include <inttypes.h>
26
33
  #include <math.h>
@@ -197,11 +204,321 @@ NISH_TLS uint64_t nish_region_chunk;
197
204
  single allocation larger than this still gets a chunk of its own size. */
198
205
  #define NISH_REGION_CHUNK_MAX ((uint64_t)1 << 20)
199
206
 
207
+ #ifdef NISH_ARENA_RANGE
208
+ /* A module compiled for this variant references it, so linking one against
209
+ the default runtime fails at the link rather than at the first reference.
210
+ The ASan build defines it too, so the same module links there. */
211
+ const int nish_arena_range_abi = 1;
212
+ /* The range's first byte: what a 32-bit reference counts from. Null under
213
+ NISH_ASAN, which reserves nothing. */
214
+ char *nish_ref_base;
215
+ #endif
216
+
217
+ /* NISH_ASAN wins over NISH_ARENA_RANGE: an instrumented build reserves
218
+ nothing and every block stays a malloc of its own, as without the range.
219
+ ASan's shadow memory on x86-64 lies across [1 GiB, 16 GiB), where the
220
+ range would go, and a block carved from a range has no redzone. */
221
+ #if defined NISH_ARENA_RANGE && !defined NISH_ASAN
222
+ /* ---- The compact-class range (`-DNISH_ARENA_RANGE`; docs/wp48-ref32-classes.md
223
+ §3.3, docs/security/runtime.md, "The compact-class range")
224
+ A program with a compact class links this variant, which build.sh selects
225
+ when the compiler asks for it; nothing selects it by hand. Every arena chunk
226
+ of 2 MiB or less is cut from one 15 GiB range, so a reference into one fits
227
+ 32 bits once it is counted in 4-byte units from the range's base. On Linux
228
+ the range sits at the fixed address [1 GiB, 16 GiB) and the base is a
229
+ constant; elsewhere (macOS) the system places it and the base is
230
+ `nish_ref_base`. It is reserved once, before main, read-write and without
231
+ committing its pages; an address something else already holds is a panic
232
+ that names it and the limit, never a fallback to another address, because
233
+ compiled code may already treat the base as a constant.
234
+ A chunk's `cap` is a power of two from 4 KiB to 2 MiB, its class, with its
235
+ 16-byte header in front; a chunk a release frees goes on its class's free
236
+ list instead of back to malloc, and the next request of that class takes
237
+ it before the range's high-water mark moves. One lock covers both, for
238
+ every thread. A chunk is told from a malloc'd one by its address. The
239
+ first 64 bytes of the range are never handed out, so offset 0 is never a
240
+ block. A request past 2 MiB keeps an exact malloc'd chunk, as today. The
241
+ range never shrinks: a chunk on a free list keeps its pages. */
242
+ #include <sys/mman.h>
243
+ #ifdef NISH_RANGE_TEST_SIZE
244
+ #define NISH_RANGE_SIZE ((uint64_t)(NISH_RANGE_TEST_SIZE))
245
+ #else
246
+ #define NISH_RANGE_SIZE ((uint64_t)15 << 30)
247
+ #endif
248
+ /* The fixed shape is Linux's. tests/runtime/range-test.c's sanitizer builds
249
+ take the based one (`NISH_RANGE_TEST_BASED`): their shadow is where the
250
+ fixed range would be. */
251
+ #if defined __linux__ && !defined NISH_RANGE_TEST_BASED
252
+ #define NISH_RANGE_FIXED ((uintptr_t)1 << 30)
253
+ #ifndef MAP_FIXED_NOREPLACE
254
+ #define MAP_FIXED_NOREPLACE 0x100000
255
+ #endif
256
+ #endif
257
+ #define NISH_RANGE_HOLE 64
258
+ #define NISH_RANGE_CLASS_MIN ((uint64_t)1 << 12)
259
+ #define NISH_RANGE_CLASS_MAX ((uint64_t)1 << 21)
260
+ #define NISH_RANGE_CLASSES 10
261
+ /* The range's mapping, `prot` its protection (the debug arena's is
262
+ PROT_NONE): the fixed address or none, with a panic on anything else. */
263
+ static char *nish_range_map(int prot) {
264
+ #ifdef NISH_RANGE_FIXED
265
+ void *p = mmap((void *)NISH_RANGE_FIXED, (size_t)NISH_RANGE_SIZE, prot,
266
+ MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE | MAP_FIXED_NOREPLACE, -1, 0);
267
+ /* A kernel older than MAP_FIXED_NOREPLACE takes the address as a hint and
268
+ maps elsewhere when it is busy: that is busy too. */
269
+ if (p != MAP_FAILED && p != (void *)NISH_RANGE_FIXED) munmap(p, (size_t)NISH_RANGE_SIZE);
270
+ /* EEXIST is the address taken; anything else (ENOMEM: a limit on address
271
+ space or mappings) is the system refusing the size. */
272
+ if (p == MAP_FAILED && errno != EEXIST)
273
+ nish_die("nish: the compact-class arena cannot reserve its 15 GiB range at 0x40000000 "
274
+ "(1 GiB to 16 GiB): the system refused the mapping (an address-space or mapping limit)\n");
275
+ if (p != (void *)NISH_RANGE_FIXED)
276
+ nish_die("nish: the compact-class arena cannot reserve its 15 GiB range at 0x40000000 "
277
+ "(1 GiB to 16 GiB): the address is in use\n");
278
+ return p;
279
+ #else
280
+ void *p = mmap(0, (size_t)NISH_RANGE_SIZE, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
281
+ if (p == MAP_FAILED) nish_die("nish: the compact-class arena cannot reserve its 15 GiB range\n");
282
+ return p;
283
+ #endif
284
+ }
285
+ #endif
286
+
287
+ #if defined NISH_ARENA_RANGE && !defined NISH_ASAN && !defined NISH_ARENA_DEBUG
288
+ static int nish_range_state; /* 0 none, 1 reserving, 2 reserved */
289
+ static int nish_range_lock;
290
+ static uint64_t nish_range_top = NISH_RANGE_HOLE; /* the high-water mark, under the lock */
291
+ static nish_chunk *nish_range_free[NISH_RANGE_CLASSES];
292
+
293
+ static void nish_range_reserve(void) {
294
+ int want = 0;
295
+ if (!__atomic_compare_exchange_n(&nish_range_state, &want, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
296
+ while (__atomic_load_n(&nish_range_state, __ATOMIC_ACQUIRE) != 2) {}
297
+ return;
298
+ }
299
+ nish_ref_base = nish_range_map(PROT_READ | PROT_WRITE);
300
+ __atomic_store_n(&nish_range_state, 2, __ATOMIC_RELEASE);
301
+ }
302
+ /* Before main, so a busy address is a panic before the program runs. */
303
+ __attribute__((constructor)) static void nish_range_init(void) { nish_range_reserve(); }
304
+
305
+ static int nish_range_owns(const void *c) {
306
+ uintptr_t a = (uintptr_t)c, base = (uintptr_t)nish_ref_base;
307
+ return nish_ref_base && a >= base && a - base < NISH_RANGE_SIZE;
308
+ }
309
+
310
+ /* A class's index: `cap` is a power of two in [4 KiB, 2 MiB]. */
311
+ static unsigned nish_range_class(uint64_t cap) { return (unsigned)__builtin_ctzll(cap) - 12; }
312
+
313
+ static void nish_range_enter(void) {
314
+ while (__atomic_exchange_n(&nish_range_lock, 1, __ATOMIC_ACQUIRE)) {}
315
+ }
316
+ static void nish_range_leave(void) { __atomic_store_n(&nish_range_lock, 0, __ATOMIC_RELEASE); }
317
+
318
+ /* A chunk of class `cap`: its free list's newest, or the next unused bytes. */
319
+ static nish_chunk *nish_range_take(uint64_t cap) {
320
+ if (__atomic_load_n(&nish_range_state, __ATOMIC_ACQUIRE) != 2) nish_range_reserve();
321
+ unsigned k = nish_range_class(cap);
322
+ nish_range_enter();
323
+ nish_chunk *c = nish_range_free[k];
324
+ if (c) {
325
+ nish_range_free[k] = c->next;
326
+ } else {
327
+ uint64_t span = sizeof(nish_chunk) + cap;
328
+ /* `span > NISH_RANGE_SIZE` folds to false at 15 GiB; it keeps a smaller
329
+ test size (NISH_RANGE_TEST_SIZE) from wrapping the subtraction. */
330
+ if (span > NISH_RANGE_SIZE || nish_range_top > NISH_RANGE_SIZE - span) {
331
+ nish_range_leave();
332
+ nish_die("nish: the compact-class arena's 15 GiB range is used up\n");
333
+ }
334
+ c = (nish_chunk *)(nish_ref_base + nish_range_top);
335
+ nish_range_top += span;
336
+ }
337
+ nish_range_leave();
338
+ return c;
339
+ }
340
+
341
+ /* A chunk a release gives back: onto its class's list if the range holds it,
342
+ to free() if malloc made it. runtime-region.c's adopt drops through this. */
343
+ void nish_range_drop(void *p) {
344
+ nish_chunk *c = p;
345
+ if (!nish_range_owns(c)) {
346
+ free(c);
347
+ return;
348
+ }
349
+ unsigned k = nish_range_class(NISH_CHUNK_CAP(c));
350
+ nish_range_enter();
351
+ c->next = nish_range_free[k];
352
+ nish_range_free[k] = c;
353
+ nish_range_leave();
354
+ }
355
+ #endif
356
+
357
+ #ifdef NISH_ARENA_DEBUG
358
+ /* ---- The debug arena (`--debug-arena`, `-DNISH_ARENA_DEBUG`;
359
+ docs/security/runtime.md, "The debug arena")
360
+ Every arena block is a chunk of its own, as under ASan: its pages are cut
361
+ from one address range reserved at the first allocation and never handed
362
+ out twice, with the header at the start of its first page and `cap` exact,
363
+ so the inline bump never fits again and every block, and every release,
364
+ comes through this file. A release or reset that frees a chunk retires it
365
+ instead: its pages go `PROT_NONE` and back to the system, but stay
366
+ reserved, so a stale reference faults at the read rather than reading what
367
+ the next allocation wrote there. The handler below names that fault before
368
+ the program dies of it. The bytes past the mark in the mark's own chunk
369
+ are not retired; with exact chunks there are none, as every mark but a
370
+ region's 0 sits at a chunk's end. A chunk C code malloc'd and linked in
371
+ (runtime-cross.c's) lies outside the range and is freed as always.
372
+ Memory only grows, since no address is reused: this is for tests and
373
+ fuzzing, never a release build. */
374
+ #include <signal.h>
375
+ #include <sys/mman.h>
376
+ static char *nish_debug_base; /* the reservation, PROT_NONE until a block is cut from it */
377
+ static uint64_t nish_debug_size;
378
+ static uint64_t nish_debug_next; /* the next unused byte's offset, taken atomically */
379
+ static uint64_t nish_debug_page;
380
+ static int nish_debug_state; /* 0 none, 1 reserving, 2 reserved */
381
+ static struct sigaction nish_debug_old_segv, nish_debug_old_bus;
382
+
383
+ /* A fault in the part of the reservation handed out so far is a stale arena
384
+ reference: say so, then put the default back and return, so the access
385
+ faults once more and the program dies of the signal, as its parent expects.
386
+ Any other fault, pages never handed out included, goes to the handler that
387
+ was there before. It runs on an alternate stack when the thread has one
388
+ (runtime-term.c's), so a stack overflow still reaches that handler. */
389
+ static void nish_debug_on_fault(int sig, siginfo_t *info, void *ctx) {
390
+ (void)ctx;
391
+ uintptr_t a = (uintptr_t)info->si_addr, base = (uintptr_t)nish_debug_base;
392
+ struct sigaction *old = sig == SIGSEGV ? &nish_debug_old_segv : &nish_debug_old_bus;
393
+ #if defined NISH_ARENA_RANGE && !defined NISH_ASAN
394
+ /* The range's first page is never handed out: a fault there (a reference
395
+ of 0, counted from the base) is not a stale block. */
396
+ uint64_t lo = nish_debug_page;
397
+ #else
398
+ uint64_t lo = 0;
399
+ #endif
400
+ if (a >= base + lo && a - base < __atomic_load_n(&nish_debug_next, __ATOMIC_RELAXED)) {
401
+ char msg[] = "nish: --debug-arena: stale arena reference at 0x0000000000000000: "
402
+ "the memory was released by the scope that allocated it\n";
403
+ char *hex = msg + sizeof "nish: --debug-arena: stale arena reference at 0x" - 1;
404
+ for (int i = 15; i >= 0; i--, a >>= 4) hex[i] = "0123456789abcdef"[a & 15];
405
+ nish_write_all(2, msg, sizeof msg - 1);
406
+ void (*hook)(void) = __atomic_load_n(&nish_fatal_hook, __ATOMIC_ACQUIRE);
407
+ if (hook) hook();
408
+ signal(sig, SIG_DFL);
409
+ return;
410
+ }
411
+ sigaction(sig, old, 0);
412
+ }
413
+
414
+ /* Reserve the range, once for every thread: as much address space as the
415
+ system lets a process have without committing it, from 1 TiB down to 1 GiB. */
416
+ static void nish_debug_reserve(void) {
417
+ int want = 0;
418
+ if (!__atomic_compare_exchange_n(&nish_debug_state, &want, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) {
419
+ while (__atomic_load_n(&nish_debug_state, __ATOMIC_ACQUIRE) != 2) {}
420
+ return;
421
+ }
422
+ long page = sysconf(_SC_PAGESIZE);
423
+ nish_debug_page = page > 0 ? (uint64_t)page : 4096;
424
+ #if defined NISH_ARENA_RANGE && !defined NISH_ASAN
425
+ /* With a compact class the reservation is the compact range itself, fixed
426
+ or based as without the debug arena, so a 32-bit reference still reaches
427
+ every block. No address is reused there either; its first page, which
428
+ holds the 64 bytes no block may have, is never handed out. */
429
+ nish_debug_base = nish_range_map(PROT_NONE);
430
+ nish_debug_size = NISH_RANGE_SIZE;
431
+ nish_debug_next = nish_debug_page;
432
+ nish_ref_base = nish_debug_base;
433
+ #else
434
+ for (uint64_t size = (uint64_t)1 << 40; size >= (uint64_t)1 << 30; size >>= 1) {
435
+ void *p = mmap(0, (size_t)size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
436
+ if (p != MAP_FAILED) {
437
+ nish_debug_base = p;
438
+ nish_debug_size = size;
439
+ break;
440
+ }
441
+ }
442
+ if (!nish_debug_base) nish_die("nish: --debug-arena: cannot reserve address space for the arena\n");
443
+ #endif
444
+ struct sigaction sa;
445
+ memset(&sa, 0, sizeof sa);
446
+ sa.sa_sigaction = nish_debug_on_fault;
447
+ sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK;
448
+ sigemptyset(&sa.sa_mask);
449
+ sigaction(SIGSEGV, &sa, &nish_debug_old_segv);
450
+ sigaction(SIGBUS, &sa, &nish_debug_old_bus);
451
+ __atomic_store_n(&nish_debug_state, 2, __ATOMIC_RELEASE);
452
+ }
453
+
454
+ static uint64_t nish_debug_span(uint64_t cap) {
455
+ return (sizeof(nish_chunk) + cap + nish_debug_page - 1) & ~(nish_debug_page - 1);
456
+ }
457
+
458
+ /* A chunk of `cap` bytes, header included, on pages no block had before. */
459
+ static nish_chunk *nish_debug_chunk(uint64_t cap) {
460
+ if (__atomic_load_n(&nish_debug_state, __ATOMIC_ACQUIRE) != 2) nish_debug_reserve();
461
+ if (cap > nish_debug_size - sizeof(nish_chunk) - nish_debug_page) nish_oom();
462
+ uint64_t span = nish_debug_span(cap);
463
+ uint64_t at = __atomic_fetch_add(&nish_debug_next, span, __ATOMIC_RELAXED);
464
+ #if defined NISH_ARENA_RANGE && !defined NISH_ASAN
465
+ if (at > nish_debug_size - span)
466
+ nish_die("nish: --debug-arena: the compact-class arena's 15 GiB range is used up (no address is reused)\n");
467
+ #else
468
+ if (at > nish_debug_size - span)
469
+ nish_die("nish: --debug-arena: the arena's address space is used up (no address is reused)\n");
470
+ #endif
471
+ char *p = nish_debug_base + at;
472
+ if (mprotect(p, (size_t)span, PROT_READ | PROT_WRITE) != 0) nish_oom();
473
+ return (nish_chunk *)p;
474
+ }
475
+
476
+ /* Whether `c` is one of the debug arena's chunks, not one C code malloc'd. */
477
+ static int nish_debug_owns(const void *c) {
478
+ uintptr_t a = (uintptr_t)c, base = (uintptr_t)nish_debug_base;
479
+ return nish_debug_base && a >= base && a - base < nish_debug_size;
480
+ }
481
+
482
+ /* Retire a chunk: every page of it unreadable and given back, its addresses
483
+ kept. A process at its limit of mappings (each retired run splits one) is
484
+ refused the `mprotect`; the chunk is then filled with 0xDB instead, which
485
+ reads as a pointer no system maps and a length no bounds check passes. */
486
+ static void nish_debug_retire(nish_chunk *c) {
487
+ uint64_t span = nish_debug_span(NISH_CHUNK_CAP(c));
488
+ if (mprotect(c, (size_t)span, PROT_NONE) == 0) madvise(c, (size_t)span, MADV_DONTNEED);
489
+ else memset(c, 0xDB, (size_t)span);
490
+ }
491
+
492
+ /* runtime-region.c's adopt drops an empty chunk through this. */
493
+ void nish_debug_drop(void *c) {
494
+ if (nish_debug_owns(c)) nish_debug_retire(c);
495
+ else free(c);
496
+ }
497
+ #endif
498
+
499
+ #if defined NISH_ARENA_DEBUG && defined NISH_ARENA_RANGE && !defined NISH_ASAN
500
+ /* Before main, as without the debug arena: a busy address is a panic before
501
+ the program runs. */
502
+ __attribute__((constructor)) static void nish_debug_range_init(void) {
503
+ if (__atomic_load_n(&nish_debug_state, __ATOMIC_ACQUIRE) != 2) nish_debug_reserve();
504
+ }
505
+ #endif
506
+
200
507
  /* Slow path (size 8-byte rounded): push a chunk (>= 64 KB, or a region's
201
508
  next size), bump from it. A region's chunks double from its first, up to
202
509
  NISH_REGION_CHUNK_MAX. */
203
510
  void *nish_arena_grow(uint64_t size) {
204
- #ifdef NISH_ASAN
511
+ #if defined NISH_ARENA_DEBUG
512
+ /* An exact chunk, as under ASan, of pages no block had before. `off` is the
513
+ whole chunk, so even a block the rounding left room after is alone in it. */
514
+ uint64_t cap = (size + 7) & ~(uint64_t)7;
515
+ if (cap < size) nish_oom();
516
+ nish_chunk *d = nish_debug_chunk(cap);
517
+ d->next = nish_arena.chunks;
518
+ d->cap = cap;
519
+ nish_arena = (struct nish_arena){ (char *)(d + 1), cap, cap, d };
520
+ return nish_arena.buf;
521
+ #elif defined NISH_ASAN
205
522
  /* An exact chunk leaves off == cap, so the inline bump never fits again and
206
523
  every block comes through here: one malloc, one redzone, per block. */
207
524
  uint64_t cap = size;
@@ -210,6 +527,17 @@ void *nish_arena_grow(uint64_t size) {
210
527
  uint64_t floor = next ? next : 65536;
211
528
  uint64_t cap = size > floor ? size : floor;
212
529
  if (next) nish_region_chunk = cap < NISH_REGION_CHUNK_MAX / 2 ? cap * 2 : NISH_REGION_CHUNK_MAX;
530
+ #endif
531
+ #if defined NISH_ARENA_RANGE && !defined NISH_ASAN && !defined NISH_ARENA_DEBUG
532
+ /* Up to 2 MiB, a chunk of the range: `cap` rounded up to its class. */
533
+ if (cap <= NISH_RANGE_CLASS_MAX) {
534
+ uint64_t k = cap < NISH_RANGE_CLASS_MIN ? NISH_RANGE_CLASS_MIN : (uint64_t)1 << (64 - __builtin_clzll(cap - 1));
535
+ nish_chunk *r = nish_range_take(k);
536
+ r->next = nish_arena.chunks;
537
+ r->cap = k;
538
+ nish_arena = (struct nish_arena){ (char *)(r + 1), size, k, r };
539
+ return nish_arena.buf;
540
+ }
213
541
  #endif
214
542
  /* A 64-bit request cannot always be asked for: wasm32's `size_t` is 32 bits,
215
543
  and malloc would silently take the low half of a chunk nobody can address. */
@@ -242,11 +570,22 @@ void *nish_alloc_struct(uint64_t size) {
242
570
  return nish_asan_alloc(size);
243
571
  #endif
244
572
  size = (size + 7) & ~(uint64_t)7;
573
+ #ifdef NISH_ARENA_RANGE
574
+ /* Compiled code bumps a compact class's 4-byte multiple, so `off` may sit
575
+ 4 bytes past an 8-byte boundary: a block from here starts at the next. */
576
+ uint64_t at = (nish_arena.off + 7) & ~(uint64_t)7;
577
+ if (at + size <= nish_arena.cap) {
578
+ void *p = nish_arena.buf + at;
579
+ nish_arena.off = at + size;
580
+ return p;
581
+ }
582
+ #else
245
583
  if (nish_arena.off + size <= nish_arena.cap) {
246
584
  void *p = nish_arena.buf + nish_arena.off;
247
585
  nish_arena.off += size;
248
586
  return p;
249
587
  }
588
+ #endif
250
589
  return nish_arena_grow(size);
251
590
  }
252
591
 
@@ -314,6 +653,18 @@ static void nish_grown_put(char *data, const void *owner, uint64_t native) {
314
653
  }
315
654
  #endif
316
655
  void nish_free_arena(void);
656
+ /* The bytes of a chunk the arena reuses from its start, after a reset or a
657
+ release to a mark there. A scope may have marked that start, and a block
658
+ that began there and filled the chunk exactly would be one
659
+ `nish_array_grow_here` reallocates -- which would either keep the grown
660
+ chunk for good (the release keeps the chunk its mark is in) or move it from
661
+ under the mark, which then names no chunk and frees nothing. So a chunk
662
+ that growth could reallocate, one past 64 KB, is reused a word short, and no
663
+ block from its start fills it. A chunk of 64 KB or less is never
664
+ reallocated and keeps all of it: a recycled task region
665
+ (runtime-async.c) or a loop's reset chunk that a word short no longer fits
666
+ the same allocation again would take a fresh chunk every time. */
667
+ #define NISH_REUSE_CAP(cap) ((cap) > 65536 ? (cap) - 8 : (cap))
317
668
  static void nish_free_until(nish_chunk *c, const nish_chunk *end) {
318
669
  #ifdef NISH_ASAN
319
670
  /* A freed block's address comes back from malloc: forget the grown ones. */
@@ -327,13 +678,19 @@ static void nish_free_until(nish_chunk *c, const nish_chunk *end) {
327
678
  between: what frees the older chunk frees the memory under it. */
328
679
  while (c != end) {
329
680
  nish_chunk *n = c->next;
681
+ #ifdef NISH_ARENA_DEBUG
682
+ if (!(c->cap & NISH_CHUNK_CARVED)) nish_debug_drop(c);
683
+ #elif defined NISH_ARENA_RANGE && !defined NISH_ASAN
684
+ if (!(c->cap & NISH_CHUNK_CARVED)) nish_range_drop(c);
685
+ #else
330
686
  if (!(c->cap & NISH_CHUNK_CARVED)) free(c);
687
+ #endif
331
688
  c = n;
332
689
  }
333
690
  }
334
691
 
335
692
  void nish_reset_arena(void) {
336
- #ifdef NISH_ASAN
693
+ #if defined NISH_ASAN || defined NISH_ARENA_DEBUG
337
694
  /* Free everything, so a value read after the reset is a use after free. */
338
695
  nish_free_arena();
339
696
  return;
@@ -354,7 +711,7 @@ void nish_reset_arena(void) {
354
711
  }
355
712
  nish_free_until(keep->next, 0);
356
713
  keep->next = 0;
357
- nish_arena = (struct nish_arena){ (char *)(keep + 1), 0, keep->cap, keep };
714
+ nish_arena = (struct nish_arena){ (char *)(keep + 1), 0, NISH_REUSE_CAP(keep->cap), keep };
358
715
  }
359
716
 
360
717
  void nish_free_arena(void) {
@@ -382,7 +739,12 @@ void nish_arena_release(uint64_t mark) {
382
739
  }
383
740
  if (!c) return;
384
741
  nish_free_until(nish_arena.chunks, c);
385
- nish_arena = (struct nish_arena){ (char *)(c + 1), mark - (uintptr_t)(c + 1), NISH_CHUNK_CAP(c), c };
742
+ uint64_t off = mark - (uintptr_t)(c + 1), cap = NISH_CHUNK_CAP(c);
743
+ nish_arena = (struct nish_arena){ (char *)(c + 1), off, off ? cap : NISH_REUSE_CAP(cap), c };
744
+ #ifdef NISH_ARENA_DEBUG
745
+ /* Never bump into what the mark gave back: the next block gets a chunk. */
746
+ nish_arena.cap = nish_arena.off;
747
+ #endif
386
748
  }
387
749
 
388
750
  /* Release back to `mark` while keeping the newest allocation; returns where it
@@ -408,12 +770,21 @@ void *nish_arena_keep(uint64_t mark, void *p) {
408
770
  if (mark >= cb && mark <= cb + NISH_CHUNK_CAP(c)) break;
409
771
  }
410
772
  if (!c || (c == pc && mark > q)) return p;
773
+ #ifdef NISH_ARENA_RANGE
774
+ /* A compact class's 4-byte bump may have left the mark 4 past an 8-byte
775
+ boundary (`nish_alloc_struct`): the kept block moves to the next one.
776
+ `q` is 8-aligned, so a mark at or below it rounds to at most `q`. */
777
+ mark = (mark + 7) & ~(uint64_t)7;
778
+ #endif
411
779
  /* mark <= q inside one chunk implies mark + size <= q + size <= its end, so
412
780
  the second arm is only ever reached with `c` older than `pc`. */
413
781
  if (mark + size <= (uintptr_t)(c + 1) + NISH_CHUNK_CAP(c)) {
414
782
  memmove((void *)mark, p, size);
415
783
  nish_free_until(pc, c);
416
784
  nish_arena = (struct nish_arena){ (char *)(c + 1), mark + size - (uintptr_t)(c + 1), NISH_CHUNK_CAP(c), c };
785
+ #ifdef NISH_ARENA_DEBUG
786
+ nish_arena.cap = nish_arena.off;
787
+ #endif
417
788
  return (void *)mark;
418
789
  }
419
790
  /* Keeping a carved `pc` while the chunks under it go could free the one it
@@ -569,7 +940,101 @@ double nish_parse_number(const nish_str *s, int32_t mode) {
569
940
  * the extra compare moved register allocation in the hot loops around them
570
941
  * (+0.2% to +2% instructions over bench/instructions.json's map rows). Out of
571
942
  * line, every one of those rows runs fewer instructions than it did before, and
572
- * the call costs nothing on a path that runs once per doubling. */
943
+ * the call costs nothing on a path that runs once per doubling.
944
+ *
945
+ * A normal build first tries to grow the block where it is
946
+ * (`nish_array_grow_here`), so that an array built by `push` costs its final
947
+ * size rather than the sum of every size it passed through. */
948
+ #ifndef NISH_ASAN
949
+ /* How many chunks `nish_array_grow_here` looks through for the one an array
950
+ fills: a program building a few large columns at once keeps each in a chunk
951
+ of its own near the head of the list, and a longer walk would cost more than
952
+ the copy it might save on a small array. */
953
+ #define NISH_GROW_WALK 16
954
+
955
+ /* Grow `a`'s block from `old` to `want` bytes (both 8-rounded) without moving
956
+ * its elements to a fresh block, or answer 0 to have the caller copy them. Two
957
+ * cases are cheap and safe:
958
+ *
959
+ * - The block is the last one bumped from the current chunk, with room
960
+ * behind it: bump `off` past the new bytes. Nothing lies after the block,
961
+ * so nothing is overwritten.
962
+ * - The block is the whole of a malloc'd chunk, as every block over 64 KB is
963
+ * (`nish_arena_grow` gives it an exact chunk): `realloc` the chunk, which
964
+ * for a large block remaps its pages rather than copying them and returns
965
+ * the old block's memory, and relink it where it was in the list. The order
966
+ * of the list is what `nish_arena_release` and runtime-cross.c's
967
+ * `nish_since` read, and it is unchanged.
968
+ *
969
+ * Both are sound because no pointer into `data` is held across a push (the
970
+ * comment above), and because a scope that releases its arena never pushes on
971
+ * an array older than its mark (docs/LANGUAGE.md, "Memory model"), so the bytes
972
+ * a grow takes past the old block are never below a mark that is still to be
973
+ * released. A carved chunk (`NISH_CHUNK_CARVED`) lies inside an older one and
974
+ * is never reallocated; an array whose block is anywhere else -- a literal on
975
+ * the stack or in a constant, a shared-memory array, a block another thread's
976
+ * or region's arena handed out, one in the middle of a chunk -- simply takes
977
+ * the copy. */
978
+ static int nish_array_grow_here(nish_array *a, uint64_t old, uint64_t want) {
979
+ #ifdef NISH_ARENA_DEBUG
980
+ /* The debug arena's chunks are cut from its reservation, never malloc'd, so
981
+ none can be `realloc`ed; and a grown array always moves, which is what
982
+ lets a reference to the old block fault. */
983
+ (void)a, (void)old, (void)want;
984
+ return 0;
985
+ #endif
986
+ char *data = a->data, *buf = nish_arena.buf;
987
+ uint64_t more = want - old;
988
+ /* Under the compact-class range this bump needs no realign: it hands out no
989
+ new block, only lengthens the one that ends at `off`, by an 8-rounded
990
+ `more`; the block keeps the alignment it had, and every runtime bump
991
+ after it realigns `off` itself. An array from `nish_alloc_struct` ends
992
+ 8-aligned, so an `off` compiled code left 4 past a boundary is never its
993
+ end, and that array takes the copy. */
994
+ if (buf && data >= buf && data + old == buf + nish_arena.off && more <= nish_arena.cap - nish_arena.off) {
995
+ nish_arena.off += more;
996
+ return 1;
997
+ }
998
+ /* A block of 64 KB or less never has a chunk to itself in the thread's arena
999
+ (`nish_arena_grow`'s floor), so it skips the walk and takes the copy, as it
1000
+ also does in a region whose chunks are smaller. Walking for every small
1001
+ array cost Bounce, which grows about ten thousand, 0.6% instructions.
1002
+
1003
+ The head is relinked by assigning the whole arena, never through a pointer
1004
+ to `nish_arena.chunks`: a link pointer the walk rewrites, or a phi or select
1005
+ of that field and a chunk's `next`, takes the arena's address, which costs
1006
+ every program LTO's GlobalsAA (see `nish_reset_arena`) -- Queens' setup
1007
+ reloaded the arena around each header store and filled an array with a
1008
+ `memset` it had folded, +0.35% instructions. The assignment makes the grown
1009
+ chunk the buffer, full, as the head already was: the buffer is always the
1010
+ head's (`nish_arena_grow`, a release, a reset and a region's adoption all
1011
+ leave it there), and a block that fills it has no room left after it. So a
1012
+ chunk further down is never the buffer, and its relink is the `next` alone. */
1013
+ if (old <= 65536) return 0;
1014
+ nish_chunk *prev = 0, *c = nish_arena.chunks;
1015
+ for (int i = 0; c && i < NISH_GROW_WALK; i++, prev = c, c = c->next) {
1016
+ if ((char *)(c + 1) != data) continue;
1017
+ if ((c->cap & NISH_CHUNK_CARVED) || c->cap != old) return 0;
1018
+ #if defined NISH_ARENA_RANGE && !defined NISH_ARENA_DEBUG
1019
+ /* A chunk of the compact-class range is no malloc's, so `realloc` may not
1020
+ touch it: an array that fills one of its class exactly (a power-of-two
1021
+ block of 128 KiB to 2 MiB) takes the copy. Its chunk keeps its class's
1022
+ `cap` for the release that puts it back on its list. */
1023
+ if (nish_range_owns(c)) return 0;
1024
+ #endif
1025
+ if (want > (uint64_t)(SIZE_MAX - sizeof(nish_chunk))) nish_oom();
1026
+ nish_chunk *n = realloc(c, sizeof *n + (size_t)want);
1027
+ if (!n) nish_oom();
1028
+ n->cap = want;
1029
+ a->data = (char *)(n + 1);
1030
+ if (prev) prev->next = n;
1031
+ else nish_arena = (struct nish_arena){ (char *)(n + 1), want, want, n };
1032
+ return 1;
1033
+ }
1034
+ return 0;
1035
+ }
1036
+ #endif
1037
+
573
1038
  __attribute__((noinline)) void nish_array_grow(nish_array *a, uint64_t elem_size) {
574
1039
  #ifdef NISH_ASAN
575
1040
  /* One more slot, not double (see `nish_grown`): in place while a normal build
@@ -599,6 +1064,10 @@ __attribute__((noinline)) void nish_array_grow(nish_array *a, uint64_t elem_size
599
1064
  char *data = nish_alloc_struct(room * elem_size);
600
1065
  NISH_POISON(data + cap * elem_size, (room - cap) * elem_size);
601
1066
  #else
1067
+ if (a->cap && nish_array_grow_here(a, (a->cap * elem_size + 7) & ~(uint64_t)7, (cap * elem_size + 7) & ~(uint64_t)7)) {
1068
+ a->cap = cap;
1069
+ return;
1070
+ }
602
1071
  char *data = nish_alloc_struct(cap * elem_size);
603
1072
  #endif
604
1073
  if (a->len) memcpy(data, a->data, a->len * elem_size);
@@ -20,8 +20,13 @@ them.
20
20
 
21
21
  ## How it is linked
22
22
 
23
- `scripts/build.sh` compiles every `*.c` here for a link whose IR declares an
24
- `sqlite3_*` or `nishsqlite_*` function, and for no other link. The options are
23
+ `nish-sqlite.c` starts with `#include "sqlite3.c"`, so SQLite and the
24
+ `nish/sqlite` adapter are one unit: the cursors call SQLite's internal
25
+ functions, which are `static` in the amalgamation
26
+ ([docs/sqlite-cursor.md](../../docs/sqlite-cursor.md#the-build-decision)).
27
+ `scripts/build.sh` compiles every `*.c` here except `sqlite3.c` for a link
28
+ whose IR declares an `sqlite3_*` or `nishsqlite_*` function, and for no other
29
+ link. The options are
25
30
  in `build.sh`, under "SQLite's compile-time options". `NISH_SQLITE_CFLAGS` adds
26
31
  to them (`docs/guide/using-nish/cli.md`). `nish --link` and `nish run` compile
27
32
  these units once per recipe into an entry of the runtime cache of their own
@@ -40,6 +45,14 @@ for the units and the files the cache key fingerprints (`sqliteUnits`,
40
45
  3. Update the table above, the two file hashes included (`openssl dgst
41
46
  -sha3-256 sqlite3.c sqlite3.h`), the version in `THIRD_PARTY_NOTICES.md`, and the
42
47
  numbers in `tests/link/sqlite_link*/expected.out`.
43
- 4. Run `node tests/run.js link`, `node tests/run.js sqlite-link`,
48
+ 4. Re-check every internal SQLite function the cursor adapter in
49
+ `nish-sqlite.c` calls, the list in
50
+ [`docs/sqlite-cursor.md`](../../docs/sqlite-cursor.md#what-the-adapter-calls):
51
+ these are `SQLITE_PRIVATE`, not SQLite's API, and a release may change one
52
+ without notice. Diff each one's declaration and body against the old
53
+ `sqlite3.c`, including what it asserts about the mutex and the cursor's
54
+ state, and the `KeyInfo` fields the adapter fills by hand against
55
+ `sqlite3KeyInfoOfIndex`. Update the adapter and that list for any change.
56
+ 5. Run `node tests/run.js link`, `node tests/run.js sqlite-link`,
44
57
  `WASI_SYSROOT=/usr node tests/run.js wasi` and the third-party-licence
45
58
  section.