@mrwinston/fibers 0.1.0 → 0.2.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/README.md CHANGED
@@ -47,7 +47,8 @@ longer works on current Node.js. It needs no patched Node: it runs on the offici
47
47
  - **Node.js 24 or 26.** Prebuilt binaries ship for both. Other versions build from source on
48
48
  install, and load only if their thread-local variables are known (see
49
49
  [Upgrading Node.js](#upgrading-nodejs)).
50
- - **x64 Linux with glibc.** Not macOS, Windows, arm64 or musl (Alpine).
50
+ - **x64 Linux with glibc 2.34 or later** (Debian 12, Ubuntu 22.04, RHEL 9, Amazon Linux 2023,
51
+ or later). Not macOS, Windows, arm64 or musl (Alpine).
51
52
  - **An unstripped `node` executable.** The addon reads the binary's symbol table. Official
52
53
  builds and nvm/fnm/Volta downloads have it. Some distribution packages strip it, and the addon
53
54
  then refuses to load with `ERR_FIBER_UNSUPPORTED_NODE`.
@@ -63,6 +64,11 @@ npm install @mrwinston/fibers
63
64
  On Node 24 and 26 the install uses the prebuilt binary and compiles nothing. On other versions
64
65
  it compiles with node-gyp, which needs `g++`, `make` and `python3`.
65
66
 
67
+ Fibers only works on x64 Linux, but the package installs on every platform. This lets an app
68
+ that also runs elsewhere (on a developer's Mac, for example) list it as a dependency. On any
69
+ other platform the install succeeds without building anything, and the package does not work
70
+ there: importing it throws `ERR_FIBER_UNSUPPORTED_PLATFORM`. Import it only on x64 Linux.
71
+
66
72
  The package is CommonJS with an ES module entry that re-exports it, so `import` and `require`
67
73
  load the same copy. Only one copy may be loaded per process; a second copy throws
68
74
  `ERR_FIBER_ALREADY_LOADED` when it loads (check with `npm ls @mrwinston/fibers`).
@@ -172,21 +178,23 @@ Whether the caller is running inside a fiber.
172
178
 
173
179
  Counters for the current JS thread:
174
180
 
175
- | field | meaning |
176
- | --------------- | ------------------------------------------------------------------------ |
177
- | `live` | fibers started and not finished |
178
- | `fibersCreated` | fibers created so far (finished ones are reused) |
179
- | `pooled` | finished fibers that kept their stack memory, ready for reuse |
180
- | `released` | finished fibers whose stack memory was released (beyond the pool size) |
181
- | `poolSize` | the current pool size (see `setPoolSize`) |
182
- | `switches` | switches between fibers since the addon loaded |
181
+ | field | meaning |
182
+ | --------------- | ---------------------------------------------------------------------------- |
183
+ | `live` | fibers started and not finished |
184
+ | `fibersCreated` | fibers created so far (finished ones are reused) |
185
+ | `pooled` | finished fibers that kept their stack memory, ready for reuse |
186
+ | `released` | finished fibers whose stack memory was released (beyond the pool size) |
187
+ | `poolSize` | the current pool size (see `setPoolSize`) |
188
+ | `stackSize` | the fiber stack size in bytes, the same in every thread (see `setStackSize`) |
189
+ | `switches` | switches between fibers since the addon loaded |
183
190
 
184
191
  ### `Fiber.setStackSize(bytes: number): void`
185
192
 
186
- Sets the stack size of fibers created afterwards. Default and minimum: 2 MiB. JS gets all but
187
- 1 MiB, which is kept for C++ frames, so by default a fiber can recurse about as deep as the main
188
- thread. Node's `--stack-size` does not apply to fibers. Call it before the first `Fiber.run` in
189
- the process; afterwards it throws `ERR_FIBER_STACK_SIZE_LOCKED`.
193
+ Sets the stack size of fibers created afterwards. Default and minimum: 2 MiB; maximum: 1 GiB.
194
+ JS gets all but 1 MiB, which is kept for C++ frames, so by default a fiber can recurse about as
195
+ deep as the main thread. A runaway recursion uses that much memory before its `RangeError`.
196
+ Node's `--stack-size` does not apply to fibers. Call it before the first `Fiber.run` in the
197
+ process; afterwards it throws `ERR_FIBER_STACK_SIZE_LOCKED`.
190
198
 
191
199
  ### `Fiber.setPoolSize(count: number): void`
192
200
 
@@ -220,23 +228,17 @@ suspending in places where suspending would corrupt state shared with other fibe
220
228
  | inside an `AsyncResource` scope the fiber entered itself (`runInAsyncScope`, `bind`, `EventEmitterAsyncResource`) | `ERR_FIBER_AWAIT_IN_ASYNC_SCOPE` |
221
229
  | inside JS run by the inspector (`Session#post("Runtime.evaluate")`, the DevTools console) | `ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE` |
222
230
  | inside code that `vm` evaluates (`vm.runIn*Context`, `vm.Script#runIn*Context`, `vm.SourceTextModule#evaluate`) | `ERR_FIBER_AWAIT_IN_VM` |
223
- | inside JS that WebAssembly calls under JSPI (an import called from a `WebAssembly.promising` function, before the wasm first suspends) | `ERR_FIBER_AWAIT_IN_JSPI` |
224
-
225
- What still works:
226
231
 
227
- - **vm:** awaiting before or after the vm call, and in a fiber that the vm code starts itself
228
- (`Fiber.run` inside the vm code), which has its own stack.
229
- - **JSPI:** awaiting the promise of the `promising` function, making the import a
230
- `WebAssembly.Suspending`, or starting a fiber inside the import.
232
+ What still works with vm: awaiting before or after the vm call, and in a fiber that the vm code
233
+ starts itself (`Fiber.run` inside the vm code), which has its own stack.
231
234
 
232
235
  <details>
233
- <summary>How the vm and JSPI checks work, and what they don't cover</summary>
236
+ <summary>How the vm check works, and what it doesn't cover</summary>
234
237
 
235
238
  Loading the package wraps `vm.Script.prototype.runInContext` and `.runInThisContext` (every
236
- `vm.runIn*` goes through them), `vm.Module.prototype.evaluate` (with
237
- `--experimental-vm-modules`) and `WebAssembly.promising`. The wrappers count evaluations in
238
- progress on the current fiber, and `Fiber.await` compares the count with 0, at no measurable
239
- cost.
239
+ `vm.runIn*` goes through them) and `vm.Module.prototype.evaluate` (with
240
+ `--experimental-vm-modules`). The wrappers count evaluations in progress on the current fiber,
241
+ and `Fiber.await` compares the count with 0, at no measurable cost.
240
242
 
241
243
  Not covered:
242
244
 
@@ -247,9 +249,7 @@ Not covered:
247
249
 
248
250
  Why vm is refused: a vm call is a synchronous step of its caller. With `timeout` or
249
251
  `breakOnSigint`, Node's watchdog terminates whatever JS runs when it fires, and a fiber
250
- suspended inside past the timeout aborted the process. Why JSPI is refused: V8 keeps the wasm
251
- stack it switched to per isolate, not per fiber, so two fibers suspended there aborted the
252
- process.
252
+ suspended inside past the timeout aborted the process.
253
253
 
254
254
  </details>
255
255
 
@@ -267,7 +267,6 @@ error shows the async callers of `Fiber.run`), and the load-time codes, which ar
267
267
  | `ERR_FIBER_AWAIT_IN_ASYNC_SCOPE` | `Fiber.await`, wrapped functions | see [Where `Fiber.await` throws](#where-fiberawait-throws) |
268
268
  | `ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE` | `Fiber.await`, wrapped functions | same |
269
269
  | `ERR_FIBER_AWAIT_IN_VM` | `Fiber.await`, wrapped functions | same |
270
- | `ERR_FIBER_AWAIT_IN_JSPI` | `Fiber.await`, wrapped functions | same |
271
270
  | `ERR_FIBER_REQUIRE_IN_PROGRESS` | `require()` | another fiber is still evaluating that module (see [Modules with top-level await](#modules-with-top-level-await)) |
272
271
  | `ERR_FIBER_AWAIT_OUTSIDE_FIBER` | `Fiber.await`, wrapped functions | called outside `Fiber.run` |
273
272
  | `ERR_FIBER_STACK_SIZE_LOCKED` | `Fiber.setStackSize` | called after the first `Fiber.run` in the process |
@@ -296,6 +295,12 @@ Errors for invalid arguments (`TypeError`, `RangeError`) have no code.
296
295
  - **Wasm code memory is not reclaimed.** The addon turns on `--no-wasm-code-gc`, because V8
297
296
  aborts once `fetch()` (which uses wasm) runs while fibers are suspended. See
298
297
  `FIBERS_WASM_CODE_GC` below.
298
+ - **No JSPI.** Loading the package removes `WebAssembly.promising` and `WebAssembly.Suspending`
299
+ (JavaScript Promise Integration), so code that checks for them does what it does on an engine
300
+ without JSPI. Other WebAssembly keeps working. During a garbage collection V8 scans the stacks
301
+ of JSPI once for every suspended fiber, which moves the objects on them more than once and
302
+ crashes the process. `vm` contexts lose the two functions too, before code first runs in them.
303
+ Don't use references to them taken before the package was loaded.
299
304
  - **C++ state across a suspending callback.** When C++ calls JS that suspends (a `toJSON` or
300
305
  getter that awaits, for example), other fibers run while that C++ frame waits. Suspending
301
306
  inside `JSON.stringify`, `JSON.parse` revivers, `v8.serialize`, `structuredClone`, proxy traps
@@ -399,7 +404,8 @@ starts `test/fixture-<subject>.mjs`, which sends its results back with `report()
399
404
  that every API heading has a test.
400
405
 
401
406
  CI (Bitbucket Pipelines) runs the suite on Node 24 and 26 for every push, and the stress pass on
402
- `v*` tags.
407
+ `v*` tags. It builds the prebuilt binaries on Debian 12, and `scripts/check-prebuilds.mjs` fails
408
+ the pipeline if they need a newer glibc or libstdc++ than [Requirements](#requirements) names.
403
409
  Pushing a `v*` tag that matches `package.json`'s version publishes to npm.
404
410
 
405
411
  `prototypes/` holds earlier approaches (a V8 patch, an addon with an OS thread per fiber, and a
package/binding.gyp CHANGED
@@ -8,7 +8,7 @@
8
8
  'conditions': [
9
9
  ['OS != "linux" or target_arch != "x64"', {'type': 'none', 'sources': []}],
10
10
  ],
11
- 'cflags': ['-fstack-protector-strong'],
11
+ 'cflags': ['-fstack-protector-strong', '-fcf-protection=none'],
12
12
  'cflags_c': ['-std=gnu11', '-O2'],
13
13
  'cflags_cc': ['-O2', '-Wall', '-Wno-unused-parameter', '-Wno-cast-function-type', '-std=gnu++20'],
14
14
  'ldflags': ['-Wl,-z,relro,-z,now', '-Wl,-z,noexecstack'],
package/dist/index.cjs CHANGED
@@ -45,30 +45,32 @@ const prebuilt = (0, node_path.join)(__dirname, "..", "prebuilds", `${process.pl
45
45
  const binding = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)((0, node_fs.existsSync)(prebuilt) ? prebuilt : (0, node_path.join)(__dirname, "..", "build", "Release", "fibers.node"));
46
46
  Object.defineProperty(globalThis, loadedKey, { value: __filename });
47
47
  // src/guards/jspi.ts
48
- let depth$1 = 0;
49
- const inJspi = () => depth$1 !== 0;
50
- function handOff$2() {
51
- const saved = depth$1;
52
- depth$1 = 0;
53
- return () => {
54
- depth$1 = saved;
55
- };
48
+ const removeJspi = (wasm) => {
49
+ if (wasm && typeof wasm === "object") {
50
+ Reflect.deleteProperty(wasm, "promising");
51
+ Reflect.deleteProperty(wasm, "Suspending");
52
+ }
53
+ };
54
+ removeJspi(globalThis.WebAssembly);
55
+ const runInContext = node_vm.default.Script.prototype.runInContext;
56
+ const createContext = node_vm.default.createContext;
57
+ const getWebAssembly = new node_vm.default.Script("WebAssembly", { filename: "fibers:jspi-guard" });
58
+ const cleaned = new WeakSet();
59
+ function removeJspiFromContext(context) {
60
+ if (typeof context !== "object" || context === null || cleaned.has(context) || !node_vm.default.isContext(context)) return;
61
+ cleaned.add(context);
62
+ removeJspi(Reflect.apply(runInContext, getWebAssembly, [context]));
56
63
  }
57
- const jspiError = () => codedError(new Error("Fiber.await cannot suspend inside JS that WebAssembly calls under JSPI (an import called by a WebAssembly.promising function): V8's stack switching state is shared by all fibers and the process would abort. Await the promise that the promising function returns instead, or make the import a WebAssembly.Suspending."), "ERR_FIBER_AWAIT_IN_JSPI");
58
- const wasm = globalThis.WebAssembly;
59
- const originalPromising = wasm?.promising;
60
- if (wasm && typeof originalPromising === "function") wasm.promising = { promising(...promisingArgs) {
61
- const exported = Reflect.apply(originalPromising, this, promisingArgs);
62
- if (typeof exported !== "function") return exported;
63
- return function promisingCall(...args) {
64
- depth$1++;
65
- try {
66
- return Reflect.apply(exported, this, args);
67
- } finally {
68
- depth$1--;
69
- }
70
- };
71
- } }.promising;
64
+ node_vm.default.createContext = { createContext(...args) {
65
+ const context = Reflect.apply(createContext, node_vm.default, args);
66
+ removeJspiFromContext(context);
67
+ return context;
68
+ } }.createContext;
69
+ node_vm.default.Script.prototype.runInContext = { runInContext(context, ...rest) {
70
+ removeJspiFromContext(context);
71
+ return Reflect.apply(runInContext, this, [context, ...rest]);
72
+ } }.runInContext;
73
+ (0, node_module.syncBuiltinESMExports)();
72
74
  // src/guards/require.ts
73
75
  let loading = [];
74
76
  const away = new Map();
@@ -164,13 +166,11 @@ const NativePromise = (async () => {})().constructor;
164
166
  function handingOff(switchFn) {
165
167
  return (...args) => {
166
168
  const restoreVm = handOff();
167
- const restoreJspi = handOff$2();
168
169
  const restoreRequire = handOff$1();
169
170
  try {
170
171
  switchFn(...args);
171
172
  } finally {
172
173
  restoreVm();
173
- restoreJspi();
174
174
  restoreRequire();
175
175
  }
176
176
  };
@@ -179,9 +179,11 @@ const startFiber = handingOff(binding.start);
179
179
  const resumeFiber = handingOff(binding.resume);
180
180
  function checkCanSuspend(publicFn, checkInFiber) {
181
181
  if (inVm()) throw fromCaller(inVmError(), publicFn);
182
- if (inJspi()) throw fromCaller(jspiError(), publicFn);
183
182
  if (checkInFiber && !binding.inFiber()) throw fromCaller(codedError(new Error(OUTSIDE_FIBER_MESSAGE), "ERR_FIBER_AWAIT_OUTSIDE_FIBER"), publicFn);
184
183
  }
184
+ function waitForTermination() {
185
+ for (;;);
186
+ }
185
187
  const returnedPromiseError = () => codedError(new TypeError("Function argument to Fiber.run should not return a Promise"), "ERR_FIBER_RUN_RETURNED_PROMISE");
186
188
  const isThenable = (value) => value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
187
189
  const ignore = () => {};
@@ -235,7 +237,7 @@ function suspendUntilSettled(value, publicFn) {
235
237
  let result;
236
238
  const restoreRequire = handOff$1();
237
239
  try {
238
- binding.suspend((id, generation) => {
240
+ if (binding.suspend((id, generation) => {
239
241
  promise.then((settled) => {
240
242
  result = settled;
241
243
  resumeFiber(id, generation);
@@ -244,7 +246,7 @@ function suspendUntilSettled(value, publicFn) {
244
246
  result = error;
245
247
  resumeFiber(id, generation);
246
248
  });
247
- });
249
+ })) waitForTermination();
248
250
  } catch (error) {
249
251
  const handler = refusedAwaitHandler;
250
252
  const refusal = fromCaller(error, publicFn);
@@ -263,7 +265,7 @@ function wrap(fn) {
263
265
  return function wrapped(...args) {
264
266
  checkCanSuspend(wrapped, true);
265
267
  try {
266
- binding.checkSuspend();
268
+ if (binding.checkSuspend()) waitForTermination();
267
269
  } catch (error) {
268
270
  throw fromCaller(error, wrapped);
269
271
  }
package/dist/index.d.cts CHANGED
@@ -9,6 +9,8 @@ interface FiberStats {
9
9
  released: number;
10
10
  /** How many finished fibers keep their stack (see setPoolSize). */
11
11
  poolSize: number;
12
+ /** The stack size of fibers in bytes, process-wide (see setStackSize). */
13
+ stackSize: number;
12
14
  /** Control transfers on this JS thread since load. */
13
15
  switches: number;
14
16
  }
@@ -35,16 +37,14 @@ interface FiberApi {
35
37
  * entered (runInAsyncScope, bind, EventEmitterAsyncResource), where
36
38
  * suspending would abort the process; with `code`
37
39
  * `ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE` inside JS run by the inspector
38
- * (Session#post 'Runtime.evaluate', DevTools console); with `code`
39
- * `ERR_FIBER_AWAIT_IN_VM` inside code that vm evaluates; and with `code`
40
- * `ERR_FIBER_AWAIT_IN_JSPI` inside JS that a WebAssembly.promising
41
- * function calls.
40
+ * (Session#post 'Runtime.evaluate', DevTools console); and with `code`
41
+ * `ERR_FIBER_AWAIT_IN_VM` inside code that vm evaluates.
42
42
  */
43
43
  await<T>(value: T | PromiseLike<T>): T;
44
44
  /**
45
45
  * A synchronous version of a promise-returning function, for use inside
46
46
  * fibers: `const readFile = Fiber.wrap(fs.promises.readFile)`. Where
47
- * Fiber.await would throw (outside a fiber, vm, JSPI, async scope, inspector),
47
+ * Fiber.await would throw (outside a fiber, vm, async scope, inspector),
48
48
  * the returned function throws before calling `fn`, with the same `code`
49
49
  * (`ERR_FIBER_AWAIT_OUTSIDE_FIBER` outside a fiber).
50
50
  */
@@ -54,7 +54,7 @@ interface FiberApi {
54
54
  stats(): FiberStats;
55
55
  /**
56
56
  * Stack size of fibers created afterwards, in bytes (default and minimum
57
- * 2 MiB). JS in a fiber can use all of it but the last 1 MiB, which is
57
+ * 2 MiB, maximum 1 GiB). JS in a fiber can use all of it but the last 1 MiB, which is
58
58
  * kept for C++ frames: by default about the main thread's depth. Keep
59
59
  * fibers shallow; --stack-size does not apply to them. Only before the
60
60
  * first Fiber.run in the process (afterwards it throws with `code`
@@ -76,6 +76,10 @@ bool Coroutine::set_stack_size(unsigned int size) {
76
76
  return true;
77
77
  }
78
78
 
79
+ size_t Coroutine::stack_size_bytes() {
80
+ return stack_size * sizeof(void*);
81
+ }
82
+
79
83
  size_t Coroutine::coroutines_created() {
80
84
  return tl.all.size();
81
85
  }
@@ -146,12 +150,17 @@ Coroutine* Coroutine::create_fiber(entry_t* entry, void* arg) {
146
150
  return coro;
147
151
  }
148
152
 
153
+ static void no_huge_pages(coro_stack& stack) {
154
+ (void)madvise(stack.sptr, stack.ssze, MADV_NOHUGEPAGE);
155
+ }
156
+
149
157
  // A new stack, with a context that starts at trampoline().
150
158
  bool Coroutine::allocate_stack() {
151
159
  if (!coro_stack_alloc(&stack, stack_size)) {
152
160
  stack.sptr = NULL;
153
161
  return false;
154
162
  }
163
+ no_huge_pages(stack);
155
164
  start_context();
156
165
  return true;
157
166
  }
@@ -180,6 +189,7 @@ bool Coroutine::reacquire_stack() {
180
189
  if (mprotect(stack.sptr, stack.ssze, PROT_READ | PROT_WRITE) != 0) {
181
190
  return false;
182
191
  }
192
+ no_huge_pages(stack);
183
193
  start_context();
184
194
  return true;
185
195
  }
@@ -80,6 +80,11 @@ class Coroutine {
80
80
  */
81
81
  static bool set_stack_size(unsigned int size);
82
82
 
83
+ /**
84
+ * The stack size of coroutines created by this library, in bytes (process-wide).
85
+ */
86
+ static size_t stack_size_bytes();
87
+
83
88
  /**
84
89
  * Get the number of coroutines that have been created (on this JS thread).
85
90
  */
package/native/fibers.cc CHANGED
@@ -69,6 +69,14 @@ constexpr const char* kOutsideFiberMessage =
69
69
  // bottom plus this, independent of --stack-size.
70
70
  constexpr size_t kCppStackReserve = 1024 * 1024;
71
71
 
72
+ constexpr size_t kCentralStackSize = size_t{1} << 36;
73
+
74
+ void SetFiberStackLimit(Isolate* isolate, uintptr_t limit) {
75
+ void* stack_start = fibers::ExchangeStackStart(reinterpret_cast<void*>(limit + kCentralStackSize));
76
+ isolate->SetStackLimit(limit);
77
+ fibers::ExchangeStackStart(stack_start);
78
+ }
79
+
72
80
  // Set by a fiber that was ended by TerminateExecution (process.exit(), worker.terminate()) for
73
81
  // the coroutine it finishes into, which then re-raises the termination.
74
82
  thread_local bool tl_terminate_pending = false;
@@ -226,7 +234,7 @@ void RunFiber(void* data) {
226
234
  Isolate::Scope isolate_scope(isolate);
227
235
  // Its JS stack limit comes from its own stack. V8 archives and restores it with the rest of
228
236
  // the thread's state at every switch.
229
- isolate->SetStackLimit(reinterpret_cast<uintptr_t>(Coroutine::current().bottom()) + kCppStackReserve);
237
+ SetFiberStackLimit(isolate, reinterpret_cast<uintptr_t>(Coroutine::current().bottom()) + kCppStackReserve);
230
238
  HandleScope scope(isolate);
231
239
  SetCped(isolate, fiber->initial_cped.Get(isolate));
232
240
  fiber->initial_cped.Reset();
@@ -271,6 +279,9 @@ void Start(const FunctionCallbackInfo<Value>& args) {
271
279
  if (args.Length() != 1 || !args[0]->IsFunction()) {
272
280
  THROW(Exception::TypeError, "start() expects a function");
273
281
  }
282
+ if (tl_data == nullptr) {
283
+ THROW(Exception::Error, "fibers: this thread's environment has shut down");
284
+ }
274
285
  Fiber* fiber = new Fiber();
275
286
  fiber->isolate = isolate;
276
287
  fiber->coroutine = Coroutine::create_fiber(RunFiber, fiber);
@@ -309,10 +320,16 @@ void Resume(const FunctionCallbackInfo<Value>& args) {
309
320
  Switch(isolate, fiber);
310
321
  }
311
322
 
323
+ void EndFiber(const FunctionCallbackInfo<Value>& args) {
324
+ args.GetIsolate()->TerminateExecution();
325
+ args.GetReturnValue().Set(true);
326
+ }
327
+
312
328
  /**
313
329
  * suspend(register): suspends the current fiber after calling register(id, generation). Returns
314
- * when resume(id, generation) is called. Creates no objects: Fiber.await calls it a lot. Throws (without suspending) outside a fiber, where suspending is refused, or
315
- * when register throws.
330
+ * when resume(id, generation) is called. Creates no objects: Fiber.await calls it a lot. Throws
331
+ * (without suspending) outside a fiber, where suspending is refused, or when register throws.
332
+ * Returns true when the fiber is being ended instead (see EndFiber), nothing otherwise.
316
333
  */
317
334
  void Suspend(const FunctionCallbackInfo<Value>& args) {
318
335
  Isolate* isolate = args.GetIsolate();
@@ -321,8 +338,7 @@ void Suspend(const FunctionCallbackInfo<Value>& args) {
321
338
  }
322
339
  Fiber& fiber = *tl_data->current;
323
340
  if (fiber.aborting) {
324
- isolate->TerminateExecution();
325
- return;
341
+ return EndFiber(args);
326
342
  } else if (args.Length() != 1 || !args[0]->IsFunction()) {
327
343
  THROW(Exception::TypeError, "suspend() expects a function");
328
344
  } else if (!CheckCanSuspend(fiber)) {
@@ -342,8 +358,7 @@ void Suspend(const FunctionCallbackInfo<Value>& args) {
342
358
  fiber.suspended = false;
343
359
 
344
360
  if (fiber.aborting) {
345
- isolate->TerminateExecution();
346
- return;
361
+ return EndFiber(args);
347
362
  }
348
363
  RecordScopeBase(fiber);
349
364
  }
@@ -351,17 +366,16 @@ void Suspend(const FunctionCallbackInfo<Value>& args) {
351
366
  /**
352
367
  * checkSuspend(): throws what suspend() would throw where suspending is refused, without
353
368
  * suspending. Outside a fiber it does nothing (src/index.ts checks that). Fiber.wrap calls it
354
- * before the wrapped function starts its work.
369
+ * before the wrapped function starts its work. Returns true when the fiber is being ended (see
370
+ * EndFiber), nothing otherwise.
355
371
  */
356
372
  void CheckSuspend(const FunctionCallbackInfo<Value>& args) {
357
- Isolate* isolate = args.GetIsolate();
358
373
  if (tl_data == nullptr || tl_data->current == nullptr) {
359
374
  return;
360
375
  }
361
376
  Fiber& fiber = *tl_data->current;
362
377
  if (fiber.aborting) {
363
- isolate->TerminateExecution();
364
- return;
378
+ return EndFiber(args);
365
379
  }
366
380
  CheckCanSuspend(fiber);
367
381
  }
@@ -431,11 +445,14 @@ void Init(Isolate* isolate) {
431
445
 
432
446
  // --- Configuration and diagnostics -------------------------------------------------------------
433
447
 
448
+ constexpr double kMinStackSize = 2.0 * kCppStackReserve;
449
+ constexpr double kMaxStackSize = 1024.0 * 1024 * 1024;
450
+
434
451
  void SetStackSize(const FunctionCallbackInfo<Value>& args) {
435
452
  Isolate* isolate = args.GetIsolate();
436
453
  double bytes = args[0]->NumberValue(isolate->GetCurrentContext()).FromMaybe(0);
437
- if (!(bytes >= 2 * kCppStackReserve)) {
438
- THROW(Exception::RangeError, "Fiber.setStackSize: must be at least 2 MiB");
454
+ if (!(bytes >= kMinStackSize && bytes <= kMaxStackSize)) {
455
+ THROW(Exception::RangeError, "Fiber.setStackSize: must be between 2 MiB and 1 GiB");
439
456
  }
440
457
  if (!Coroutine::set_stack_size(static_cast<unsigned int>(bytes / sizeof(void*)))) {
441
458
  return ThrowCoded(isolate, "Fiber.setStackSize: call it before the first Fiber.run",
@@ -464,6 +481,7 @@ void Stats(const FunctionCallbackInfo<Value>& args) {
464
481
  set("pooled", static_cast<double>(Coroutine::pooled()));
465
482
  set("released", static_cast<double>(Coroutine::released()));
466
483
  set("poolSize", static_cast<double>(Coroutine::pool_size));
484
+ set("stackSize", static_cast<double>(Coroutine::stack_size_bytes()));
467
485
  set("switches", tl_switches);
468
486
  args.GetReturnValue().Set(out);
469
487
  }
package/native/tls.cc CHANGED
@@ -218,12 +218,17 @@ TlsLayout DiscoverTls() {
218
218
  "needs it to find V8's thread-locals";
219
219
  return out;
220
220
  }
221
+ if (symtab->sh_link >= sh.size()) {
222
+ out.error = ".symtab has no string table";
223
+ return out;
224
+ }
221
225
  const Elf64_Shdr& strtab = sh[symtab->sh_link];
222
226
  std::vector<char> strings(strtab.sh_size);
223
227
  if (!PRead(fd, strings.data(), strings.size(), strtab.sh_offset)) {
224
228
  out.error = "cannot read .strtab";
225
229
  return out;
226
230
  }
231
+ strings.push_back('\0');
227
232
  size_t count = symtab->sh_size / sizeof(Elf64_Sym);
228
233
  // Read in chunks: .symtab of node is ~10-20 MB.
229
234
  const size_t kChunk = 65536;
@@ -301,6 +306,7 @@ std::vector<SwapSlot> g_swap;
301
306
  std::vector<CheckSlot> g_must_be_zero; // checked before every switch
302
307
  std::vector<CheckSlot> g_enter_managed; // checked after a full Exit
303
308
  intptr_t g_current_isolate_offset = 0;
309
+ intptr_t g_stack_start_offset = 0;
304
310
  uint8_t g_assert_data_initial[8];
305
311
  bool g_skip_checks = false; // FIBERS_NO_CHECKS=1 (diagnostics only)
306
312
  std::string g_layout_report;
@@ -376,7 +382,7 @@ std::string SetUpLayout() {
376
382
  return;
377
383
  }
378
384
  size_t image_off = 0;
379
- bool have_isolate = false, have_tid = false, have_stack = false;
385
+ int isolates = 0, tids = 0, stacks = 0, assert_datas = 0;
380
386
  for (const TlsVar& v : layout.vars) {
381
387
  // Expected sizes, so that a type change in V8 is noticed.
382
388
  size_t want = v.role == TlsRole::kThreadId ? 4
@@ -394,12 +400,14 @@ std::string SetUpLayout() {
394
400
  }
395
401
  if (v.role == TlsRole::kCurrentIsolate) {
396
402
  g_current_isolate_offset = v.tp_offset;
397
- have_isolate = true;
403
+ isolates++;
398
404
  }
399
- if (v.role == TlsRole::kThreadId) {
400
- have_tid = true;
405
+ if (v.role == TlsRole::kThreadId) tids++;
406
+ if (v.role == TlsRole::kStackStart) {
407
+ g_stack_start_offset = v.tp_offset;
408
+ stacks++;
401
409
  }
402
- if (v.role == TlsRole::kStackStart) have_stack = true;
410
+ if (v.role == TlsRole::kAssertData) assert_datas++;
403
411
  switch (v.cls) {
404
412
  case TlsClass::kSwap:
405
413
  if (image_off + v.size > kTlsImageSize) {
@@ -422,11 +430,17 @@ std::string SetUpLayout() {
422
430
  break;
423
431
  }
424
432
  }
425
- if (!have_isolate || !have_tid || !have_stack) {
433
+ if (isolates == 0 || tids == 0 || stacks == 0) {
426
434
  error = "g_current_isolate_, thread_id or thread_stack_start not found "
427
435
  "in the node executable's .symtab";
428
436
  return;
429
437
  }
438
+ if (isolates > 1 || tids > 1 || stacks > 1 || assert_datas > 1) {
439
+ error = "more than one thread-local named g_current_isolate_, "
440
+ "thread_id, thread_stack_start or "
441
+ "current_per_thread_assert_data in the node executable";
442
+ return;
443
+ }
430
444
  });
431
445
  return error;
432
446
  }
@@ -488,6 +502,14 @@ void SetTlsStackStart(TlsImage* image, void* stack_top) {
488
502
  }
489
503
  }
490
504
 
505
+ void* ExchangeStackStart(void* stack_start) {
506
+ char* slot = ThreadPointer() + g_stack_start_offset;
507
+ void* previous;
508
+ memcpy(&previous, slot, sizeof previous);
509
+ memcpy(slot, &stack_start, sizeof stack_start);
510
+ return previous;
511
+ }
512
+
491
513
  void CheckTlsBeforeSwitch() { CheckBeforeSwitchImpl(); }
492
514
  void CheckTlsAfterExit() { CheckAfterExitImpl(); }
493
515
 
package/native/tls.h CHANGED
@@ -85,6 +85,7 @@ void InitTls(TlsImage* image, void* stack_top);
85
85
  // A coroutine that got a new stack keeps its V8 thread id (and the rest of the
86
86
  // image); only its stack start moves to the new stack's top.
87
87
  void SetTlsStackStart(TlsImage* image, void* stack_top);
88
+ void* ExchangeStackStart(void* stack_start);
88
89
  // Fatal if a "must be zero" variable is set (a compiler / GC / wasm scope
89
90
  // that can't move between fibers); call before every switch.
90
91
  void CheckTlsBeforeSwitch();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrwinston/fibers",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Fibers for stock Node.js 24/26 on x64 Linux: node-fibers' native core (libcoro, one OS thread) with a promise-based API (Fiber.run / Fiber.await)",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -32,12 +32,6 @@
32
32
  "test": "node --expose-gc --test \"test/*.test.mjs\"",
33
33
  "test:stress": "node scripts/test-stress.mjs"
34
34
  },
35
- "os": [
36
- "linux"
37
- ],
38
- "cpu": [
39
- "x64"
40
- ],
41
35
  "engines": {
42
36
  "node": ">=24"
43
37
  },
@@ -10,10 +10,10 @@ const supported = ["linux-x64"];
10
10
  const target = `${process.platform}-${process.arch}`;
11
11
 
12
12
  if (!supported.includes(target)) {
13
- console.error(
14
- `fibers: only ${supported.join(" and ")} is supported (got ${target})`,
13
+ console.log(
14
+ `fibers: ${target} is not supported (only ${supported.join(" and ")}); nothing was built, and importing the package will throw`,
15
15
  );
16
- process.exit(1);
16
+ process.exit(0);
17
17
  }
18
18
 
19
19
  const prebuilt = path.join(