vsql-node 0.0.0-stage → 0.0.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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +203 -2
  3. package/binding.gyp +44 -0
  4. package/index.d.ts +133 -0
  5. package/internal/amalgamation/LICENSE +21 -0
  6. package/internal/amalgamation/LICENSE-V +21 -0
  7. package/internal/amalgamation/afunix.h +26 -0
  8. package/internal/amalgamation/atomic.h +571 -0
  9. package/internal/amalgamation/core_windows.c +25 -0
  10. package/internal/amalgamation/core_windows.h +9 -0
  11. package/internal/amalgamation/execute_capture_nix.c +7 -0
  12. package/internal/amalgamation/execute_capture_nix.h +266 -0
  13. package/internal/amalgamation/gc/cord.h +426 -0
  14. package/internal/amalgamation/gc/cord_pos.h +151 -0
  15. package/internal/amalgamation/gc/ec.h +91 -0
  16. package/internal/amalgamation/gc/gc.h +2826 -0
  17. package/internal/amalgamation/gc/gc_allocator.h +480 -0
  18. package/internal/amalgamation/gc/gc_backptr.h +109 -0
  19. package/internal/amalgamation/gc/gc_config_macros.h +548 -0
  20. package/internal/amalgamation/gc/gc_disclaim.h +85 -0
  21. package/internal/amalgamation/gc/gc_gcj.h +123 -0
  22. package/internal/amalgamation/gc/gc_inline.h +261 -0
  23. package/internal/amalgamation/gc/gc_mark.h +516 -0
  24. package/internal/amalgamation/gc/gc_pthread_redirects.h +140 -0
  25. package/internal/amalgamation/gc/gc_tiny_fl.h +107 -0
  26. package/internal/amalgamation/gc/gc_typed.h +196 -0
  27. package/internal/amalgamation/gc/gc_version.h +55 -0
  28. package/internal/amalgamation/gc/javaxfc.h +76 -0
  29. package/internal/amalgamation/gc/leak_detector.h +120 -0
  30. package/internal/amalgamation/gc.c +45932 -0
  31. package/internal/amalgamation/gc.h +4 -0
  32. package/internal/amalgamation/gc_boehm_helpers.c +64 -0
  33. package/internal/amalgamation/gc_debugger_linux.h +61 -0
  34. package/internal/amalgamation/getrandom_linux.h +33 -0
  35. package/internal/amalgamation/ipv6_v6only.h +5 -0
  36. package/internal/amalgamation/libvsql.c +27 -0
  37. package/internal/amalgamation/libvsql.h +1772 -0
  38. package/internal/amalgamation/libvsql_linux_amd64.c +106591 -0
  39. package/internal/amalgamation/libvsql_linux_arm64.c +106571 -0
  40. package/internal/amalgamation/libvsql_macos_amd64.c +106728 -0
  41. package/internal/amalgamation/libvsql_macos_arm64.c +106708 -0
  42. package/internal/amalgamation/libvsql_windows_amd64.c +108235 -0
  43. package/internal/amalgamation/segfault_handler_nix.c +56 -0
  44. package/internal/amalgamation/segfault_handler_nix.h +449 -0
  45. package/internal/amalgamation/segfault_handler_windows.h +52 -0
  46. package/internal/amalgamation/thread_helper.c +12 -0
  47. package/internal/amalgamation/thread_helper.h +96 -0
  48. package/internal/amalgamation/ticks_windows.c +3 -0
  49. package/internal/amalgamation/ticks_windows.h +31 -0
  50. package/internal/amalgamation/ticks_windows_api.h +6 -0
  51. package/internal/amalgamation/vsql_runtime.c +14 -0
  52. package/internal/amalgamation/vsql_runtime_linux.c +6 -0
  53. package/internal/amalgamation/vsql_runtime_macos.c +6 -0
  54. package/internal/amalgamation/vsql_runtime_windows.c +6 -0
  55. package/lib/binding.js +13 -0
  56. package/lib/connection.js +492 -0
  57. package/lib/convert.js +213 -0
  58. package/lib/errors.js +17 -0
  59. package/lib/index.js +41 -0
  60. package/libvsql_flags.gypi +30 -0
  61. package/package.json +45 -4
  62. package/src/binding.c +773 -0
  63. package/src/runtime.c +20 -0
