@mrwinston/fibers 0.0.0-stage → 0.1.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/native/tls.cc ADDED
@@ -0,0 +1,494 @@
1
+ // See tls.h.
2
+ #include "tls.h"
3
+
4
+ #include <cxxabi.h>
5
+ #include <elf.h>
6
+ #include <fcntl.h>
7
+ #include <link.h>
8
+ #include <unistd.h>
9
+
10
+ #include <cstdio>
11
+ #include <cstdlib>
12
+ #include <cstring>
13
+ #include <memory>
14
+ #include <mutex>
15
+
16
+ namespace fibers {
17
+
18
+ namespace {
19
+
20
+ struct Rule {
21
+ const char* name; // demangled; a trailing '*' means prefix match
22
+ TlsClass cls;
23
+ TlsRole role;
24
+ const char* why;
25
+ bool added_for_node26 = false; // documentation: first seen in Node 26
26
+ };
27
+
28
+ // Every TLS symbol of the executable must match one rule, else loading is
29
+ // refused. Evidence for each class: V8 13.6.233.17 (Node 24) and 14.6
30
+ // (Node 26) sources, cited in each rule below.
31
+ const Rule kRules[] = {
32
+ // --- V8: the identity of the "thread" (swap) ---------------------------
33
+ {"v8::internal::(anonymous namespace)::thread_id", TlsClass::kSwap,
34
+ TlsRole::kThreadId,
35
+ "ThreadId::Current(): Locker/ThreadManager ownership, archived thread "
36
+ "state and PerIsolateThreadData are keyed by it; 0 = assign a new id"},
37
+ {"v8::base::(anonymous namespace)::thread_stack_start", TlsClass::kSwap,
38
+ TlsRole::kStackStart,
39
+ "base::Stack::GetStackStart() cache: StackGuard JS limit for a new "
40
+ "thread, heap::base::Stack start (cppgc conservative stack scan) set by "
41
+ "Isolate::Enter, wasm central-stack view"},
42
+ {"v8::internal::(anonymous namespace)::current_per_thread_assert_data",
43
+ TlsClass::kSwap, TlsRole::kAssertData,
44
+ "PerThreadAssertScope bits (Disallow/AllowHeapAllocation, ...): scoped "
45
+ "per stack"},
46
+ {"v8::internal::wasm::(anonymous namespace)::current_code_refs_scope",
47
+ TlsClass::kSwap, TlsRole::kNone,
48
+ "WasmCodeRefScope chain: linked list of scopes on the current stack"},
49
+ // --- V8: set by Isolate::Enter / Exit (SetIsolateThreadLocals) ---------
50
+ {"v8::internal::g_current_isolate_", TlsClass::kEnterManaged,
51
+ TlsRole::kCurrentIsolate, "Isolate::SetIsolateThreadLocals"},
52
+ {"v8::internal::g_current_per_isolate_thread_data_",
53
+ TlsClass::kEnterManaged, TlsRole::kNone,
54
+ "Isolate::SetIsolateThreadLocals"},
55
+ {"v8::internal::(anonymous namespace)::current_marking_barrier",
56
+ TlsClass::kEnterManaged, TlsRole::kNone,
57
+ "WriteBarrier::SetForThread from SetIsolateThreadLocals"},
58
+ // --- V8: must be empty at a switch -------------------------------------
59
+ {"v8::internal::g_current_local_heap_", TlsClass::kEnterManaged,
60
+ TlsRole::kNone,
61
+ "V8 13.6: only background LocalHeaps set it (null on the JS thread); "
62
+ "V8 14.6: also SetIsolateThreadLocals (main thread LocalHeap). Null "
63
+ "after a full Exit in both"},
64
+ {"v8::internal::(anonymous namespace)::pending_layout_change_object_address",
65
+ TlsClass::kMustBeZero, TlsRole::kNone,
66
+ "between NotifyObjectLayoutChange and the end of the change, no JS"},
67
+ {"v8::internal::trap_handler::g_thread_in_wasm_code", TlsClass::kMustBeZero,
68
+ TlsRole::kNone, "set only while wasm code runs; we are in C++"},
69
+ {"v8::internal::trap_handler::TrapHandlerGuard::is_active_",
70
+ TlsClass::kMustBeZero, TlsRole::kNone,
71
+ "set only inside the trap handler (signal handler)", true},
72
+ {"v8::internal::(anonymous namespace)::tls_singleton_taken",
73
+ TlsClass::kMustBeZero, TlsRole::kNone,
74
+ "assembler buffer in use (code generation), no JS"},
75
+ {"v8::internal::(anonymous namespace)::tls_singleton_storage",
76
+ TlsClass::kLeave, TlsRole::kNone, "buffer, guarded by tls_singleton_taken"},
77
+ {"v8::base::ContextualVariable<v8::internal::compiler::turboshaft::*",
78
+ TlsClass::kMustBeZero, TlsRole::kNone,
79
+ "Turboshaft compile-time scopes (Tracing, TypeInferenceReducerArgs)"},
80
+ {"v8::internal::maglev::thread_graph_labeller", TlsClass::kMustBeZero,
81
+ TlsRole::kNone, "Maglev graph printing scope during compilation", true},
82
+ {"v8::internal::wasm::wasm_traces_object", TlsClass::kLeave, TlsRole::kNone,
83
+ "LeakyObject for wasm memory tracing (testing flags only)", true},
84
+ {"v8::base::OS::GetCurrentThreadId()::id", TlsClass::kLeave, TlsRole::kNone,
85
+ "OS thread id cache: still the same OS thread"},
86
+ {"guard variable for v8::base::OS::GetCurrentThreadId()::id",
87
+ TlsClass::kLeave, TlsRole::kNone, "init guard"},
88
+ // --- Node ---------------------------------------------------------------
89
+ {"node::crypto::root_cert_store", TlsClass::kLeave, TlsRole::kNone,
90
+ "per OS thread root cert store: same OS thread, which is what Node "
91
+ "expects (approach B had to route TLS to the root thread)"},
92
+ {"node::crypto::root_certs_from_users", TlsClass::kLeave, TlsRole::kNone,
93
+ "same"},
94
+ {"node::crypto::has_cleanup_hook", TlsClass::kLeave, TlsRole::kNone,
95
+ "same"},
96
+ {"node::thread_local_modpending", TlsClass::kMustBeZero, TlsRole::kNone,
97
+ "set between dlopen and module registration, no JS"},
98
+ {"node::is_retrieving_js_stacktrace", TlsClass::kSwap, TlsRole::kNone,
99
+ "recursion guard while printing a fatal error's JS stack"},
100
+ {"node::is_in_uncaught_exception", TlsClass::kSwap, TlsRole::kNone,
101
+ "recursion guard around 'uncaughtException' handlers, which run JS "
102
+ "that could park"},
103
+ {"node::handle_cleanup_depth", TlsClass::kLeave, TlsRole::kNone,
104
+ "set by the root during Environment::CleanupHandles; fibers resumed "
105
+ "there run inside it", true},
106
+ {"node::InitializePrimordials(*", TlsClass::kLeave, TlsRole::kNone,
107
+ "per thread BuiltinLoader cache"},
108
+ {"guard variable for node::InitializePrimordials(*", TlsClass::kLeave,
109
+ TlsRole::kNone, "init guard"},
110
+ {"__tls_guard", TlsClass::kLeave, TlsRole::kNone,
111
+ "compiler TLS init guard"},
112
+ // --- third-party libraries without JS callbacks --------------------------
113
+ {"absl::*", TlsClass::kLeave, TlsRole::kNone, "Abseil caches"},
114
+ {"guard variable for absl::*", TlsClass::kLeave, TlsRole::kNone, ""},
115
+ {"lexer::*", TlsClass::kLeave, TlsRole::kNone, "parser error slots"},
116
+ {"spdlog::*", TlsClass::kLeave, TlsRole::kNone, "logging context"},
117
+ {"guard variable for spdlog::*", TlsClass::kLeave, TlsRole::kNone, ""},
118
+ {"std::*", TlsClass::kLeave, TlsRole::kNone,
119
+ "Rust std (temporal_rs) thread state; no JS callbacks"},
120
+ };
121
+
122
+ bool Matches(const char* pattern, const std::string& name) {
123
+ size_t n = strlen(pattern);
124
+ if (n > 0 && pattern[n - 1] == '*') return name.compare(0, n - 1, pattern, n - 1) == 0;
125
+ return name == pattern;
126
+ }
127
+
128
+ std::string Demangle(const char* sym) {
129
+ int status = 0;
130
+ char* d = abi::__cxa_demangle(sym, nullptr, nullptr, &status);
131
+ if (status != 0 || d == nullptr) {
132
+ // LTO-split symbols (Rust std in Node 26): "<mangled>.0" -> retry without.
133
+ const char* dot = strrchr(sym, '.');
134
+ if (dot != nullptr && dot != sym) return Demangle(std::string(sym, dot).c_str());
135
+ return sym;
136
+ }
137
+ std::string out(d);
138
+ free(d);
139
+ return out;
140
+ }
141
+
142
+ bool PRead(int fd, void* buf, size_t len, off_t off) {
143
+ char* p = static_cast<char*>(buf);
144
+ while (len > 0) {
145
+ ssize_t r = pread(fd, p, len, off);
146
+ if (r <= 0) return false;
147
+ p += r;
148
+ len -= r;
149
+ off += r;
150
+ }
151
+ return true;
152
+ }
153
+
154
+ struct TlsModuleInfo {
155
+ bool found = false;
156
+ void* tls_data = nullptr; // this thread's TLS block of the executable
157
+ size_t memsz = 0, align = 0;
158
+ };
159
+
160
+ int FindMainTls(struct dl_phdr_info* info, size_t, void* data) {
161
+ auto* out = static_cast<TlsModuleInfo*>(data);
162
+ if (info->dlpi_tls_modid != 1) return 0;
163
+ out->found = true;
164
+ out->tls_data = info->dlpi_tls_data;
165
+ for (int i = 0; i < info->dlpi_phnum; i++) {
166
+ if (info->dlpi_phdr[i].p_type == PT_TLS) {
167
+ out->memsz = info->dlpi_phdr[i].p_memsz;
168
+ out->align = info->dlpi_phdr[i].p_align;
169
+ }
170
+ }
171
+ return 1;
172
+ }
173
+
174
+ } // namespace
175
+
176
+ TlsLayout DiscoverTls() {
177
+ TlsLayout out;
178
+ TlsModuleInfo mod;
179
+ dl_iterate_phdr(FindMainTls, &mod);
180
+ if (!mod.found || mod.tls_data == nullptr) {
181
+ out.error = "the executable has no TLS block (dl_iterate_phdr modid 1)";
182
+ return out;
183
+ }
184
+ char* tp = ThreadPointer();
185
+ // Cross-check with the x86-64 variant II formula: the executable's block
186
+ // ends at the thread pointer.
187
+ size_t align = mod.align ? mod.align : 1;
188
+ size_t rounded = (mod.memsz + align - 1) / align * align;
189
+ if (static_cast<char*>(mod.tls_data) != tp - rounded) {
190
+ out.error = "the executable's TLS block is not where TLS variant II puts it";
191
+ return out;
192
+ }
193
+
194
+ int fd = open("/proc/self/exe", O_RDONLY | O_CLOEXEC);
195
+ if (fd < 0) {
196
+ out.error = "cannot open /proc/self/exe";
197
+ return out;
198
+ }
199
+ std::unique_ptr<int, void (*)(int*)> closer(&fd, [](int* f) { close(*f); });
200
+ Elf64_Ehdr eh;
201
+ if (!PRead(fd, &eh, sizeof eh, 0) || memcmp(eh.e_ident, ELFMAG, SELFMAG) != 0 ||
202
+ eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_X86_64) {
203
+ out.error = "/proc/self/exe is not an x86-64 ELF64 file";
204
+ return out;
205
+ }
206
+ std::vector<Elf64_Shdr> sh(eh.e_shnum);
207
+ if (!PRead(fd, sh.data(), sizeof(Elf64_Shdr) * eh.e_shnum, eh.e_shoff)) {
208
+ out.error = "cannot read section headers";
209
+ return out;
210
+ }
211
+ const Elf64_Shdr* symtab = nullptr;
212
+ for (auto& s : sh) {
213
+ if (s.sh_type == SHT_SYMTAB) symtab = &s;
214
+ }
215
+ if (symtab == nullptr) {
216
+ out.error =
217
+ "the node executable has no .symtab (stripped binary); fibers "
218
+ "needs it to find V8's thread-locals";
219
+ return out;
220
+ }
221
+ const Elf64_Shdr& strtab = sh[symtab->sh_link];
222
+ std::vector<char> strings(strtab.sh_size);
223
+ if (!PRead(fd, strings.data(), strings.size(), strtab.sh_offset)) {
224
+ out.error = "cannot read .strtab";
225
+ return out;
226
+ }
227
+ size_t count = symtab->sh_size / sizeof(Elf64_Sym);
228
+ // Read in chunks: .symtab of node is ~10-20 MB.
229
+ const size_t kChunk = 65536;
230
+ std::vector<Elf64_Sym> buf(kChunk);
231
+ for (size_t base = 0; base < count; base += kChunk) {
232
+ size_t n = std::min(kChunk, count - base);
233
+ if (!PRead(fd, buf.data(), n * sizeof(Elf64_Sym),
234
+ symtab->sh_offset + base * sizeof(Elf64_Sym))) {
235
+ out.error = "cannot read .symtab";
236
+ return out;
237
+ }
238
+ for (size_t i = 0; i < n; i++) {
239
+ const Elf64_Sym& s = buf[i];
240
+ if (ELF64_ST_TYPE(s.st_info) != STT_TLS || s.st_shndx == SHN_UNDEF) continue;
241
+ if (s.st_name >= strings.size()) continue;
242
+ TlsVar v;
243
+ v.name = Demangle(&strings[s.st_name]);
244
+ v.size = s.st_size;
245
+ v.tp_offset = (static_cast<char*>(mod.tls_data) + s.st_value) - tp;
246
+ bool matched = false;
247
+ for (const Rule& r : kRules) {
248
+ if (Matches(r.name, v.name)) {
249
+ v.cls = r.cls;
250
+ v.role = r.role;
251
+ v.why = r.why;
252
+ matched = true;
253
+ break;
254
+ }
255
+ }
256
+ bool dup = false;
257
+ for (auto& e : out.vars) {
258
+ if (e.name == v.name && e.tp_offset == v.tp_offset) dup = true;
259
+ }
260
+ if (dup) continue;
261
+ if (!matched) out.unknown.push_back(v.name);
262
+ out.vars.push_back(v);
263
+ }
264
+ }
265
+ return out;
266
+ }
267
+
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // Swapping and checking (process-wide layout, computed once).
271
+ // ---------------------------------------------------------------------------
272
+ namespace {
273
+
274
+ [[noreturn]] void Fatal(const std::string& msg) {
275
+ fprintf(stderr, "fibers: FATAL: %s\n", msg.c_str());
276
+ fflush(stderr);
277
+ abort();
278
+ }
279
+
280
+ bool EnvFlag(const char* name) {
281
+ const char* e = getenv(name);
282
+ return e != nullptr && strcmp(e, "1") == 0;
283
+ }
284
+
285
+ // ---------------------------------------------------------------------------
286
+ // Thread-local layout (process-wide, computed once).
287
+ // ---------------------------------------------------------------------------
288
+ struct SwapSlot {
289
+ intptr_t tp_offset;
290
+ size_t size;
291
+ size_t image_offset;
292
+ TlsRole role;
293
+ };
294
+ struct CheckSlot {
295
+ intptr_t tp_offset;
296
+ size_t size;
297
+ const char* name;
298
+ };
299
+
300
+ std::vector<SwapSlot> g_swap;
301
+ std::vector<CheckSlot> g_must_be_zero; // checked before every switch
302
+ std::vector<CheckSlot> g_enter_managed; // checked after a full Exit
303
+ intptr_t g_current_isolate_offset = 0;
304
+ uint8_t g_assert_data_initial[8];
305
+ bool g_skip_checks = false; // FIBERS_NO_CHECKS=1 (diagnostics only)
306
+ std::string g_layout_report;
307
+
308
+ bool AllZero(const char* p, size_t n) {
309
+ for (size_t i = 0; i < n; i++)
310
+ if (p[i] != 0) return false;
311
+ return true;
312
+ }
313
+
314
+ // The name of the first non-empty variable, or nullptr.
315
+ const char* FirstNonZero(const std::vector<CheckSlot>& slots) {
316
+ char* tp = ThreadPointer();
317
+ for (const CheckSlot& c : slots) {
318
+ if (!AllZero(tp + c.tp_offset, c.size)) return c.name;
319
+ }
320
+ return nullptr;
321
+ }
322
+
323
+ void CheckBeforeSwitchImpl() {
324
+ if (g_skip_checks) return;
325
+ if (const char* bad = FirstNonZero(g_must_be_zero)) {
326
+ Fatal(std::string("thread-local '") + bad +
327
+ "' is not empty at a fiber switch; V8 state that fibers cannot "
328
+ "move between fibers");
329
+ }
330
+ }
331
+
332
+ void CheckAfterExitImpl() {
333
+ if (g_skip_checks) return;
334
+ if (const char* bad = FirstNonZero(g_enter_managed)) {
335
+ Fatal(std::string("thread-local '") + bad +
336
+ "' is still set after the isolate was fully exited");
337
+ }
338
+ }
339
+
340
+ const char* ClassName(TlsClass c) {
341
+ switch (c) {
342
+ case TlsClass::kSwap: return "swap";
343
+ case TlsClass::kEnterManaged: return "enter-managed";
344
+ case TlsClass::kMustBeZero: return "must-be-zero";
345
+ case TlsClass::kLeave: return "leave";
346
+ }
347
+ return "?";
348
+ }
349
+
350
+ // Builds the layout once per process. Returns an error message or "".
351
+ std::string SetUpLayout() {
352
+ static std::once_flag once;
353
+ static std::string error;
354
+ std::call_once(once, [] {
355
+ g_skip_checks = EnvFlag("FIBERS_NO_CHECKS");
356
+ TlsLayout layout = DiscoverTls();
357
+ if (!layout.error.empty()) {
358
+ error = layout.error;
359
+ return;
360
+ }
361
+ for (const TlsVar& v : layout.vars) {
362
+ char line[512];
363
+ snprintf(line, sizeof line, "%-14s %+6ld %3zu %s\n", ClassName(v.cls),
364
+ static_cast<long>(v.tp_offset), v.size, v.name.c_str());
365
+ g_layout_report += line;
366
+ }
367
+ if (!layout.unknown.empty() && !EnvFlag("FIBERS_ALLOW_UNKNOWN_TLS")) {
368
+ error = "refusing to load: this node binary has thread-local variables "
369
+ "that fibers does not know: ";
370
+ for (size_t i = 0; i < layout.unknown.size(); i++) {
371
+ if (i) error += ", ";
372
+ error += layout.unknown[i];
373
+ }
374
+ error += ". They must be classified in native/tls.cc (swap / must-be-zero "
375
+ "/ leave) after reading their V8/Node source.";
376
+ return;
377
+ }
378
+ size_t image_off = 0;
379
+ bool have_isolate = false, have_tid = false, have_stack = false;
380
+ for (const TlsVar& v : layout.vars) {
381
+ // Expected sizes, so that a type change in V8 is noticed.
382
+ size_t want = v.role == TlsRole::kThreadId ? 4
383
+ : v.role == TlsRole::kStackStart ? 8
384
+ : v.role == TlsRole::kAssertData ? 4
385
+ : v.role == TlsRole::kCurrentIsolate ? 8
386
+ : 0;
387
+ if (want != 0 && v.size != want) {
388
+ error = "unexpected size of the thread-local " + v.name;
389
+ return;
390
+ }
391
+ if (v.cls != TlsClass::kLeave && v.size > 16) {
392
+ error = "unexpectedly large swapped/checked thread-local " + v.name;
393
+ return;
394
+ }
395
+ if (v.role == TlsRole::kCurrentIsolate) {
396
+ g_current_isolate_offset = v.tp_offset;
397
+ have_isolate = true;
398
+ }
399
+ if (v.role == TlsRole::kThreadId) {
400
+ have_tid = true;
401
+ }
402
+ if (v.role == TlsRole::kStackStart) have_stack = true;
403
+ switch (v.cls) {
404
+ case TlsClass::kSwap:
405
+ if (image_off + v.size > kTlsImageSize) {
406
+ error = "too many swapped thread-locals";
407
+ return;
408
+ }
409
+ if (v.role == TlsRole::kAssertData) {
410
+ memcpy(g_assert_data_initial, ThreadPointer() + v.tp_offset, v.size);
411
+ }
412
+ g_swap.push_back({v.tp_offset, v.size, image_off, v.role});
413
+ image_off += (v.size + 7) & ~size_t{7};
414
+ break;
415
+ case TlsClass::kEnterManaged:
416
+ g_enter_managed.push_back({v.tp_offset, v.size, strdup(v.name.c_str())});
417
+ break;
418
+ case TlsClass::kMustBeZero:
419
+ g_must_be_zero.push_back({v.tp_offset, v.size, strdup(v.name.c_str())});
420
+ break;
421
+ case TlsClass::kLeave:
422
+ break;
423
+ }
424
+ }
425
+ if (!have_isolate || !have_tid || !have_stack) {
426
+ error = "g_current_isolate_, thread_id or thread_stack_start not found "
427
+ "in the node executable's .symtab";
428
+ return;
429
+ }
430
+ });
431
+ return error;
432
+ }
433
+
434
+ // Runs on every JS thread that loads the addon: the computed address of
435
+ // g_current_isolate_ must hold the isolate this thread runs, and the
436
+ // must-be-zero variables must be zero while JS runs.
437
+ std::string SelfCheck(void* isolate) {
438
+ void* seen;
439
+ memcpy(&seen, ThreadPointer() + g_current_isolate_offset, sizeof seen);
440
+ if (seen != isolate) {
441
+ char m[256];
442
+ snprintf(m, sizeof m,
443
+ "self-check failed: the computed g_current_isolate_ holds %p, "
444
+ "v8::Isolate::GetCurrent() is %p",
445
+ seen, isolate);
446
+ return m;
447
+ }
448
+ if (const char* bad = FirstNonZero(g_must_be_zero)) {
449
+ return std::string("self-check failed: '") + bad +
450
+ "' is not empty while JS runs";
451
+ }
452
+ return "";
453
+ }
454
+
455
+ } // namespace
456
+
457
+ std::string InitTls(void* isolate) {
458
+ std::string error = SetUpLayout();
459
+ return error.empty() ? SelfCheck(isolate) : error;
460
+ }
461
+
462
+ const std::string& TlsReport() { return g_layout_report; }
463
+
464
+ void SaveTls(TlsImage* image) {
465
+ char* tp = ThreadPointer();
466
+ for (const SwapSlot& s : g_swap) memcpy(image->bytes + s.image_offset, tp + s.tp_offset, s.size);
467
+ }
468
+
469
+ void LoadTls(const TlsImage* image) {
470
+ char* tp = ThreadPointer();
471
+ for (const SwapSlot& s : g_swap) memcpy(tp + s.tp_offset, image->bytes + s.image_offset, s.size);
472
+ }
473
+
474
+ void InitTls(TlsImage* image, void* stack_top) {
475
+ for (const SwapSlot& s : g_swap) {
476
+ uint8_t* p = image->bytes + s.image_offset;
477
+ memset(p, 0, s.size);
478
+ if (s.role == TlsRole::kStackStart) memcpy(p, &stack_top, sizeof stack_top);
479
+ if (s.role == TlsRole::kAssertData) memcpy(p, g_assert_data_initial, s.size);
480
+ }
481
+ }
482
+
483
+ void SetTlsStackStart(TlsImage* image, void* stack_top) {
484
+ for (const SwapSlot& s : g_swap) {
485
+ if (s.role == TlsRole::kStackStart) {
486
+ memcpy(image->bytes + s.image_offset, &stack_top, sizeof stack_top);
487
+ }
488
+ }
489
+ }
490
+
491
+ void CheckTlsBeforeSwitch() { CheckBeforeSwitchImpl(); }
492
+ void CheckTlsAfterExit() { CheckAfterExitImpl(); }
493
+
494
+ } // namespace fibers
package/native/tls.h ADDED
@@ -0,0 +1,101 @@
1
+ // V8's thread-locals. For V8 to treat every fiber as its own thread, each fiber
2
+ // needs its own thread id, stack start and a few scope variables. V8 keeps them
3
+ // in C++ thread_locals (since commit dacc2fee0f, Node 16), which no API exposes.
4
+ // This file finds them in the node executable's ELF .symtab, checks that it
5
+ // knows every one of them, and saves / loads the ones that make up a V8
6
+ // "thread".
7
+ //
8
+ // Discovery:
9
+ // Finds every TLS symbol of the running executable through its ELF .symtab,
10
+ // classifies it by (demangled) name, and computes its offset from the thread
11
+ // pointer. Main-executable TLS on x86-64 is static TLS (TLS variant II, local-
12
+ // exec model), so the offset from %fs:0 is the same on every OS thread.
13
+ #pragma once
14
+
15
+ #include <cstddef>
16
+ #include <cstdint>
17
+ #include <string>
18
+ #include <vector>
19
+
20
+ namespace fibers {
21
+
22
+ enum class TlsClass {
23
+ // Per logical thread: saved/restored on every switch.
24
+ kSwap,
25
+ // Managed by Isolate::Enter/Exit: must be zero after the isolate has been
26
+ // fully exited (checked on every switch).
27
+ kEnterManaged,
28
+ // Must be zero whenever a fiber switch happens (compiler / wasm / GC-internal
29
+ // scopes that never span a call into JS). Checked on every switch.
30
+ kMustBeZero,
31
+ // Per OS thread and not tied to the V8 "thread" identity: left alone.
32
+ kLeave,
33
+ };
34
+
35
+ // What a swapped variable is, so a new fiber gets the right initial value.
36
+ enum class TlsRole {
37
+ kNone,
38
+ kThreadId, // v8::internal::(anon)::thread_id -> 0 (fresh id)
39
+ kStackStart, // v8::base::(anon)::thread_stack_start -> fiber stack top
40
+ kAssertData, // current_per_thread_assert_data -> value seen at load
41
+ kCurrentIsolate, // g_current_isolate_ (self-check)
42
+ };
43
+
44
+ struct TlsVar {
45
+ std::string name; // demangled
46
+ size_t size = 0;
47
+ intptr_t tp_offset = 0; // address = thread pointer + tp_offset
48
+ TlsClass cls = TlsClass::kLeave;
49
+ TlsRole role = TlsRole::kNone;
50
+ const char* why = "";
51
+ };
52
+
53
+ struct TlsLayout {
54
+ std::vector<TlsVar> vars;
55
+ std::vector<std::string> unknown; // names no rule matched (load refused)
56
+ std::string error; // non-empty: discovery failed
57
+ };
58
+
59
+ // Reads /proc/self/exe once. Must run on a thread that has entered the
60
+ // isolate (for the self-check done by the caller).
61
+ TlsLayout DiscoverTls();
62
+
63
+ // --- Used by coroutine.cc and fibers.cc ------------------------------------
64
+
65
+ // The swapped thread-locals of one coroutine.
66
+ constexpr size_t kTlsImageSize = 64;
67
+ struct TlsImage {
68
+ alignas(8) uint8_t bytes[kTlsImageSize] = {};
69
+ };
70
+
71
+ // Once per JS thread at load, with the isolate entered: classifies the
72
+ // thread-locals (once per process) and self-checks them on this thread.
73
+ // Returns an error message, or "" when fibers can run here.
74
+ std::string InitTls(void* isolate);
75
+ // The classification, one line per variable (diagnostics).
76
+ const std::string& TlsReport();
77
+
78
+ void SaveTls(TlsImage* image);
79
+ void LoadTls(const TlsImage* image);
80
+ // The image of a V8 thread that has not started yet: thread id 0 (V8 assigns
81
+ // one at its first Locker), stack start = top of its stack (V8 derives the JS
82
+ // stack limit and the conservative stack scan range from it), empty scopes.
83
+ void InitTls(TlsImage* image, void* stack_top);
84
+
85
+ // A coroutine that got a new stack keeps its V8 thread id (and the rest of the
86
+ // image); only its stack start moves to the new stack's top.
87
+ void SetTlsStackStart(TlsImage* image, void* stack_top);
88
+ // Fatal if a "must be zero" variable is set (a compiler / GC / wasm scope
89
+ // that can't move between fibers); call before every switch.
90
+ void CheckTlsBeforeSwitch();
91
+ // Fatal if Isolate::Enter state is still set after the isolate was exited
92
+ // completely; call after the full Exit, before the Unlocker.
93
+ void CheckTlsAfterExit();
94
+
95
+ inline char* ThreadPointer() {
96
+ char* tp;
97
+ asm volatile("mov %%fs:0, %0" : "=r"(tp));
98
+ return tp;
99
+ }
100
+
101
+ } // namespace fibers
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
- "name": "@mrwinston/fibers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@mrwinston/fibers",
3
+ "version": "0.1.0",
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
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "types": "dist/index.d.cts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.cts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "binding.gyp",
18
+ "dist/",
19
+ "native/",
20
+ "scripts/install.mjs",
21
+ "prebuilds/",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "scripts": {
26
+ "install": "node scripts/install.mjs",
27
+ "typecheck": "tsc --noEmit",
28
+ "build:js": "tsdown",
29
+ "build:native": "node-gyp rebuild",
30
+ "build": "npm run typecheck && npm run build:js && npm run build:native",
31
+ "prebuilds": "node scripts/build-prebuilds.mjs",
32
+ "test": "node --expose-gc --test \"test/*.test.mjs\"",
33
+ "test:stress": "node scripts/test-stress.mjs"
34
+ },
35
+ "os": [
36
+ "linux"
37
+ ],
38
+ "cpu": [
39
+ "x64"
40
+ ],
41
+ "engines": {
42
+ "node": ">=24"
43
+ },
44
+ "gypfile": true,
45
+ "keywords": [
46
+ "fibers",
47
+ "coroutines",
48
+ "sync",
49
+ "async",
50
+ "v8",
51
+ "meteor"
52
+ ],
53
+ "license": "MIT",
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://bitbucket.org/possys/node-fibers.git"
57
+ },
58
+ "publishConfig": {
59
+ "access": "public"
60
+ },
61
+ "devDependencies": {
62
+ "@biomejs/biome": "^2.6.8",
63
+ "@types/node": "^24.19.2",
64
+ "node-gyp": "^13.1.0",
65
+ "tsdown": "^0.23.7",
66
+ "typescript": "^7.1.0-beta"
67
+ }
68
+ }