nish 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