@@ -0,0 +1,56 @@
1
+ // Keep platform signal layouts in a cached native object, outside generated C.
2
+ #include <stddef.h>
3
+ #if defined(V_GCBOEHM_NATIVE)
4
+ #if defined(__TINYC__) && defined(__linux__)
5
+ #include <gc/gc.h>
6
+ #else
7
+ #include <gc.h>
8
+ #endif
9
+ #define CUSTOM_DEFINE_gcboehm
10
+ #endif
11
+ #define V_PARALLEL_CC 1
12
+ #define V_PARALLEL_CC_OUT_0 1
13
+ #include "segfault_handler_nix.h"
14
+
15
+ void* v_thread_signal_stack_enter(void* stack_top, size_t stack_size) {
16
+ #if defined(V_SEGFAULT_HANDLER_ACTIVE)
17
+ stack_t old;
18
+ memset(&old, 0, sizeof(old));
19
+ if (sigaltstack(NULL, &old) != 0 || !(old.ss_flags & SS_DISABLE)) {
20
+ return NULL;
21
+ }
22
+ #if defined(__APPLE__)
23
+ (void)stack_top;
24
+ uintptr_t hi = (uintptr_t)pthread_get_stackaddr_np(pthread_self());
25
+ stack_size = pthread_get_stacksize_np(pthread_self());
26
+ #else
27
+ uintptr_t hi = (uintptr_t)stack_top;
28
+ #endif
29
+ v_signal_stack_register(hi > stack_size ? hi - stack_size : 0, hi);
30
+ stack_t ss;
31
+ memset(&ss, 0, sizeof(ss));
32
+ if (sigaltstack(NULL, &ss) == 0 && !(ss.ss_flags & SS_DISABLE)) {
33
+ return ss.ss_sp;
34
+ }
35
+ #else
36
+ (void)stack_top;
37
+ (void)stack_size;
38
+ #endif
39
+ return NULL;
40
+ }
41
+
42
+ void v_thread_signal_stack_leave(void* alt_stack) {
43
+ #if defined(V_SEGFAULT_HANDLER_ACTIVE)
44
+ if (alt_stack == NULL) {
45
+ return;
46
+ }
47
+ stack_t ss;
48
+ memset(&ss, 0, sizeof(ss));
49
+ ss.ss_flags = SS_DISABLE;
50
+ if (sigaltstack(&ss, NULL) == 0) {
51
+ munmap(alt_stack, (size_t)((uintptr_t*)alt_stack)[3]);
52
+ }
53
+ #else
54
+ (void)alt_stack;
55
+ #endif
56
+ }
@@ -0,0 +1,449 @@
1
+ // segfault_handler_nix.h installs V's SIGSEGV/SIGBUS handler for hosted Unix programs.
2
+ //
3
+ // A stack overflow leaves no room on the faulting thread's own stack, so the handler
4
+ // runs on an alternate signal stack (`sigaltstack`). A fault address inside or just
5
+ // below the stack of the faulting thread is reported as a stack overflow. Any other
6
+ // fault goes to the handler that was installed before (if any), or for SIGSEGV to V's
7
+ // `v_segmentation_fault_handler`. The stack overflow path is
8
+ // async-signal-safe: it only uses write(2), sigaltstack(2), backtrace_symbols_fd and
9
+ // _exit.
10
+ //
11
+ // Every alternate signal stack that V registers starts with 4 words: a magic value,
12
+ // the lowest and the highest address of the thread stack it belongs to, and the size of
13
+ // the alternate stack mapping. The spawned-thread runtime that the C backend emits
14
+ // (`__v_thread_signal_stack_enter`) writes the same layout; keep both in sync.
15
+ #if !defined(_WIN32) && !defined(V_SEGFAULT_HANDLER_NIX_H)
16
+ #define V_SEGFAULT_HANDLER_NIX_H
17
+
18
+ // Split builds keep the signal actions and their helpers in the owner unit.
19
+ #define V_PARALLEL_CC_STATIC_STORAGE_HANDLED 1
20
+ #if !defined(V_PARALLEL_CC) || defined(V_PARALLEL_CC_OUT_0)
21
+
22
+ #if defined(V_PARALLEL_CC)
23
+ #define V_SEGFAULT_HANDLER_SCOPE
24
+ #else
25
+ #define V_SEGFAULT_HANDLER_SCOPE static
26
+ #endif
27
+
28
+ #include <errno.h>
29
+ #include <signal.h>
30
+ #include <stddef.h>
31
+ #include <stdint.h>
32
+ #include <string.h>
33
+ #include <unistd.h>
34
+ #include <pthread.h>
35
+ #include <sys/mman.h>
36
+ #include <sys/resource.h>
37
+
38
+ #if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) || defined(__SANITIZE_HWADDRESS__)
39
+ #define V_SEGFAULT_HANDLER_SANITIZED 1
40
+ #elif defined(__has_feature)
41
+ #if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || __has_feature(memory_sanitizer) || __has_feature(hwaddress_sanitizer)
42
+ #define V_SEGFAULT_HANDLER_SANITIZED 1
43
+ #endif
44
+ #endif
45
+
46
+ #if defined(SA_ONSTACK) && defined(SA_SIGINFO) && defined(SS_DISABLE) && (defined(MAP_ANONYMOUS) || defined(MAP_ANON)) \
47
+ && !defined(V_SEGFAULT_HANDLER_SANITIZED) && !defined(__wasm__) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
48
+ #define V_SEGFAULT_HANDLER_ACTIVE 1
49
+ #endif
50
+
51
+ #if defined(V_SEGFAULT_HANDLER_ACTIVE)
52
+
53
+ #if defined(__APPLE__) || defined(__linux__)
54
+ #include <sys/ucontext.h>
55
+ #endif
56
+ #if defined(__APPLE__) || defined(__GLIBC__)
57
+ #include <execinfo.h>
58
+ #define V_SEGFAULT_HANDLER_SYMBOLS 1
59
+ #endif
60
+
61
+ #define V_SIGNAL_STACK_MAGIC ((uintptr_t)0x56534f56u)
62
+ // Faults up to this far below the lowest stack address still count as a stack
63
+ // overflow: a function with a big frame can skip past the guard page.
64
+ #define V_STACK_OVERFLOW_SLACK ((uintptr_t)256 * 1024)
65
+ #define V_STACK_OVERFLOW_MAX_LINES 48
66
+
67
+ typedef void (*v_segfault_fallback_fn)(int);
68
+ static v_segfault_fallback_fn v_segfault_fallback = 0;
69
+ // The actions that were installed before V's handler, for SIGSEGV and SIGBUS.
70
+ static struct sigaction v_segfault_previous[2];
71
+ // Saved actions stay immutable. Atomically consume one-shot handlers across threads.
72
+ static int v_segfault_previous_consumed[2];
73
+
74
+ static int v_segfault_consume_previous(int index) {
75
+ #if defined(__TINYC__)
76
+ // TinyCC compiles atomic builtins to calls into its runtime, and the runtimes of the
77
+ // Linux arm and arm64 TCC bundles have no atomic helpers. V's action is one-shot
78
+ // there whenever the previous one is (see v_segfault_install_signal), so the kernel
79
+ // consumed it, when it delivered this signal.
80
+ (void)index;
81
+ return 1;
82
+ #else
83
+ return __atomic_exchange_n(&v_segfault_previous_consumed[index], 1, 5) == 0;
84
+ #endif
85
+ }
86
+
87
+ static void v_segfault_write(const char* s, size_t len) {
88
+ while (len > 0) {
89
+ ssize_t written = write(2, s, len);
90
+ if (written <= 0) {
91
+ if (written < 0 && errno == EINTR) {
92
+ continue;
93
+ }
94
+ return;
95
+ }
96
+ s += written;
97
+ len -= (size_t)written;
98
+ }
99
+ }
100
+
101
+ static void v_segfault_write_str(const char* s) {
102
+ v_segfault_write(s, strlen(s));
103
+ }
104
+
105
+ static void v_segfault_write_uint(uintptr_t value, unsigned base) {
106
+ char buf[32];
107
+ size_t i = sizeof(buf);
108
+ do {
109
+ unsigned digit = (unsigned)(value % base);
110
+ buf[--i] = (char)(digit < 10 ? '0' + digit : 'a' + digit - 10);
111
+ value /= base;
112
+ } while (value != 0 && i > 0);
113
+ v_segfault_write(buf + i, sizeof(buf) - i);
114
+ }
115
+
116
+ // v_signal_stack_bounds reads the stack bounds that V stored at the base of the
117
+ // alternate signal stack, that the handler currently runs on.
118
+ static int v_signal_stack_bounds(uintptr_t* lo, uintptr_t* hi) {
119
+ stack_t ss;
120
+ memset(&ss, 0, sizeof(ss));
121
+ if (sigaltstack(NULL, &ss) != 0 || !(ss.ss_flags & SS_ONSTACK) || ss.ss_sp == NULL
122
+ || ss.ss_size < 4 * sizeof(uintptr_t)) {
123
+ return 0;
124
+ }
125
+ uintptr_t* header = (uintptr_t*)ss.ss_sp;
126
+ if (header[0] != V_SIGNAL_STACK_MAGIC || header[2] == 0) {
127
+ return 0;
128
+ }
129
+ *lo = header[1];
130
+ *hi = header[2];
131
+ return 1;
132
+ }
133
+
134
+ static uintptr_t v_segfault_code_address(uintptr_t addr) {
135
+ #if defined(__aarch64__) || defined(__arm64__)
136
+ // Drop pointer authentication bits from saved return addresses.
137
+ addr &= (uintptr_t)0x0000ffffffffffffULL;
138
+ #endif
139
+ return addr;
140
+ }
141
+
142
+ static int v_segfault_context_registers(void* context, uintptr_t* pc, uintptr_t* fp) {
143
+ if (context == NULL) {
144
+ return 0;
145
+ }
146
+ #if defined(__APPLE__) && (defined(__aarch64__) || defined(__arm64__))
147
+ ucontext_t* uc = (ucontext_t*)context;
148
+ *pc = (uintptr_t)uc->uc_mcontext->__ss.__pc;
149
+ *fp = (uintptr_t)uc->uc_mcontext->__ss.__fp;
150
+ return 1;
151
+ #elif defined(__APPLE__) && defined(__x86_64__)
152
+ ucontext_t* uc = (ucontext_t*)context;
153
+ *pc = (uintptr_t)uc->uc_mcontext->__ss.__rip;
154
+ *fp = (uintptr_t)uc->uc_mcontext->__ss.__rbp;
155
+ return 1;
156
+ #elif defined(__linux__) && defined(__x86_64__)
157
+ ucontext_t* uc = (ucontext_t*)context;
158
+ // REG_RIP and REG_RBP, without depending on _GNU_SOURCE:
159
+ *pc = (uintptr_t)uc->uc_mcontext.gregs[16];
160
+ *fp = (uintptr_t)uc->uc_mcontext.gregs[10];
161
+ return 1;
162
+ #elif defined(__linux__) && defined(__aarch64__)
163
+ // uc_mcontext is 16-byte aligned. TCC ignores that alignment attribute, which
164
+ // would shift every register by 8 bytes, so align its offset explicitly.
165
+ size_t offset = (offsetof(ucontext_t, uc_mcontext) + 15) & ~(size_t)15;
166
+ mcontext_t* mc = (mcontext_t*)((char*)context + offset);
167
+ *pc = (uintptr_t)mc->pc;
168
+ *fp = (uintptr_t)mc->regs[29];
169
+ return 1;
170
+ #else
171
+ (void)pc;
172
+ (void)fp;
173
+ return 0;
174
+ #endif
175
+ }
176
+
177
+ static void v_segfault_flush_frames(void** frames, int* len) {
178
+ if (*len == 0) {
179
+ return;
180
+ }
181
+ #if defined(V_SEGFAULT_HANDLER_SYMBOLS)
182
+ backtrace_symbols_fd(frames, *len, 2);
183
+ #else
184
+ for (int i = 0; i < *len; i++) {
185
+ v_segfault_write_str("0x");
186
+ v_segfault_write_uint((uintptr_t)frames[i], 16);
187
+ v_segfault_write_str("\n");
188
+ }
189
+ #endif
190
+ *len = 0;
191
+ }
192
+
193
+ // v_stack_overflow_backtrace walks the frame pointer chain of the overflowed stack,
194
+ // starting from the interrupted context. It only reads frame records inside the
195
+ // thread's stack bounds, and folds the long runs of identical frames, that a
196
+ // runaway recursion leaves, into a single line.
197
+ static void v_stack_overflow_backtrace(void* context, uintptr_t lo, uintptr_t hi) {
198
+ uintptr_t pc = 0;
199
+ uintptr_t fp = 0;
200
+ if (!v_segfault_context_registers(context, &pc, &fp)) {
201
+ return;
202
+ }
203
+ // The recorded bounds can be estimates, see v_install_segfault_handler and
204
+ // `__v_thread_signal_stack_enter`, so accept frames in the whole overflow window.
205
+ uintptr_t lowest = lo > V_STACK_OVERFLOW_SLACK ? lo - V_STACK_OVERFLOW_SLACK : 0;
206
+ void* frames[V_STACK_OVERFLOW_MAX_LINES];
207
+ int nframes = 0;
208
+ int lines = 0;
209
+ uintptr_t current = v_segfault_code_address(pc);
210
+ uintptr_t repeats = 0;
211
+ for (;;) {
212
+ uintptr_t next = 0;
213
+ if (fp >= lowest && fp <= hi - 2 * sizeof(uintptr_t) && fp % sizeof(uintptr_t) == 0) {
214
+ uintptr_t* record = (uintptr_t*)fp;
215
+ uintptr_t next_fp = record[0];
216
+ next = v_segfault_code_address(record[1]);
217
+ fp = next_fp > fp ? next_fp : 0;
218
+ }
219
+ if (next != 0 && next == current) {
220
+ repeats++;
221
+ continue;
222
+ }
223
+ if (current != 0) {
224
+ frames[nframes++] = (void*)current;
225
+ lines++;
226
+ if (repeats > 0 || nframes == V_STACK_OVERFLOW_MAX_LINES) {
227
+ v_segfault_flush_frames(frames, &nframes);
228
+ }
229
+ if (repeats > 0) {
230
+ v_segfault_write_str(" ... the frame above repeats ");
231
+ v_segfault_write_uint(repeats, 10);
232
+ v_segfault_write_str(" more times\n");
233
+ lines++;
234
+ }
235
+ }
236
+ if (next == 0) {
237
+ break;
238
+ }
239
+ if (lines >= V_STACK_OVERFLOW_MAX_LINES) {
240
+ v_segfault_flush_frames(frames, &nframes);
241
+ v_segfault_write_str(" ... more frames omitted\n");
242
+ break;
243
+ }
244
+ current = next;
245
+ repeats = 0;
246
+ }
247
+ v_segfault_flush_frames(frames, &nframes);
248
+ }
249
+
250
+ static int v_segfault_is_stack_overflow(siginfo_t* info) {
251
+ uintptr_t lo = 0;
252
+ uintptr_t hi = 0;
253
+ // si_code <= 0 means that the signal was sent by a process, not raised by a fault.
254
+ if (info == NULL || info->si_code <= 0 || !v_signal_stack_bounds(&lo, &hi) || lo == 0) {
255
+ return 0;
256
+ }
257
+ uintptr_t addr = (uintptr_t)info->si_addr;
258
+ uintptr_t lowest = lo > V_STACK_OVERFLOW_SLACK ? lo - V_STACK_OVERFLOW_SLACK : 0;
259
+ return addr >= lowest && addr < hi;
260
+ }
261
+
262
+ static void v_segfault_signal_handler(int sig, siginfo_t* info, void* context) {
263
+ if (v_segfault_is_stack_overflow(info)) {
264
+ v_segfault_write_str("V panic: stack overflow\n");
265
+ #if !defined(CUSTOM_DEFINE_no_backtrace)
266
+ uintptr_t lo = 0;
267
+ uintptr_t hi = 0;
268
+ if (v_signal_stack_bounds(&lo, &hi)) {
269
+ v_stack_overflow_backtrace(context, lo, hi);
270
+ }
271
+ #endif
272
+ _exit(128 + sig);
273
+ }
274
+ // A handler that was installed earlier (by TCC's `-bt` runtime, or by the GC for
275
+ // its write barrier) keeps handling every other fault.
276
+ int previous_index = sig == SIGBUS ? 1 : 0;
277
+ struct sigaction* previous = &v_segfault_previous[previous_index];
278
+ if (previous->sa_handler != SIG_DFL && previous->sa_handler != SIG_IGN
279
+ && (!(previous->sa_flags & SA_RESETHAND)
280
+ || v_segfault_consume_previous(previous_index))) {
281
+ if (previous->sa_flags & SA_SIGINFO) {
282
+ previous->sa_sigaction(sig, info, context);
283
+ } else {
284
+ previous->sa_handler(sig);
285
+ }
286
+ return;
287
+ }
288
+ if (sig == SIGSEGV && v_segfault_fallback != 0) {
289
+ #if defined(_VGCBOEHM) || defined(CUSTOM_DEFINE_gcboehm)
290
+ // The fallback allocates, and a collection started from the alternate signal
291
+ // stack would scan the gap between it and the thread's own stack.
292
+ GC_disable();
293
+ #endif
294
+ v_segfault_fallback(sig);
295
+ }
296
+ // Restore the default action, so that the process still terminates with `sig`.
297
+ struct sigaction dfl;
298
+ memset(&dfl, 0, sizeof(dfl));
299
+ dfl.sa_handler = SIG_DFL;
300
+ sigemptyset(&dfl.sa_mask);
301
+ sigaction(sig, &dfl, NULL);
302
+ raise(sig);
303
+ }
304
+
305
+ static size_t v_signal_stack_size(void) {
306
+ size_t size = 64 * 1024;
307
+ #if defined(_SC_MINSIGSTKSZ)
308
+ long min_size = sysconf(_SC_MINSIGSTKSZ);
309
+ if (min_size > 0 && (size_t)min_size + 32 * 1024 > size) {
310
+ size = (size_t)min_size + 32 * 1024;
311
+ }
312
+ #endif
313
+ return size;
314
+ }
315
+
316
+ // v_signal_stack_register gives the calling thread an alternate signal stack, unless
317
+ // it already has one.
318
+ static void v_signal_stack_register(uintptr_t lo, uintptr_t hi) {
319
+ stack_t old;
320
+ memset(&old, 0, sizeof(old));
321
+ if (sigaltstack(NULL, &old) != 0 || !(old.ss_flags & SS_DISABLE)) {
322
+ return;
323
+ }
324
+ size_t size = v_signal_stack_size();
325
+ #if defined(MAP_ANONYMOUS)
326
+ void* base = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
327
+ #else
328
+ void* base = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
329
+ #endif
330
+ if (base == MAP_FAILED) {
331
+ return;
332
+ }
333
+ uintptr_t* header = (uintptr_t*)base;
334
+ header[0] = V_SIGNAL_STACK_MAGIC;
335
+ header[1] = lo;
336
+ header[2] = hi;
337
+ header[3] = (uintptr_t)size;
338
+ stack_t ss;
339
+ memset(&ss, 0, sizeof(ss));
340
+ ss.ss_sp = base;
341
+ ss.ss_size = size;
342
+ ss.ss_flags = 0;
343
+ if (sigaltstack(&ss, NULL) != 0) {
344
+ munmap(base, size);
345
+ }
346
+ }
347
+
348
+ // v_segfault_save_previous stores the current action for `sig`. It reports false for
349
+ // an ignored signal, that is left alone. sa_handler and sa_sigaction share their
350
+ // storage, so SIG_DFL is checked through sa_handler, whatever sa_flags is: macOS keeps
351
+ // SA_SIGINFO in sa_flags across exec, while it resets the handler to SIG_DFL.
352
+ static int v_segfault_save_previous(int sig, struct sigaction* previous) {
353
+ memset(previous, 0, sizeof(*previous));
354
+ if (sigaction(sig, NULL, previous) != 0 || previous->sa_handler == SIG_IGN) {
355
+ return 0;
356
+ }
357
+ #if defined(__APPLE__)
358
+ // Darwin does not return SA_RESETHAND when querying an installed action. Keep
359
+ // existing callbacks under kernel control, so one-shot handlers stay one-shot.
360
+ if (previous->sa_handler != SIG_DFL) {
361
+ return 0;
362
+ }
363
+ #endif
364
+ return 1;
365
+ }
366
+
367
+ // v_segfault_install_signal must run after v_segfault_save_previous: V's handler calls
368
+ // the previous one directly, so it blocks the signals of the previous action's sa_mask.
369
+ // The Boehm GC, for example, blocks its stop-the-world signal in its write fault
370
+ // handler, and the heap gets corrupted when a collection interrupts that handler.
371
+ static void v_segfault_install_signal(int sig) {
372
+ struct sigaction sa;
373
+ memset(&sa, 0, sizeof(sa));
374
+ sa.sa_sigaction = v_segfault_signal_handler;
375
+ struct sigaction* previous = &v_segfault_previous[sig == SIGBUS ? 1 : 0];
376
+ int inherited_flags = SA_NODEFER | SA_RESTART;
377
+ #if defined(__TINYC__)
378
+ // With a one-shot previous handler, V's handler either reports a stack overflow and
379
+ // exits, or forwards the fault to that handler. Taking over SA_RESETHAND makes the
380
+ // kernel reset the signal to SIG_DFL, when it delivers it, so the previous handler
381
+ // still runs at most once, without an atomic exchange in C.
382
+ if (previous->sa_handler != SIG_DFL) {
383
+ inherited_flags |= SA_RESETHAND;
384
+ }
385
+ #endif
386
+ sa.sa_flags = SA_SIGINFO | SA_ONSTACK | (previous->sa_flags & inherited_flags);
387
+ sa.sa_mask = previous->sa_mask;
388
+ sigaction(sig, &sa, NULL);
389
+ }
390
+
391
+ // v_install_segfault_handler is called once, at the start of the main thread, from
392
+ // builtin_init. `main_argv` is the argv of C's main, which the startup code
393
+ // places above the frames of main on the initial stack.
394
+ V_SEGFAULT_HANDLER_SCOPE void v_install_segfault_handler(void* fallback, void* main_argv) {
395
+ // Sanitizers report stack overflows themselves; they are excluded at compile time.
396
+ int install_segv = v_segfault_save_previous(SIGSEGV, &v_segfault_previous[0]);
397
+ int install_bus = v_segfault_save_previous(SIGBUS, &v_segfault_previous[1]);
398
+ if (!install_segv && !install_bus) {
399
+ return;
400
+ }
401
+ v_segfault_fallback = (v_segfault_fallback_fn)fallback;
402
+ uintptr_t lo = 0;
403
+ uintptr_t hi = 0;
404
+ #if defined(__APPLE__)
405
+ pthread_t self = pthread_self();
406
+ hi = (uintptr_t)pthread_get_stackaddr_np(self);
407
+ size_t stack_size = pthread_get_stacksize_np(self);
408
+ lo = hi > stack_size ? hi - stack_size : 0;
409
+ (void)main_argv;
410
+ #else
411
+ char marker = 0;
412
+ hi = (uintptr_t)&marker;
413
+ struct rlimit limit;
414
+ memset(&limit, 0, sizeof(limit));
415
+ if (getrlimit(RLIMIT_STACK, &limit) == 0 && limit.rlim_cur != RLIM_INFINITY && (uintptr_t)limit.rlim_cur < hi) {
416
+ uintptr_t argv_addr = (uintptr_t)main_argv;
417
+ if (argv_addr > hi && argv_addr - hi < (uintptr_t)limit.rlim_cur) {
418
+ hi = argv_addr;
419
+ }
420
+ // The main thread stack can grow down to RLIMIT_STACK below its top, that is a
421
+ // bit above `hi`, so this estimate is at most a little too low.
422
+ lo = hi - (uintptr_t)limit.rlim_cur;
423
+ }
424
+ #endif
425
+ v_signal_stack_register(lo, hi);
426
+ if (install_segv) {
427
+ v_segfault_install_signal(SIGSEGV);
428
+ }
429
+ if (install_bus) {
430
+ v_segfault_install_signal(SIGBUS);
431
+ }
432
+ }
433
+
434
+ #else
435
+
436
+ V_SEGFAULT_HANDLER_SCOPE void v_install_segfault_handler(void* fallback, void* main_argv) {
437
+ (void)fallback;
438
+ (void)main_argv;
439
+ }
440
+
441
+ #endif
442
+ #undef V_SEGFAULT_HANDLER_SCOPE
443
+
444
+ #else
445
+
446
+ void v_install_segfault_handler(void* fallback, void* main_argv);
447
+
448
+ #endif
449
+ #endif
@@ -0,0 +1,52 @@
1
+ // Stack overflow handling must run before stack unwinding and needs reserved stack
2
+ // space on every thread. Other first-chance exceptions continue to their handlers.
3
+ #ifndef V_SEGFAULT_HANDLER_WINDOWS_H
4
+ #define V_SEGFAULT_HANDLER_WINDOWS_H
5
+
6
+ #include <windows.h>
7
+
8
+ #if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) || defined(__SANITIZE_HWADDRESS__)
9
+ #define V_SEGFAULT_HANDLER_SANITIZED 1
10
+ #elif defined(__has_feature)
11
+ #if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || __has_feature(memory_sanitizer) || __has_feature(hwaddress_sanitizer)
12
+ #define V_SEGFAULT_HANDLER_SANITIZED 1
13
+ #endif
14
+ #endif
15
+
16
+ typedef BOOL (WINAPI *v_windows_stack_guarantee_fn)(PULONG);
17
+
18
+ static inline void v_windows_set_stack_guarantee(void) {
19
+ // Bundled TCC's kernel32 import library omits this API even though its Windows
20
+ // headers declare it. Resolve the system export without changing that library.
21
+ v_windows_stack_guarantee_fn guarantee = (v_windows_stack_guarantee_fn)GetProcAddress(
22
+ GetModuleHandleW(L"kernel32.dll"), "SetThreadStackGuarantee");
23
+ if (guarantee) {
24
+ ULONG size = 64 * 1024;
25
+ guarantee(&size);
26
+ }
27
+ }
28
+
29
+ #if !defined(V_SEGFAULT_HANDLER_SANITIZED)
30
+ static inline LONG CALLBACK v_windows_stack_overflow_handler(EXCEPTION_POINTERS* exception) {
31
+ if (exception->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
32
+ return EXCEPTION_CONTINUE_SEARCH;
33
+ }
34
+ // Write directly to stderr without allocation, CRT buffering, or a backtrace.
35
+ DWORD written;
36
+ WriteFile(GetStdHandle(STD_ERROR_HANDLE), "V panic: stack overflow\n",
37
+ sizeof("V panic: stack overflow\n") - 1, &written, NULL);
38
+ // The stack is exhausted: do not run CRT or DLL cleanup on this thread.
39
+ TerminateProcess(GetCurrentProcess(), 1);
40
+ return EXCEPTION_CONTINUE_SEARCH;
41
+ }
42
+ #endif
43
+
44
+ static inline void v_install_windows_stack_overflow_handler(void) {
45
+ v_windows_set_stack_guarantee();
46
+ #if !defined(V_SEGFAULT_HANDLER_SANITIZED)
47
+ // Sanitizers report stack overflows themselves; do not intercept their faults.
48
+ AddVectoredExceptionHandler(1, v_windows_stack_overflow_handler);
49
+ #endif
50
+ }
51
+
52
+ #endif
@@ -0,0 +1,12 @@
1
+ #ifdef V_GCBOEHM_NATIVE
2
+ #if defined(__APPLE__) && !defined(GC_DARWIN_THREADS)
3
+ #define GC_DARWIN_THREADS 1
4
+ #endif
5
+ #if defined(__TINYC__) && defined(__linux__)
6
+ #include <gc/gc.h>
7
+ #else
8
+ #include <gc.h>
9
+ #endif
10
+ #endif
11
+ #define V_SYNC_THREAD_SCOPE
12
+ #include "thread_helper.h"
@@ -0,0 +1,96 @@
1
+ #ifndef V_SYNC_THREAD_HELPER_H
2
+ #define V_SYNC_THREAD_HELPER_H
3
+
4
+ #ifndef V_SYNC_THREAD_SCOPE
5
+ #define V_SYNC_THREAD_SCOPE static inline
6
+ #endif
7
+
8
+ #ifndef V_THREAD_STACK_SIZE
9
+ #define V_THREAD_STACK_SIZE 0
10
+ #endif
11
+
12
+ #ifdef _WIN32
13
+ #include <windows.h>
14
+
15
+ /* Boehm only scans threads it created or registered. gc.h redirects CreateThread to
16
+ * GC_CreateThread only when it precedes this header, so declare GC_CreateThread here
17
+ * for Boehm builds. A plain CreateThread thread aborts the next collection it triggers. */
18
+ #if (defined(_VGCBOEHM) || defined(CUSTOM_DEFINE_gcboehm)) && !defined(GC_H)
19
+ /* gc.h renames GC_CreateThread under GC_UNDERSCORE_STDCALL. Mirror that rename so the
20
+ * declaration matches the libgc export. */
21
+ #if defined(GC_UNDERSCORE_STDCALL)
22
+ #define GC_CreateThread _GC_CreateThread
23
+ #endif
24
+ HANDLE WINAPI GC_CreateThread(LPSECURITY_ATTRIBUTES, SIZE_T, LPTHREAD_START_ROUTINE,
25
+ LPVOID, DWORD, LPDWORD);
26
+ #endif
27
+ #if defined(_VGCBOEHM) || defined(CUSTOM_DEFINE_gcboehm)
28
+ #define v_sync_create_thread GC_CreateThread
29
+ #else
30
+ #define v_sync_create_thread CreateThread
31
+ #endif
32
+
33
+ typedef struct {
34
+ unsigned int (*start)(void *);
35
+ void *arg;
36
+ } v_sync_windows_thread_context;
37
+
38
+ static DWORD WINAPI v_sync_windows_thread_start(void *raw_context) {
39
+ v_sync_windows_thread_context *context = (v_sync_windows_thread_context *)raw_context;
40
+ unsigned int (*start)(void *) = context->start;
41
+ void *arg = context->arg;
42
+ HeapFree(GetProcessHeap(), 0, context);
43
+ return (DWORD)start(arg);
44
+ }
45
+
46
+ V_SYNC_THREAD_SCOPE int v_sync_thread_create_detached_with_stack(void *start, void *arg, size_t stack_size) {
47
+ v_sync_windows_thread_context *context = (v_sync_windows_thread_context *)HeapAlloc(
48
+ GetProcessHeap(), 0, sizeof(v_sync_windows_thread_context));
49
+ if (context == NULL) {
50
+ return ERROR_NOT_ENOUGH_MEMORY;
51
+ }
52
+ context->start = (unsigned int (*)(void *))start;
53
+ context->arg = arg;
54
+ HANDLE handle = v_sync_create_thread(NULL, stack_size, v_sync_windows_thread_start, context, 0, NULL);
55
+ if (handle == NULL) {
56
+ DWORD error = GetLastError();
57
+ HeapFree(GetProcessHeap(), 0, context);
58
+ return (int)error;
59
+ }
60
+ CloseHandle(handle);
61
+ return 0;
62
+ }
63
+ #else
64
+ #ifndef V_FASTC_NO_HEADERS
65
+ #include <pthread.h>
66
+ #include <stdlib.h>
67
+ #endif
68
+
69
+ V_SYNC_THREAD_SCOPE int v_sync_thread_create_detached_with_stack(void *start, void *arg, size_t stack_size) {
70
+ pthread_attr_t attr;
71
+ int rc = pthread_attr_init(&attr);
72
+ if (rc != 0) {
73
+ return rc;
74
+ }
75
+ if (stack_size != 0) {
76
+ rc = pthread_attr_setstacksize(&attr, stack_size);
77
+ }
78
+ if (rc == 0) {
79
+ rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
80
+ }
81
+ if (rc == 0) {
82
+ pthread_t thread;
83
+ rc = pthread_create(&thread, &attr, (void *(*)(void *))start, arg);
84
+ }
85
+ if (pthread_attr_destroy(&attr) != 0) {
86
+ abort();
87
+ }
88
+ return rc;
89
+ }
90
+ #endif
91
+
92
+ V_SYNC_THREAD_SCOPE int v_sync_thread_create_detached(void *start, void *arg) {
93
+ return v_sync_thread_create_detached_with_stack(start, arg, V_THREAD_STACK_SIZE);
94
+ }
95
+
96
+ #endif
@@ -0,0 +1,3 @@
1
+ #include "ticks_windows_api.h"
2
+ #define V_TIME_TICKS_SCOPE
3
+ #include "ticks_windows.h"
@@ -0,0 +1,31 @@
1
+ #ifndef V_TIME_TICKS_WINDOWS_H
2
+ #define V_TIME_TICKS_WINDOWS_H
3
+
4
+ #include <windows.h>
5
+
6
+ #ifndef V_TIME_TICKS_SCOPE
7
+ #define V_TIME_TICKS_SCOPE static inline
8
+ #endif
9
+
10
+ V_TIME_TICKS_SCOPE unsigned long long v_time_ticks_ms(void) {
11
+ typedef ULONGLONG (WINAPI *tick_count_fn)(void);
12
+ HMODULE kernel32 = GetModuleHandleA("kernel32.dll");
13
+ tick_count_fn tick_count = kernel32
14
+ ? (tick_count_fn)GetProcAddress(kernel32, "GetTickCount64")
15
+ : NULL;
16
+ if (tick_count) {
17
+ return tick_count();
18
+ }
19
+
20
+ // Older Windows versions do not export GetTickCount64. QPC is also 64 bit.
21
+ LARGE_INTEGER counter, frequency;
22
+ if (QueryPerformanceFrequency(&frequency) && frequency.QuadPart > 0
23
+ && QueryPerformanceCounter(&counter)) {
24
+ unsigned long long count = (unsigned long long)counter.QuadPart;
25
+ unsigned long long freq = (unsigned long long)frequency.QuadPart;
26
+ return (count / freq) * 1000ULL + (count % freq) * 1000ULL / freq;
27
+ }
28
+ return GetTickCount();
29
+ }
30
+
31
+ #endif