The best way to control Claude Code, Codex and more from any computer or phone

main
c 401 lines 10.4 KB
Raw
1 /*
2 * Copyright 2018 WebAssembly Community Group participants
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "wasm-rt-impl.h"
18
19 #include <assert.h>
20 #include <math.h>
21 #include <stdarg.h>
22 #include <stdbool.h>
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #if WASM_RT_INSTALL_SIGNAL_HANDLER && !defined(_WIN32)
29 #include <signal.h>
30 #include <unistd.h>
31 #endif
32
33 #ifdef _WIN32
34 #include <windows.h>
35 #else
36 #include <sys/mman.h>
37 #endif
38
39 #ifndef NDEBUG
40 #define DEBUG_PRINTF(...) fprintf(stderr, __VA_ARGS__);
41 #else
42 #define DEBUG_PRINTF(...)
43 #endif
44
45 #if WASM_RT_INSTALL_SIGNAL_HANDLER
46 static bool g_signal_handler_installed = false;
47 #ifdef _WIN32
48 static void* g_sig_handler_handle = 0;
49 #endif
50 #endif
51
52 #if WASM_RT_USE_SEGUE
53 bool wasm_rt_fsgsbase_inst_supported = false;
54 #ifdef __linux__
55 #include <sys/auxv.h>
56 #ifdef __GLIBC__
57 #include <gnu/libc-version.h>
58 #endif
59 #include <asm/prctl.h> // For ARCH_SET_GS
60 #include <sys/syscall.h> // For SYS_arch_prctl
61 #include <unistd.h> // For syscall
62 #ifndef HWCAP2_FSGSBASE
63 #define HWCAP2_FSGSBASE (1 << 1)
64 #endif
65 #elif defined(__FreeBSD__)
66 #include <machine/sysarch.h> // For amd64_set_gsbase etc.
67 #endif
68 #endif
69
70 #if WASM_RT_SEGUE_FREE_SEGMENT
71 WASM_RT_THREAD_LOCAL void* wasm_rt_last_segment_val = NULL;
72 #endif
73
74 #if WASM_RT_STACK_DEPTH_COUNT
75 WASM_RT_THREAD_LOCAL uint32_t wasm_rt_call_stack_depth;
76 WASM_RT_THREAD_LOCAL uint32_t wasm_rt_saved_call_stack_depth;
77 #elif WASM_RT_STACK_EXHAUSTION_HANDLER
78 static WASM_RT_THREAD_LOCAL void* g_alt_stack = NULL;
79 #endif
80
81 #ifndef WASM_RT_TRAP_HANDLER
82 WASM_RT_THREAD_LOCAL wasm_rt_jmp_buf g_wasm_rt_jmp_buf;
83 #endif
84
85 #ifdef WASM_RT_TRAP_HANDLER
86 extern void WASM_RT_TRAP_HANDLER(wasm_rt_trap_t code);
87 #endif
88
89 void wasm_rt_trap(wasm_rt_trap_t code) {
90 assert(code != WASM_RT_TRAP_NONE);
91 #if WASM_RT_STACK_DEPTH_COUNT
92 wasm_rt_call_stack_depth = wasm_rt_saved_call_stack_depth;
93 #endif
94
95 #ifdef WASM_RT_TRAP_HANDLER
96 WASM_RT_TRAP_HANDLER(code);
97 wasm_rt_unreachable();
98 #else
99 WASM_RT_LONGJMP(g_wasm_rt_jmp_buf, code);
100 #endif
101 }
102
103 #ifdef _WIN32
104
105 #if WASM_RT_INSTALL_SIGNAL_HANDLER
106
107 static LONG os_signal_handler(PEXCEPTION_POINTERS info) {
108 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
109 wasm_rt_trap(WASM_RT_TRAP_OOB);
110 } else if (info->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) {
111 wasm_rt_trap(WASM_RT_TRAP_EXHAUSTION);
112 }
113 return EXCEPTION_CONTINUE_SEARCH;
114 }
115
116 static void os_install_signal_handler(void) {
117 g_sig_handler_handle =
118 AddVectoredExceptionHandler(1 /* CALL_FIRST */, os_signal_handler);
119 }
120
121 static void os_cleanup_signal_handler(void) {
122 RemoveVectoredExceptionHandler(g_sig_handler_handle);
123 }
124
125 #endif
126
127 #else
128
129 #if WASM_RT_INSTALL_SIGNAL_HANDLER
130 static void os_signal_handler(int sig, siginfo_t* si, void* unused) {
131 if (si->si_code == SEGV_ACCERR) {
132 wasm_rt_trap(WASM_RT_TRAP_OOB);
133 } else {
134 wasm_rt_trap(WASM_RT_TRAP_EXHAUSTION);
135 }
136 }
137
138 static void os_install_signal_handler(void) {
139 struct sigaction sa;
140 memset(&sa, '\0', sizeof(sa));
141 sa.sa_flags = SA_SIGINFO;
142 #if WASM_RT_STACK_EXHAUSTION_HANDLER
143 sa.sa_flags |= SA_ONSTACK;
144 #endif
145 sigemptyset(&sa.sa_mask);
146 sa.sa_sigaction = os_signal_handler;
147
148 /* Install SIGSEGV and SIGBUS handlers, since macOS seems to use SIGBUS. */
149 if (sigaction(SIGSEGV, &sa, NULL) != 0 || sigaction(SIGBUS, &sa, NULL) != 0) {
150 perror("sigaction failed");
151 abort();
152 }
153 }
154
155 static void os_cleanup_signal_handler(void) {
156 /* Undo what was done in os_install_signal_handler */
157 struct sigaction sa;
158 memset(&sa, '\0', sizeof(sa));
159 sa.sa_handler = SIG_DFL;
160 if (sigaction(SIGSEGV, &sa, NULL) != 0 || sigaction(SIGBUS, &sa, NULL)) {
161 perror("sigaction failed");
162 abort();
163 }
164 }
165 #endif
166
167 #if WASM_RT_STACK_EXHAUSTION_HANDLER
168 static bool os_has_altstack_installed() {
169 /* check for altstack already in place */
170 stack_t ss;
171 if (sigaltstack(NULL, &ss) != 0) {
172 perror("os_has_altstack_installed: sigaltstack failed");
173 abort();
174 }
175
176 return !(ss.ss_flags & SS_DISABLE);
177 }
178
179 /* These routines set up an altstack to handle SIGSEGV from stack overflow. */
180 static void os_allocate_and_install_altstack(void) {
181 /* verify altstack not already allocated */
182 assert(!g_alt_stack &&
183 "wasm-rt error: tried to re-allocate thread-local alternate stack");
184
185 /* We could check and warn if an altstack is already installed, but some
186 * sanitizers install their own altstack, so this warning would fire
187 * spuriously and break the test outputs. */
188
189 /* allocate altstack */
190 g_alt_stack = malloc(SIGSTKSZ);
191 if (g_alt_stack == NULL) {
192 perror("malloc failed");
193 abort();
194 }
195
196 /* install altstack */
197 stack_t ss;
198 ss.ss_sp = g_alt_stack;
199 ss.ss_flags = 0;
200 ss.ss_size = SIGSTKSZ;
201 if (sigaltstack(&ss, NULL) != 0) {
202 perror("os_allocate_and_install_altstack: sigaltstack failed");
203 abort();
204 }
205 }
206
207 static void os_disable_and_deallocate_altstack(void) {
208 /* in debug build, verify altstack allocated */
209 assert(g_alt_stack &&
210 "wasm-rt error: thread-local alternate stack not allocated");
211
212 /* verify altstack was still in place */
213 stack_t ss;
214 if (sigaltstack(NULL, &ss) != 0) {
215 perror("os_disable_and_deallocate_altstack: sigaltstack failed");
216 abort();
217 }
218
219 if ((!g_alt_stack) || (ss.ss_flags & SS_DISABLE) ||
220 (ss.ss_sp != g_alt_stack) || (ss.ss_size != SIGSTKSZ)) {
221 DEBUG_PRINTF(
222 "wasm-rt warning: alternate stack was modified unexpectedly\n");
223 return;
224 }
225
226 assert(!(ss.ss_flags & SS_ONSTACK) &&
227 "attempt to deallocate altstack while in use");
228
229 /* disable and free */
230 ss.ss_flags = SS_DISABLE;
231 if (sigaltstack(&ss, NULL) != 0) {
232 perror("sigaltstack disable failed");
233 abort();
234 }
235 assert(!os_has_altstack_installed());
236 free(g_alt_stack);
237 g_alt_stack = NULL;
238 }
239 #endif
240
241 #endif
242
243 #if WASM_RT_USE_SEGUE && defined(__FreeBSD__)
244 static void call_cpuid(uint64_t* rax,
245 uint64_t* rbx,
246 uint64_t* rcx,
247 uint64_t* rdx) {
248 __asm__ volatile(
249 "cpuid"
250 : "=a"(*rax), "=b"(*rbx), "=c"(*rcx), "=d"(*rdx) // output operands
251 : "a"(*rax), "c"(*rcx) // input operands
252 );
253 }
254 #endif
255
256 void wasm_rt_init(void) {
257 wasm_rt_init_thread();
258 #if WASM_RT_INSTALL_SIGNAL_HANDLER
259 if (!g_signal_handler_installed) {
260 g_signal_handler_installed = true;
261 os_install_signal_handler();
262 }
263 #endif
264
265 #if WASM_RT_USE_SEGUE
266 #if defined(__linux__) && defined(__GLIBC__) && __GLIBC__ >= 2 && \
267 __GLIBC_MINOR__ >= 18
268 // Check for support for userspace wrgsbase instructions
269 unsigned long val = getauxval(AT_HWCAP2);
270 wasm_rt_fsgsbase_inst_supported = val & HWCAP2_FSGSBASE;
271 #elif defined(__FreeBSD__)
272 // FreeBSD enables fsgsbase on the newer kernels if the hardware supports it.
273 // We just need to check if the hardware supports it by querying the correct
274 // cpuid leaf.
275 uint64_t rax, rbx, rcx, rdx;
276 rax = 0;
277 call_cpuid(&rax, &rbx, &rcx, &rdx);
278
279 if (rax > 7) {
280 rax = 7;
281 rcx = 0;
282 call_cpuid(&rax, &rbx, &rcx, &rdx);
283 if (rbx & 0x1) {
284 wasm_rt_fsgsbase_inst_supported = true;
285 }
286 }
287 #endif
288 #endif
289
290 assert(wasm_rt_is_initialized());
291 }
292
293 bool wasm_rt_is_initialized(void) {
294 #if WASM_RT_STACK_EXHAUSTION_HANDLER
295 if (!os_has_altstack_installed()) {
296 return false;
297 }
298 #endif
299 #if WASM_RT_INSTALL_SIGNAL_HANDLER
300 return g_signal_handler_installed;
301 #else
302 return true;
303 #endif
304 }
305
306 void wasm_rt_free(void) {
307 assert(wasm_rt_is_initialized());
308 #if WASM_RT_INSTALL_SIGNAL_HANDLER
309 os_cleanup_signal_handler();
310 g_signal_handler_installed = false;
311 #endif
312 wasm_rt_free_thread();
313 }
314
315 void wasm_rt_init_thread(void) {
316 #if WASM_RT_STACK_EXHAUSTION_HANDLER
317 os_allocate_and_install_altstack();
318 #endif
319 }
320
321 void wasm_rt_free_thread(void) {
322 #if WASM_RT_STACK_EXHAUSTION_HANDLER
323 os_disable_and_deallocate_altstack();
324 #endif
325 }
326
327 #if WASM_RT_USE_SEGUE
328 void wasm_rt_syscall_set_segue_base(void* base) {
329 int error_code = 0;
330 #ifdef __linux__
331 error_code = syscall(SYS_arch_prctl, ARCH_SET_GS, base);
332 #elif defined(__FreeBSD__)
333 error_code = amd64_set_gsbase(base);
334 #else
335 #error "Unknown platform"
336 #endif
337 if (error_code != 0) {
338 perror("wasm_rt_syscall_set_segue_base error");
339 abort();
340 }
341 }
342 void* wasm_rt_syscall_get_segue_base() {
343 void* base;
344 int error_code = 0;
345 #ifdef __linux__
346 error_code = syscall(SYS_arch_prctl, ARCH_GET_GS, &base);
347 #elif defined(__FreeBSD__)
348 error_code = amd64_get_gsbase(&base);
349 #else
350 #error "Unknown platform"
351 #endif
352 if (error_code != 0) {
353 perror("wasm_rt_syscall_get_segue_base error");
354 abort();
355 }
356 return base;
357 }
358 #endif
359
360 // Include table operations for funcref
361 #define WASM_RT_TABLE_OPS_FUNCREF
362 #include "wasm-rt-impl-tableops.inc"
363 #undef WASM_RT_TABLE_OPS_FUNCREF
364
365 // Include table operations for externref
366 #define WASM_RT_TABLE_OPS_EXTERNREF
367 #include "wasm-rt-impl-tableops.inc"
368 #undef WASM_RT_TABLE_OPS_EXTERNREF
369
370 const char* wasm_rt_strerror(wasm_rt_trap_t trap) {
371 switch (trap) {
372 case WASM_RT_TRAP_NONE:
373 return "No error";
374 case WASM_RT_TRAP_OOB:
375 #if WASM_RT_MERGED_OOB_AND_EXHAUSTION_TRAPS
376 return "Out-of-bounds access in linear memory or a table, or call stack "
377 "exhausted";
378 #else
379 return "Out-of-bounds access in linear memory or a table";
380 case WASM_RT_TRAP_EXHAUSTION:
381 return "Call stack exhausted";
382 #endif
383 case WASM_RT_TRAP_INT_OVERFLOW:
384 return "Integer overflow on divide or truncation";
385 case WASM_RT_TRAP_DIV_BY_ZERO:
386 return "Integer divide by zero";
387 case WASM_RT_TRAP_INVALID_CONVERSION:
388 return "Conversion from NaN to integer";
389 case WASM_RT_TRAP_UNREACHABLE:
390 return "Unreachable instruction executed";
391 case WASM_RT_TRAP_CALL_INDIRECT:
392 return "Invalid call_indirect or return_call_indirect";
393 case WASM_RT_TRAP_UNCAUGHT_EXCEPTION:
394 return "Uncaught exception";
395 case WASM_RT_TRAP_UNALIGNED:
396 return "Unaligned atomic memory access";
397 case WASM_RT_TRAP_NULL_REF:
398 return "Null reference";
399 }
400 return "invalid trap code";
401 }