@mrwinston/fibers 0.0.0-stage → 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/dist/index.cjs ADDED
@@ -0,0 +1,286 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ let node_worker_threads = require("node:worker_threads");
24
+ let node_fs = require("node:fs");
25
+ let node_module = require("node:module");
26
+ let node_path = require("node:path");
27
+ let node_vm = require("node:vm");
28
+ node_module = __toESM(node_module, 1);
29
+ node_vm = __toESM(node_vm, 1);
30
+ // src/errors.ts
31
+ function fromCaller(error, publicFn) {
32
+ if (error !== null && typeof error === "object") Error.captureStackTrace(error, publicFn);
33
+ return error;
34
+ }
35
+ function codedError(error, code) {
36
+ return Object.assign(error, { code });
37
+ }
38
+ const OUTSIDE_FIBER_MESSAGE = "Fiber.await and Fiber.wrap'd functions can only be called inside Fiber.run";
39
+ // src/binding.ts
40
+ const loadedKey = Symbol.for("fibers.loaded");
41
+ const loadedFrom = globalThis[loadedKey];
42
+ if (loadedFrom !== void 0) throw codedError(new Error(`fibers is already loaded from ${String(loadedFrom)}; a second copy (${__filename}) in the same process is not supported. Make sure only one copy is installed (npm ls @mrwinston/fibers).`), "ERR_FIBER_ALREADY_LOADED");
43
+ if (process.platform !== "linux" || process.arch !== "x64") throw codedError(new Error(`fibers supports x64 Linux only (this is ${process.platform}-${process.arch})`), "ERR_FIBER_UNSUPPORTED_PLATFORM");
44
+ const prebuilt = (0, node_path.join)(__dirname, "..", "prebuilds", `${process.platform}-${process.arch}`, `node-${process.versions.modules}`, "fibers.node");
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
+ Object.defineProperty(globalThis, loadedKey, { value: __filename });
47
+ // src/guards/jspi.ts
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]));
63
+ }
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)();
74
+ // src/guards/require.ts
75
+ let loading = [];
76
+ const away = new Map();
77
+ function markAway(filenames, delta) {
78
+ for (const filename of filenames) {
79
+ const count = (away.get(filename) ?? 0) + delta;
80
+ if (count === 0) away.delete(filename);
81
+ else away.set(filename, count);
82
+ }
83
+ }
84
+ function handOff$1() {
85
+ const saved = loading;
86
+ loading = [];
87
+ if (saved.length !== 0) markAway(saved, 1);
88
+ return () => {
89
+ loading = saved;
90
+ if (saved.length !== 0) markAway(saved, -1);
91
+ };
92
+ }
93
+ const requireInProgressError = (filename) => codedError(new Error(`require() of ${filename}, which another fiber (or the root) is still evaluating: it would get the module's partial exports. The fiber that loads it waits in its top level (Fiber.await) or started this fiber from there. Require it before the fibers that use it start, or wait for the other fiber (Fiber.await its Fiber.run promise).`), "ERR_FIBER_REQUIRE_IN_PROGRESS");
94
+ function fromRequireCaller(error) {
95
+ Error.captureStackTrace(error, moduleInternals._load);
96
+ const lines = String(error.stack).split("\n");
97
+ const firstFrame = lines.findIndex((line) => line.startsWith(" at "));
98
+ let userFrame = firstFrame;
99
+ while (userFrame >= 0 && userFrame < lines.length && /\(node:internal\/|at node:internal\//.test(lines[userFrame] ?? "")) userFrame++;
100
+ if (firstFrame >= 0 && userFrame < lines.length) {
101
+ lines.splice(firstFrame, userFrame - firstFrame);
102
+ error.stack = lines.join("\n");
103
+ }
104
+ return error;
105
+ }
106
+ const moduleInternals = node_module.default;
107
+ const originalLoad = moduleInternals.prototype.load;
108
+ const originalModuleLoad = moduleInternals._load;
109
+ if (typeof originalLoad === "function" && typeof originalModuleLoad === "function") {
110
+ moduleInternals.prototype.load = function load(filename) {
111
+ const list = loading;
112
+ list.push(filename);
113
+ try {
114
+ return Reflect.apply(originalLoad, this, [filename]);
115
+ } finally {
116
+ list.pop();
117
+ }
118
+ };
119
+ moduleInternals._load = function _load(request, parent, isMain) {
120
+ if (away.size !== 0) {
121
+ let filename;
122
+ try {
123
+ filename = moduleInternals._resolveFilename(request, parent, isMain);
124
+ } catch {}
125
+ if (filename !== void 0 && away.has(filename)) throw fromRequireCaller(requireInProgressError(filename));
126
+ }
127
+ return Reflect.apply(originalModuleLoad, this, [
128
+ request,
129
+ parent,
130
+ isMain
131
+ ]);
132
+ };
133
+ }
134
+ // src/guards/vm.ts
135
+ let depth = 0;
136
+ const inVm = () => depth !== 0;
137
+ function handOff() {
138
+ const saved = depth;
139
+ depth = 0;
140
+ return () => {
141
+ depth = saved;
142
+ };
143
+ }
144
+ const inVmError = () => codedError(new Error("Fiber.await cannot suspend inside code run by vm (vm.runIn*Context, vm.Script#runIn*Context, vm.SourceTextModule#evaluate): a fiber may not await across a vm boundary. Await before or after the vm call, or start a fiber inside the vm code (Fiber.run) and let that one await."), "ERR_FIBER_AWAIT_IN_VM");
145
+ function countCalls(prototype, name) {
146
+ const descriptor = prototype && Object.getOwnPropertyDescriptor(prototype, name);
147
+ const original = descriptor?.value;
148
+ if (!prototype || typeof original !== "function") return;
149
+ Object.defineProperty(prototype, name, {
150
+ ...descriptor,
151
+ value: { [name](...args) {
152
+ depth++;
153
+ try {
154
+ return Reflect.apply(original, this, args);
155
+ } finally {
156
+ depth--;
157
+ }
158
+ } }[name]
159
+ });
160
+ }
161
+ countCalls(node_vm.default.Script.prototype, "runInContext");
162
+ countCalls(node_vm.default.Script.prototype, "runInThisContext");
163
+ countCalls(node_vm.default.Module?.prototype, "evaluate");
164
+ // src/index.ts
165
+ const NativePromise = (async () => {})().constructor;
166
+ function handingOff(switchFn) {
167
+ return (...args) => {
168
+ const restoreVm = handOff();
169
+ const restoreRequire = handOff$1();
170
+ try {
171
+ switchFn(...args);
172
+ } finally {
173
+ restoreVm();
174
+ restoreRequire();
175
+ }
176
+ };
177
+ }
178
+ const startFiber = handingOff(binding.start);
179
+ const resumeFiber = handingOff(binding.resume);
180
+ function checkCanSuspend(publicFn, checkInFiber) {
181
+ if (inVm()) throw fromCaller(inVmError(), publicFn);
182
+ if (checkInFiber && !binding.inFiber()) throw fromCaller(codedError(new Error(OUTSIDE_FIBER_MESSAGE), "ERR_FIBER_AWAIT_OUTSIDE_FIBER"), publicFn);
183
+ }
184
+ function waitForTermination() {
185
+ for (;;);
186
+ }
187
+ const returnedPromiseError = () => codedError(new TypeError("Function argument to Fiber.run should not return a Promise"), "ERR_FIBER_RUN_RETURNED_PROMISE");
188
+ const isThenable = (value) => value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
189
+ const ignore = () => {};
190
+ let refusedAwaitHandler = ignore;
191
+ function setRefusedAwaitHandler(handler) {
192
+ if (handler !== void 0 && typeof handler !== "function") throw fromCaller(new TypeError("Fiber.setRefusedAwaitHandler expects a function or undefined"), setRefusedAwaitHandler);
193
+ refusedAwaitHandler = handler ?? ignore;
194
+ }
195
+ async function run(fn) {
196
+ if (typeof fn !== "function") throw fromCaller(new TypeError("Fiber.run expects a function"), run);
197
+ if (fn.constructor.name === "AsyncFunction") throw fromCaller(returnedPromiseError(), run);
198
+ const { promise, resolve, reject } = NativePromise.withResolvers();
199
+ let returnedPromise = false;
200
+ try {
201
+ startFiber(() => {
202
+ try {
203
+ const result = fn();
204
+ returnedPromise = isThenable(result);
205
+ if (returnedPromise) {
206
+ const handler = refusedAwaitHandler;
207
+ const refusal = fromCaller(returnedPromiseError(), run);
208
+ result.then(void 0, (reason) => handler(reason, refusal));
209
+ }
210
+ resolve(returnedPromise ? void 0 : result);
211
+ } catch (error) {
212
+ reject(error);
213
+ }
214
+ });
215
+ } catch (error) {
216
+ throw fromCaller(error, run);
217
+ }
218
+ const result = returnedPromise ? void 0 : await promise;
219
+ if (returnedPromise) throw fromCaller(returnedPromiseError(), run);
220
+ return result;
221
+ }
222
+ const poolSizeKey = "@mrwinston/fibers:poolSize";
223
+ const inheritedPoolSize = (0, node_worker_threads.getEnvironmentData)(poolSizeKey);
224
+ if (typeof inheritedPoolSize === "number") binding.setPoolSize(inheritedPoolSize);
225
+ function setPoolSize(count) {
226
+ try {
227
+ binding.setPoolSize(count);
228
+ } catch (error) {
229
+ throw fromCaller(error, setPoolSize);
230
+ }
231
+ (0, node_worker_threads.setEnvironmentData)(poolSizeKey, binding.stats().poolSize);
232
+ }
233
+ function suspendUntilSettled(value, publicFn) {
234
+ checkCanSuspend(publicFn, false);
235
+ const promise = NativePromise.resolve(value);
236
+ let failed = false;
237
+ let result;
238
+ const restoreRequire = handOff$1();
239
+ try {
240
+ if (binding.suspend((id, generation) => {
241
+ promise.then((settled) => {
242
+ result = settled;
243
+ resumeFiber(id, generation);
244
+ }, (error) => {
245
+ failed = true;
246
+ result = error;
247
+ resumeFiber(id, generation);
248
+ });
249
+ })) waitForTermination();
250
+ } catch (error) {
251
+ const handler = refusedAwaitHandler;
252
+ const refusal = fromCaller(error, publicFn);
253
+ promise.then(void 0, (reason) => handler(reason, refusal));
254
+ throw refusal;
255
+ } finally {
256
+ restoreRequire();
257
+ }
258
+ if (failed) throw result;
259
+ return result;
260
+ }
261
+ function awaitValue(value) {
262
+ return suspendUntilSettled(value, awaitValue);
263
+ }
264
+ function wrap(fn) {
265
+ return function wrapped(...args) {
266
+ checkCanSuspend(wrapped, true);
267
+ try {
268
+ if (binding.checkSuspend()) waitForTermination();
269
+ } catch (error) {
270
+ throw fromCaller(error, wrapped);
271
+ }
272
+ return suspendUntilSettled(fn.apply(this, args), wrapped);
273
+ };
274
+ }
275
+ const Fiber = {
276
+ run,
277
+ wrap,
278
+ await: awaitValue,
279
+ inFiber: binding.inFiber,
280
+ stats: binding.stats,
281
+ setStackSize: binding.setStackSize,
282
+ setPoolSize,
283
+ setRefusedAwaitHandler,
284
+ _tlsLayout: binding.tlsLayout
285
+ };
286
+ exports.Fiber = Fiber;
@@ -0,0 +1,81 @@
1
+ interface FiberStats {
2
+ /** Fibers started and not finished yet. */
3
+ live: number;
4
+ /** Fibers created on this JS thread (each keeps its V8 thread id for reuse). */
5
+ fibersCreated: number;
6
+ /** Finished fibers waiting for reuse that kept their stack (at most poolSize). */
7
+ pooled: number;
8
+ /** Finished fibers waiting for reuse whose stack memory was released (beyond poolSize). */
9
+ released: number;
10
+ /** How many finished fibers keep their stack (see setPoolSize). */
11
+ poolSize: number;
12
+ /** The stack size of fibers in bytes, process-wide (see setStackSize). */
13
+ stackSize: number;
14
+ /** Control transfers on this JS thread since load. */
15
+ switches: number;
16
+ }
17
+ /**
18
+ * Gets the rejection of a promise whose Fiber.await was refused, and the error that refusal
19
+ * threw. What it throws (or a promise it returns that rejects) is an unhandled rejection.
20
+ */
21
+ type RefusedAwaitHandler = (reason: unknown, refusal: unknown) => unknown;
22
+ interface FiberApi {
23
+ /**
24
+ * Run `fn` in a new fiber. `fn` runs synchronously until its first
25
+ * Fiber.await; the promise resolves with its return value or rejects with
26
+ * what it throws. `fn` must not return a promise (rejects with code
27
+ * `ERR_FIBER_RUN_RETURNED_PROMISE`). Rejects with a RangeError with code
28
+ * `ERR_FIBER_STACK_ALLOC` if no fiber stack can be allocated.
29
+ */
30
+ run<T>(fn: () => T): Promise<T>;
31
+ /**
32
+ * Suspend the current fiber (not the thread) until `value` settles and
33
+ * return its value, or throw its rejection. Other fibers and the event loop
34
+ * keep running. Throws with `code` `ERR_FIBER_AWAIT_OUTSIDE_FIBER` outside
35
+ * a fiber; with `code`
36
+ * `ERR_FIBER_AWAIT_IN_ASYNC_SCOPE` inside an AsyncResource scope the fiber
37
+ * entered (runInAsyncScope, bind, EventEmitterAsyncResource), where
38
+ * suspending would abort the process; with `code`
39
+ * `ERR_FIBER_AWAIT_IN_MICROTASKS_SCOPE` inside JS run by the inspector
40
+ * (Session#post 'Runtime.evaluate', DevTools console); and with `code`
41
+ * `ERR_FIBER_AWAIT_IN_VM` inside code that vm evaluates.
42
+ */
43
+ await<T>(value: T | PromiseLike<T>): T;
44
+ /**
45
+ * A synchronous version of a promise-returning function, for use inside
46
+ * fibers: `const readFile = Fiber.wrap(fs.promises.readFile)`. Where
47
+ * Fiber.await would throw (outside a fiber, vm, async scope, inspector),
48
+ * the returned function throws before calling `fn`, with the same `code`
49
+ * (`ERR_FIBER_AWAIT_OUTSIDE_FIBER` outside a fiber).
50
+ */
51
+ wrap<A extends unknown[], R>(fn: (...args: A) => R | PromiseLike<R>): (...args: A) => R;
52
+ /** Whether the caller is running inside a fiber. */
53
+ inFiber(): boolean;
54
+ stats(): FiberStats;
55
+ /**
56
+ * Stack size of fibers created afterwards, in bytes (default and minimum
57
+ * 2 MiB, maximum 1 GiB). JS in a fiber can use all of it but the last 1 MiB, which is
58
+ * kept for C++ frames: by default about the main thread's depth. Keep
59
+ * fibers shallow; --stack-size does not apply to them. Only before the
60
+ * first Fiber.run in the process (afterwards it throws with `code`
61
+ * `ERR_FIBER_STACK_SIZE_LOCKED`).
62
+ */
63
+ setStackSize(bytes: number): void;
64
+ /**
65
+ * How many finished fibers keep their stack memory for reuse (default 120); the others
66
+ * release its pages. Per JS thread; a worker starts with the value of the thread that created
67
+ * it.
68
+ */
69
+ setPoolSize(count: number): void;
70
+ /**
71
+ * Where Fiber.await is refused (it throws without suspending), nobody waits for its promise.
72
+ * If that promise later rejects, `handler(reason, refusal)` gets the rejection and the error
73
+ * the refusal threw. Default (also with `undefined`): the rejection is ignored, so it can't
74
+ * end the process as an unhandled rejection.
75
+ */
76
+ setRefusedAwaitHandler(handler?: RefusedAwaitHandler): void;
77
+ /** Internal, for debugging: how this node binary's thread-local variables are handled. */
78
+ _tlsLayout(): string;
79
+ }
80
+ export declare const Fiber: FiberApi;
81
+ export type { FiberApi, FiberStats, RefusedAwaitHandler };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./index.cjs";
@@ -0,0 +1,251 @@
1
+ // See coroutine.h. Derived from node-fibers' src/coroutine.cc (laverdet/node-fibers, MIT).
2
+ //
3
+ // - transfer() saves and loads V8's thread-locals (tls.cc) around the libcoro switch.
4
+ // - State is per JS thread (thread_local), so fibers work in workers.
5
+ // - coro_create is serialized: libcoro passes its arguments to the new stack through
6
+ // process-wide statics.
7
+ // - Finished coroutines are never deleted: each keeps the V8 thread id it got the first time
8
+ // (the last transfer of finish() saves it in fls_data), so V8's thread ids are reused. V8
9
+ // hands them out from a process-wide counter and dies after 2^31; reusing them bounds the
10
+ // number by the peak number of live fibers.
11
+ // - Up to pool_size finished coroutines keep their stack (parked in finish(), resumed there when
12
+ // reused). Beyond that, a finished coroutine releases its stack's pages: they are replaced by
13
+ // an inaccessible, uncommitted mapping at the same address (memory and commit charge go back;
14
+ // address space and the mapping stay). Reused, it makes the range writable again and starts
15
+ // from trampoline(). A coroutine's stack never moves, so V8's data for its thread id (the
16
+ // stack limit that StackGuard stored, PerIsolateThreadData) stays valid and is never
17
+ // discarded: DiscardThreadSpecificMetadata would leave V8's CpuSampler with a dangling
18
+ // pointer to it.
19
+ #include "coroutine.h"
20
+ #include <assert.h>
21
+ #include <sys/mman.h>
22
+
23
+ #include <atomic>
24
+ #include <mutex>
25
+ #include <vector>
26
+ using namespace std;
27
+
28
+ namespace {
29
+ struct ThreadState {
30
+ Coroutine* current = NULL;
31
+ vector<Coroutine*> fiber_pool; // finished, with a stack (parked in finish())
32
+ vector<Coroutine*> released; // finished, stack pages released (same address)
33
+ vector<Coroutine*> all; // every coroutine created on this thread (freed at shutdown)
34
+ Coroutine* release_me = NULL;
35
+ };
36
+ thread_local ThreadState tl;
37
+
38
+ // In sizeof(void*). 2 MiB: 1 MiB for JS (about the main thread's default depth), 1 MiB kept for
39
+ // C++ frames (see RunFiber in fibers.cc).
40
+ size_t stack_size = 2 * 1024 * 1024 / sizeof(void*);
41
+ std::mutex coro_create_mutex;
42
+ std::atomic<bool> any_created{false};
43
+ }
44
+
45
+ thread_local size_t Coroutine::pool_size = 120;
46
+
47
+ /**
48
+ * Coroutine class definition
49
+ */
50
+ std::string Coroutine::init(v8::Isolate* isolate) {
51
+ return fibers::InitTls(isolate);
52
+ }
53
+
54
+ void Coroutine::shutdown() {
55
+ for (Coroutine* coro : tl.all) {
56
+ delete coro;
57
+ }
58
+ tl.all.clear();
59
+ tl.fiber_pool.clear();
60
+ tl.released.clear();
61
+ tl.release_me = NULL;
62
+ }
63
+
64
+ Coroutine& Coroutine::current() {
65
+ if (!tl.current) {
66
+ tl.current = new Coroutine;
67
+ }
68
+ return *tl.current;
69
+ }
70
+
71
+ bool Coroutine::set_stack_size(unsigned int size) {
72
+ if (any_created.load()) {
73
+ return false;
74
+ }
75
+ stack_size = size;
76
+ return true;
77
+ }
78
+
79
+ size_t Coroutine::stack_size_bytes() {
80
+ return stack_size * sizeof(void*);
81
+ }
82
+
83
+ size_t Coroutine::coroutines_created() {
84
+ return tl.all.size();
85
+ }
86
+
87
+ size_t Coroutine::pooled() {
88
+ return tl.fiber_pool.size();
89
+ }
90
+
91
+ size_t Coroutine::released() {
92
+ return tl.released.size();
93
+ }
94
+
95
+ bool Coroutine::finishing_releases_stack() {
96
+ return tl.fiber_pool.size() >= pool_size;
97
+ }
98
+
99
+ void Coroutine::trampoline(void* that) {
100
+ while (true) {
101
+ static_cast<Coroutine*>(that)->entry(const_cast<void*>(static_cast<Coroutine*>(that)->arg));
102
+ }
103
+ }
104
+
105
+ Coroutine::Coroutine() :
106
+ entry(NULL),
107
+ arg(NULL) {
108
+ stack.sptr = NULL;
109
+ coro_create(&context, NULL, NULL, NULL, 0);
110
+ }
111
+
112
+ Coroutine::Coroutine(entry_t& entry, void* arg) :
113
+ entry(entry),
114
+ arg(arg) {
115
+ stack.sptr = NULL;
116
+ }
117
+
118
+ Coroutine::~Coroutine() {
119
+ if (stack.sptr) {
120
+ coro_stack_free(&stack);
121
+ }
122
+ (void)coro_destroy(&context);
123
+ }
124
+
125
+ Coroutine* Coroutine::create_fiber(entry_t* entry, void* arg) {
126
+ if (!tl.fiber_pool.empty()) {
127
+ Coroutine* fiber = tl.fiber_pool.back();
128
+ tl.fiber_pool.pop_back();
129
+ fiber->reset(entry, arg);
130
+ return fiber;
131
+ }
132
+ if (!tl.released.empty()) {
133
+ // Keeps its V8 thread id and its stack's address; starts from the trampoline.
134
+ Coroutine* fiber = tl.released.back();
135
+ if (!fiber->reacquire_stack()) {
136
+ return NULL;
137
+ }
138
+ tl.released.pop_back();
139
+ fiber->reset(entry, arg);
140
+ return fiber;
141
+ }
142
+ any_created.store(true);
143
+ Coroutine* coro = new Coroutine(*entry, arg);
144
+ if (!coro->allocate_stack()) {
145
+ delete coro;
146
+ return NULL;
147
+ }
148
+ fibers::InitTls(&coro->fls_data, coro->top());
149
+ tl.all.push_back(coro);
150
+ return coro;
151
+ }
152
+
153
+ static void no_huge_pages(coro_stack& stack) {
154
+ (void)madvise(stack.sptr, stack.ssze, MADV_NOHUGEPAGE);
155
+ }
156
+
157
+ // A new stack, with a context that starts at trampoline().
158
+ bool Coroutine::allocate_stack() {
159
+ if (!coro_stack_alloc(&stack, stack_size)) {
160
+ stack.sptr = NULL;
161
+ return false;
162
+ }
163
+ no_huge_pages(stack);
164
+ start_context();
165
+ return true;
166
+ }
167
+
168
+ void Coroutine::start_context() {
169
+ std::lock_guard<std::mutex> lock(coro_create_mutex);
170
+ coro_create(&context, trampoline, this, stack.sptr, stack.ssze);
171
+ }
172
+
173
+ // Gives the pages of a finished coroutine's stack (not the current one) back to the OS: a fresh
174
+ // inaccessible mapping replaces them, which also drops the commit charge. The guard pages below
175
+ // are inaccessible too, so the kernel can merge both into one mapping. On failure the pages stay:
176
+ // the stack is still usable, it just keeps its memory.
177
+ void Coroutine::release_stack() {
178
+ void* p = mmap(stack.sptr, stack.ssze, PROT_NONE,
179
+ MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED | MAP_NORESERVE, -1, 0);
180
+ if (p == MAP_FAILED) {
181
+ (void)madvise(stack.sptr, stack.ssze, MADV_DONTNEED);
182
+ }
183
+ }
184
+
185
+ // Makes a released stack usable again (zero-filled pages, faulted in as they are touched) and
186
+ // restarts its context at trampoline(). Fails (stack stays released) when the kernel refuses:
187
+ // commit limit, or vm.max_map_count, since the range splits off the guard again.
188
+ bool Coroutine::reacquire_stack() {
189
+ if (mprotect(stack.sptr, stack.ssze, PROT_READ | PROT_WRITE) != 0) {
190
+ return false;
191
+ }
192
+ no_huge_pages(stack);
193
+ start_context();
194
+ return true;
195
+ }
196
+
197
+ void Coroutine::reset(entry_t* entry, void* arg) {
198
+ assert(entry != NULL);
199
+ this->entry = entry;
200
+ this->arg = arg;
201
+ }
202
+
203
+ void Coroutine::transfer(Coroutine& next) {
204
+ assert(this != &next);
205
+ fibers::CheckTlsBeforeSwitch();
206
+ fibers::SaveTls(&fls_data);
207
+ fibers::LoadTls(&next.fls_data);
208
+ tl.current = &next;
209
+ coro_transfer(&context, &next.context);
210
+ tl.current = this;
211
+ }
212
+
213
+ void Coroutine::run() {
214
+ Coroutine& current = Coroutine::current();
215
+ assert(!tl.release_me);
216
+ assert(&current != this);
217
+ current.transfer(*this);
218
+
219
+ if (tl.release_me) {
220
+ // A coroutine finished beyond the pool size: release its stack's pages. Not from inside
221
+ // finish(), which runs on that stack.
222
+ Coroutine* coro = tl.release_me;
223
+ tl.release_me = NULL;
224
+ coro->release_stack();
225
+ }
226
+ }
227
+
228
+ void Coroutine::finish(Coroutine& next, bool release_stack) {
229
+ {
230
+ assert(&next != this);
231
+ assert(&current() == this);
232
+ if (release_stack) {
233
+ assert(tl.release_me == NULL);
234
+ tl.released.push_back(this);
235
+ tl.release_me = this;
236
+ } else {
237
+ tl.fiber_pool.push_back(this);
238
+ }
239
+ }
240
+ this->transfer(next);
241
+ // Reused with its stack: continues in trampoline(), which calls entry again. (After its pages
242
+ // were released it never comes back here: reacquire_stack() restarts it at trampoline().)
243
+ }
244
+
245
+ void* Coroutine::bottom() const {
246
+ return stack.sptr;
247
+ }
248
+
249
+ void* Coroutine::top() const {
250
+ return static_cast<char*>(stack.sptr) + stack.ssze;
251
+ }