Make Blob reads iterative, validate before allocating, and open with O_CLOEXEC (#4608)

* Make Blob reads iterative, validate before allocating, and open with O_CLOEXEC

- Blob: ask a source before allocating its bytes on read.

* Blob: hold a validation frame's window across a stack push

* Format tests/harness/blob-fd-cloexec.test.ts

* Blob: validate only the window a slice reads
This commit is contained in:
Chris Tate
2026-11-29 12:35:36 +00:00
committed by GitHub
parent 5d20261b26
commit 9c8118482e
14 changed files with 504 additions and 56 deletions
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/blob-doubled-chain-stale.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/blob-slice-copied-bytes.ts"
],
"diags": []
}
+254 -47
View File
@@ -360,58 +360,255 @@ typedef struct ScrBlobChain {
size_t len;
} ScrBlobChain;
static bool scr_blob_chain_read(void *ctx, size_t off, size_t len, uint8_t *dst) {
ScrBlobChain *c = ctx;
/* A read of the whole Blob asks every file part, an empty one included:
* the part's own check is what turns a changed or removed file into
* NotReadableError. A read of a window inside it (a slice, which shares
* this chain) asks only the file parts the window covers, so a slice of
* copied bytes does not depend on a file outside it. */
bool whole = off == 0 && len == c->len;
size_t at = 0;
for (size_t i = 0; i < c->nsegs; i++) {
ScrBlobSeg *seg = &c->segs[i];
bool asked = whole || (seg->len != 0 && at < off + len && off < at + seg->len);
if (asked && seg->source != NULL &&
!seg->source->read(seg->source->ctx, seg->source_off, 0, NULL)) {
return false;
}
at += seg->len;
}
size_t pos = 0, done = 0;
for (size_t i = 0; i < c->nsegs && done < len; i++) {
ScrBlobSeg *seg = &c->segs[i];
if (off >= pos + seg->len) {
pos += seg->len;
continue;
}
size_t skip = off > pos ? off - pos : 0;
size_t take = seg->len - skip;
if (take > len - done) take = len - done;
if (seg->source != NULL) {
if (!seg->source->read(seg->source->ctx, seg->source_off + skip, take, dst + done)) return false;
} else if (take) {
memcpy(dst + done, c->store->data + seg->store_off + skip, take);
}
done += take;
pos += seg->len;
}
return done == len;
static bool scr_blob_chain_read(void *ctx, size_t off, size_t len, uint8_t *dst);
/* Whether a Blob source is a chain (a Blob built from several sources). */
static bool scr_blob_source_is_chain(const ScrBlobSource *source) {
return source != NULL && source->read == scr_blob_chain_read;
}
/* The Blob's release: the store, every file part's share, the segments. */
static void scr_blob_chain_release(void *ctx) {
/* One window of a chain still to walk. A frame starts at `at` in `chain`,
* stops at `end`, and remembers where in the segment list it is. */
typedef struct {
ScrBlobChain *chain;
size_t at;
size_t end;
size_t seg;
size_t base; /* where the current segment starts, in the chain */
} ScrBlobWindow;
/* A (pointer, window) pair a walk has already handled. */
typedef struct {
const void *ptr;
size_t at;
size_t end;
} ScrBlobVisit;
typedef struct {
ScrBlobVisit *slots; /* ptr == NULL marks an empty slot */
size_t cap;
size_t count;
} ScrBlobVisitSet;
static size_t scr_blob_visit_slot(const void *ptr, size_t at, size_t end, size_t cap) {
uint64_t h = (uint64_t)(uintptr_t)ptr;
h ^= (uint64_t)at * UINT64_C(0x9e3779b97f4a7c15);
h ^= (uint64_t)end * UINT64_C(0xc2b2ae3d27d4eb4f);
h ^= h >> 29;
return (size_t)h & (cap - 1);
}
/* Records (ptr, at, end); false when the set already held it. */
static bool scr_blob_visit_add(ScrBlobVisitSet *set, const void *ptr, size_t at, size_t end) {
if ((set->count + 1) * 2 > set->cap) {
size_t cap = set->cap != 0 ? set->cap * 2 : 64;
ScrBlobVisit *slots = calloc(cap, sizeof *slots);
if (!slots) scr_trap("scriptc: out of memory\n");
for (size_t i = 0; i < set->cap; i++) {
if (set->slots[i].ptr == NULL) continue;
size_t j =
scr_blob_visit_slot(set->slots[i].ptr, set->slots[i].at, set->slots[i].end, cap);
while (slots[j].ptr != NULL) j = (j + 1) & (cap - 1);
slots[j] = set->slots[i];
}
free(set->slots);
set->slots = slots;
set->cap = cap;
}
size_t i = scr_blob_visit_slot(ptr, at, end, set->cap);
while (set->slots[i].ptr != NULL) {
if (set->slots[i].ptr == ptr && set->slots[i].at == at && set->slots[i].end == end)
return false;
i = (i + 1) & (set->cap - 1);
}
set->slots[i] = (ScrBlobVisit){ptr, at, end};
set->count++;
return true;
}
/* Grows the walk's frame stack. Pushing can move the array, so a walk
* indexes the stack by number and never keeps a frame pointer across it. */
static void scr_blob_window_push(ScrBlobWindow **stack, size_t *n, size_t *cap,
ScrBlobChain *chain, size_t at, size_t end) {
if (*n == *cap) {
size_t grown = *cap != 0 ? *cap * 2 : 16;
ScrBlobWindow *next = realloc(*stack, grown * sizeof *next);
if (!next) scr_trap("scriptc: out of memory\n");
*stack = next;
*cap = grown;
}
(*stack)[(*n)++] = (ScrBlobWindow){chain, at, end, 0, 0};
}
/* Asks every file part the window [off, off + len) of `chain` depends on:
* a whole read asks every part, an empty one included; a window inside the
* chain asks only the parts it covers, so a slice of copied bytes does not
* depend on a file outside it. Each distinct part is asked once and each
* chain window is visited once, so a Blob built from the same sub-Blob a
* dozen times costs one visit per level, not one per path. Iterative: how
* deeply a Blob nests is program data. */
static bool scr_blob_chain_validate(ScrBlobChain *chain, size_t off, size_t len) {
ScrBlobVisitSet seen = {0};
ScrBlobWindow *stack = NULL;
size_t n = 0, cap = 0;
bool ok = true;
(void)scr_blob_visit_add(&seen, chain, off, off + len);
scr_blob_window_push(&stack, &n, &cap, chain, off, off + len);
while (ok && n > 0) {
ScrBlobWindow *frame = &stack[n - 1];
ScrBlobChain *c = frame->chain;
/* A push can move the stack, so this iteration's window is copied out
* before any push can reallocate it; `frame` itself is not touched
* again after a push. */
size_t window_at = frame->at;
size_t window_end = frame->end;
if (frame->seg >= c->nsegs) {
n--;
continue;
}
ScrBlobSeg *seg = &c->segs[frame->seg];
size_t seg_start = frame->base;
size_t seg_end = frame->base + seg->len;
frame->base = seg_end;
frame->seg++;
bool whole = window_at == 0 && window_end == c->len;
bool overlap = seg->len != 0 && seg_start < window_end && window_at < seg_end;
if (!(whole || overlap) || seg->source == NULL) continue;
if (scr_blob_source_is_chain(seg->source)) {
/* A whole read asks every part, an empty one included, for the window
* at its start. A read of a window inside the chain asks only the
* bytes it covers (below), so a slice made of copied bytes does not
* depend on a file part outside it. */
ScrBlobChain *inner = seg->source->ctx;
if (whole && scr_blob_visit_add(&seen, inner, seg->source_off, seg->source_off))
scr_blob_window_push(&stack, &n, &cap, inner, seg->source_off, seg->source_off);
/* The copy descends into the part of the seg the window covers, and
* that descent validates its own window; visit it here too, so a stale
* file inside a nested part is found before any output is allocated. */
if (overlap) {
size_t from = window_at > seg_start ? window_at - seg_start : 0;
size_t to = seg_end < window_end ? seg->len : window_end - seg_start;
if (scr_blob_visit_add(&seen, inner, seg->source_off + from, seg->source_off + to))
scr_blob_window_push(&stack, &n, &cap, inner, seg->source_off + from,
seg->source_off + to);
}
continue;
}
if (!scr_blob_visit_add(&seen, seg->source, 0, 0)) continue;
if (!seg->source->read(seg->source->ctx, seg->source_off, 0, NULL)) ok = false;
}
free(stack);
free(seen.slots);
return ok;
}
/* Copies the window [off, off + len) of `chain` into dst. Nested chains are
* walked with an explicit stack rather than a call per level; the window was
* validated first, so a part only contributes its bytes here. */
static bool scr_blob_chain_copy(ScrBlobChain *chain, size_t off, size_t len, uint8_t *dst) {
ScrBlobWindow *stack = NULL;
size_t n = 0, cap = 0;
size_t done = 0;
bool ok = true;
scr_blob_window_push(&stack, &n, &cap, chain, off, off + len);
while (ok && n > 0) {
ScrBlobWindow *frame = &stack[n - 1];
ScrBlobChain *c = frame->chain;
if (frame->at >= frame->end || frame->seg >= c->nsegs) {
n--;
continue;
}
ScrBlobSeg *seg = &c->segs[frame->seg];
size_t seg_start = frame->base;
size_t seg_end = frame->base + seg->len;
if (frame->at >= seg_end) {
frame->base = seg_end;
frame->seg++;
continue;
}
size_t skip = frame->at - seg_start;
size_t take = seg->len - skip;
if (take > frame->end - frame->at) take = frame->end - frame->at;
frame->base = seg_end;
frame->seg++;
frame->at += take;
if (take == 0) continue;
if (seg->source == NULL) {
memcpy(dst + done, c->store->data + seg->store_off + skip, take);
done += take;
} else if (scr_blob_source_is_chain(seg->source)) {
ScrBlobChain *inner = seg->source->ctx;
scr_blob_window_push(&stack, &n, &cap, inner, seg->source_off + skip,
seg->source_off + skip + take);
} else if (!seg->source->read(seg->source->ctx, seg->source_off + skip, take, dst + done)) {
ok = false;
} else {
done += take;
}
}
free(stack);
return ok && done == len;
}
static bool scr_blob_chain_read(void *ctx, size_t off, size_t len, uint8_t *dst) {
ScrBlobChain *c = ctx;
scr_blob_store_release(c->store);
for (size_t i = 0; i < c->nsegs; i++) {
ScrBlobSource *source = c->segs[i].source;
if (source != NULL && --source->rc == 0) {
if (!scr_blob_chain_validate(c, off, len)) return false;
/* A NULL destination asks only whether the window can be read: the
* caller validates a window before it allocates that much output, so a
* changed file answers NotReadableError even when the Blob's logical
* length is far beyond what could ever be allocated. */
if (len == 0 || dst == NULL) return true;
return scr_blob_chain_copy(c, off, len, dst);
}
/* One source waiting to be released. */
typedef struct {
ScrBlobSource **items;
size_t n;
size_t cap;
} ScrBlobWork;
static void scr_blob_work_push(ScrBlobWork *w, ScrBlobSource *source) {
if (w->n == w->cap) {
size_t grown = w->cap != 0 ? w->cap * 2 : 16;
ScrBlobSource **next = realloc(w->items, grown * sizeof *next);
if (!next) scr_trap("scriptc: out of memory\n");
w->items = next;
w->cap = grown;
}
w->items[w->n++] = source;
}
/* The Blob's release: the store, every file part's share, the segments.
* A chain part hands its own chain to the worklist instead of recursing, so
* a deeply nested Blob frees without consuming the C stack. */
static void scr_blob_chain_release(void *ctx) {
ScrBlobChain *chain = ctx;
ScrBlobWork work = {0};
for (size_t i = 0; i < chain->nsegs; i++) {
if (chain->segs[i].source != NULL) scr_blob_work_push(&work, chain->segs[i].source);
}
scr_blob_store_release(chain->store);
free(chain->segs);
free(chain);
while (work.n > 0) {
ScrBlobSource *source = work.items[--work.n];
if (--source->rc != 0) continue;
if (scr_blob_source_is_chain(source)) {
ScrBlobChain *inner = source->ctx;
for (size_t i = 0; i < inner->nsegs; i++) {
if (inner->segs[i].source != NULL) scr_blob_work_push(&work, inner->segs[i].source);
}
scr_blob_store_release(inner->store);
free(inner->segs);
free(inner);
free(source);
} else {
if (source->release) source->release(source->ctx);
free(source);
}
}
free(c->segs);
free(c);
free(work.items);
}
static ScrBlob *scr_blob_construct(const ScrDyn *sources, const ScrDyn *options) {
@@ -737,11 +934,21 @@ static void scr_blob_not_readable(void) {
* array can hold (a chain of file-backed parts can exceed it without
* holding the bytes). */
static ScrBytes *scr_blob_copy_bytes(const ScrBlob *b) {
/* Ask the source before the output is allocated, as Node's reader does: a
* changed or removed file answers NotReadableError even when the Blob's
* logical length is far beyond what could be allocated (a deeply doubled
* chain of file parts reaches terabytes without holding the bytes). */
if (b->source) {
if (!b->source->read(b->source->ctx, b->off, b->len, NULL)) {
scr_blob_not_readable();
return NULL;
}
}
ScrBytes *bytes = scr_bytes_new(SCR_BYTES_U8, (double)b->len);
if (bytes == NULL) return NULL; /* RangeError pending: the read rejects */
if (b->source) {
/* The source is asked even for an empty Blob: its check is what turns
* a changed or removed file into NotReadableError. */
/* Fill the buffer now; the window was just validated, and a file that
* changed in between is caught here too. */
if (!b->source->read(b->source->ctx, b->off, b->len, bytes->len ? bytes->data : NULL)) {
scr_bytes_release(bytes);
scr_blob_not_readable();
+3 -1
View File
@@ -38,7 +38,9 @@ bool scr_blob_body_info(const ScrDyn *value, ScrBytes **bytes, ScrStr **type);
* into an immutable store (fs.openAsBlob's file). read fills dst with the
* range [off, off + len) of the WHOLE source and answers false when the
* source changed or cannot be read; every read of the Blob then rejects
* with Node's NotReadableError DOMException. release drops what ctx owns
* with Node's NotReadableError DOMException. A NULL dst asks only whether
* the range can still be read, so a caller validates a window before it
* allocates that much output. release drops what ctx owns
* (the Blob frees the source record itself). Slices
* share the source (rc), so scr_blob_from_source moves the source's
* reference in, borrows type, and answers +1 (NULL with the exception
+18 -6
View File
@@ -31,6 +31,18 @@
#ifndef O_SYNC
#define O_SYNC 0
#endif
/* The descriptor a Blob keeps must not survive an exec: a child spawned
* between the open and a later fcntl would inherit it. O_CLOEXEC (POSIX) and
* the Windows CRT's _O_NOINHERIT are part of the open itself, so no window
* exists; a platform with neither keeps the caller's fcntl-based close-on-
* exec. */
#if defined(_WIN32) && defined(_O_NOINHERIT)
#define SCR_FILE_HANDLE_NOINHERIT _O_NOINHERIT
#elif defined(O_CLOEXEC)
#define SCR_FILE_HANDLE_NOINHERIT O_CLOEXEC
#else
#define SCR_FILE_HANDLE_NOINHERIT 0
#endif
/* One shared mutable descriptor slot gives aliases Node's close/fd behavior.
* The last native reference closes a still-open descriptor; explicit close
@@ -255,16 +267,16 @@ ScrFileHandle *scr_file_handle_open(ScrStr *path, ScrStr *flags, double mode) {
return h;
}
/* A read-only open that cannot park the event loop on a FIFO's writer. The
* caller only stats the descriptor (fs.openAsBlob's creation stat) and
* closes it, so the non-blocking flag needs no clearing: opening a FIFO
* without a writer answers at once instead of waiting, as Node's open does
* off the event loop. A regular file, a directory and a device open the
/* A read-only open that cannot park the event loop on a FIFO's writer and
* that a child can never inherit. fs.openAsBlob keeps this descriptor for
* the Blob's life, so the non-blocking flag needs no clearing: opening a
* FIFO without a writer answers at once instead of waiting, as Node's open
* does off the event loop. A regular file, a directory and a device open the
* same way. */
ScrFileHandle *scr_file_handle_open_read_only_nonblocking(ScrStr *path) {
scr_file_handle_dyn_install();
if (!scr_file_handle_path_valid(path)) return NULL;
int fd = open(path->data, O_RDONLY | O_NONBLOCK | O_BINARY);
int fd = open(path->data, O_RDONLY | O_NONBLOCK | O_BINARY | SCR_FILE_HANDLE_NOINHERIT);
if (fd < 0) {
scr_fs_throw(errno, "open", path);
return NULL;
+4 -2
View File
@@ -161,7 +161,9 @@ static void scr_fs_blob_close_on_exec(ScrFileHandle *h) {
* descriptor the creation open took (never from a path opened afterwards).
* Every read takes the held file's stat (it must still have the size and
* modification time the Blob was created with) and checks that the path
* still names the same file (its device and inode). */
* still names the same file (its device and inode). A NULL destination asks
* only whether the range can still be read, so a caller can validate a
* window before it allocates that much output. */
static bool scr_fs_blob_read(void *ctx, size_t off, size_t len, uint8_t *dst) {
ScrFsBlob *b = ctx;
int error = 0;
@@ -186,7 +188,7 @@ static bool scr_fs_blob_read(void *ctx, size_t off, size_t len, uint8_t *dst) {
}
if (path_st != NULL) scr_stats_release(path_st);
}
if (ok && len) {
if (ok && len && dst != NULL) {
ScrBytes *buf = scr_bytes_new(SCR_BYTES_U8, (double)len);
double got = scr_file_handle_read(b->handle, buf, 0, (double)len, (double)off, false);
if (scr_exc_pending()) {
+22
View File
@@ -0,0 +1,22 @@
// A Blob built by doubling a file-backed Blob forty times has a logical
// length in the terabytes. Reading it asks the source first, so a file that
// changed since creation answers NotReadableError instead of attempting the
// allocation, as Node's reader does when the part it pulls is stale.
import { mkdtempSync, openAsBlob, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = mkdtempSync(join(tmpdir(), "scriptc-blob-doubled-"));
const path = join(dir, "payload.bin");
writeFileSync(path, "hello");
let blob = await openAsBlob(path);
for (let i = 0; i < 40; i++) blob = new Blob([blob, blob]);
console.log("size", blob.size);
writeFileSync(path, "HELLO");
try {
const text = await blob.text();
console.log("read", text.length);
} catch (error) {
console.log("read", (error as Error).name);
}
rmSync(dir, { recursive: true, force: true });
+22
View File
@@ -0,0 +1,22 @@
// A slice of a composed Blob that covers only copied bytes does not depend
// on a file part outside it: a nested chain is validated for the window the
// slice reads, not for the part its start happens to fall in.
import { mkdtempSync, openAsBlob, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const dir = mkdtempSync(join(tmpdir(), "scriptc-blob-slice-"));
const path = join(dir, "payload.bin");
writeFileSync(path, "hello");
const chain = new Blob([await openAsBlob(path), "TAIL"]);
const inner = chain.slice(2, 9);
const outer = new Blob([inner, "x"]);
const copyOnly = outer.slice(3, 7);
console.log("size", copyOnly.size);
writeFileSync(path, "HELLO");
try {
console.log("read", JSON.stringify(await copyOnly.text()));
} catch (error) {
console.log("read", (error as Error).name);
}
rmSync(dir, { recursive: true, force: true });
+28
View File
@@ -0,0 +1,28 @@
// A Blob chain's depth is program data: nesting a file-backed Blob keeps
// reading and freeing one level deep, a Blob built from the same empty
// sub-Blob twice per level still validates in linear time, and a file that
// changed underneath the chain still turns the read into NotReadableError.
// Usage: main <file> <levels> <nest|double|double-change>
import { openAsBlob, writeFileSync } from "node:fs";
const levels = Number(process.argv[3] ?? "0");
const mode = process.argv[4] ?? "double";
let blob = await openAsBlob(process.argv[2]!);
if (mode === "nest") {
for (let i = 0; i < levels; i++) blob = new Blob([blob, "x"]);
} else {
for (let i = 0; i < levels; i++) blob = new Blob([blob, blob]);
}
console.log("built", blob.size);
if (mode === "double-change") {
writeFileSync(process.argv[2]!, "grown");
try {
const text = await blob.text();
console.log("changed", text.length);
} catch (error) {
console.log("changed", (error as Error).name);
}
} else {
const text = await blob.text();
console.log("read", text.length);
}
+7
View File
@@ -0,0 +1,7 @@
// fs.openAsBlob keeps the descriptor it opened for the Blob's whole life, so
// the open itself has to carry close-on-exec: a child spawned while the Blob
// lives must not inherit the file. Usage: main <file>
import { openAsBlob } from "node:fs";
const blob = await openAsBlob(process.argv[2]!);
console.log("size", blob.size);
+65
View File
@@ -0,0 +1,65 @@
/* A Blob's chain depth comes from program data. Nesting a file-backed Blob
* 200000 times used to recurse once per level when the bytes were read and
* again when the chain was freed (a sanitized run dies of stack overflow),
* and building each level from the same empty sub-Blob twice used to cost
* two validations per path, so forty doublings never finished. Both walks
* are iterative now, and each distinct file part is asked once. The fixtures
* run as compiled binaries only: Node's own blob reader recurses too and
* throws RangeError after a few thousand levels. */
import { execFile } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { compile } from "@scriptc/compiler";
const execFileAsync = promisify(execFile);
const repoRoot = join(import.meta.dirname, "../..");
const entry = join(repoRoot, "tests/fixtures/blob-chain-depth/main.ts");
const outDir = join(repoRoot, "node_modules/.cache/scriptc-tests/blob-chain-depth");
const sanitize = process.env["SCRIPTC_SAN"] === "1";
let binary = "";
let dir = "";
async function run(file: string, levels: string, mode: string): Promise<string> {
const { stdout } = await execFileAsync(binary, [file, levels, mode], {
encoding: "utf8",
timeout: 120_000,
});
return stdout;
}
describe("a Blob chain built at depth", () => {
beforeAll(async () => {
mkdirSync(outDir, { recursive: true });
const result = await compile(entry, { outPath: join(outDir, "main"), outDir, sanitize });
if (!result.ok)
throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"));
binary = result.binaryPath;
dir = mkdtempSync(join(tmpdir(), "scriptc-blob-depth-"));
}, 600_000);
afterAll(() => {
if (dir !== "") rmSync(dir, { recursive: true, force: true });
});
test("nesting a file-backed Blob 200000 deep reads and frees without recursing", async () => {
const file = join(dir, "nested.txt");
writeFileSync(file, "hello");
expect(await run(file, "200000", "nest")).toBe("built 200005\nread 200005\n");
}, 180_000);
test("forty doublings of an empty file Blob validate once per level", async () => {
const file = join(dir, "empty.bin");
writeFileSync(file, "");
expect(await run(file, "40", "double")).toBe("built 0\nread 0\n");
}, 60_000);
test("a file changed under a deep chain still rejects the read", async () => {
const file = join(dir, "changed.bin");
writeFileSync(file, "");
expect(await run(file, "40", "double-change")).toBe("built 0\nchanged NotReadableError\n");
}, 60_000);
});
+67
View File
@@ -0,0 +1,67 @@
/* fs.openAsBlob holds its descriptor for the Blob's whole life, so the open
* itself has to carry close-on-exec. Setting FD_CLOEXEC with a later fcntl
* leaves a window: a child spawned from another thread in that window
* inherits the file. The check runs the open under strace and reads the
* openat that names the payload. Linux only; skipped when strace is absent. */
import { execFile } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { compile } from "@scriptc/compiler";
const execFileAsync = promisify(execFile);
const repoRoot = join(import.meta.dirname, "../..");
const entry = join(repoRoot, "tests/fixtures/blob-fd-cloexec/main.ts");
const outDir = join(repoRoot, "node_modules/.cache/scriptc-tests/blob-fd-cloexec");
const sanitize = process.env["SCRIPTC_SAN"] === "1";
let binary = "";
let dir = "";
let payload = "";
async function hasStrace(): Promise<boolean> {
try {
await execFileAsync("strace", ["--version"]);
return true;
} catch {
return false;
}
}
describe.skipIf(process.platform !== "linux")("fs.openAsBlob's descriptor", () => {
beforeAll(async () => {
mkdirSync(outDir, { recursive: true });
const result = await compile(entry, { outPath: join(outDir, "main"), outDir, sanitize });
if (!result.ok)
throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"));
binary = result.binaryPath;
dir = mkdtempSync(join(tmpdir(), "scriptc-blob-cloexec-"));
payload = join(dir, "payload.bin");
writeFileSync(payload, "hello");
}, 600_000);
afterAll(() => {
if (dir !== "") rmSync(dir, { recursive: true, force: true });
});
test("is opened close-on-exec, not flagged afterwards", async () => {
if (!(await hasStrace())) return; // no tracer on this host: nothing to read
const log = join(dir, "strace.log");
await execFileAsync(
"strace",
["-f", "-s", "4096", "-e", "trace=openat", "-o", log, binary, payload],
{
timeout: 60_000,
// LeakSanitizer cannot run under a tracer; the trace is the check.
env: { ...process.env, ASAN_OPTIONS: "detect_leaks=0" },
},
);
const lines = readFileSync(log, "utf8")
.split("\n")
.filter((line) => line.includes(payload));
expect(lines.length).toBeGreaterThan(0);
for (const line of lines) expect(line).toContain("O_CLOEXEC");
}, 120_000);
});
@@ -0,0 +1 @@
{"plain": 1500, "san": 5000}
@@ -0,0 +1 @@
{"plain": 1200, "san": 2500}