Debian Codegraph @

js/src/wasm/WasmSignalHandlers.cpp

raw ◀ ▶
1 Debian patch touch this file
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 *
4 * Copyright 2014 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "wasm/WasmSignalHandlers.h"
20
21 #include "mozilla/Casting.h"
22 #include "mozilla/ThreadLocal.h"
23
24 #include "threading/Thread.h"
25 #include "vm/JitActivation.h" // js::jit::JitActivation
26 #include "vm/Realm.h"
27 #include "vm/Runtime.h"
28 #include "wasm/WasmCode.h"
29 #include "wasm/WasmInstance.h"
30
31 #if defined(XP_WIN)
32 # include <winternl.h> // must include before util/WindowsWrapper.h's `#undef`s
33 # include "util/WindowsWrapper.h"
34 #elif defined(XP_DARWIN)
35 # include <mach/exc.h>
36 # include <mach/mach.h>
37 #elif !defined(__wasi__)
38 # include <signal.h>
39 #endif
40
41 using namespace js;
42 using namespace js::wasm;
43
44 #if !defined(JS_CODEGEN_NONE)
45
46 // =============================================================================
47 // This following pile of macros and includes defines the ToRegisterState() and
48 // the ContextTo{PC,FP,SP,LR}() functions from the (highly) platform-specific
49 // CONTEXT struct which is provided to the signal handler.
50 // =============================================================================
51
52 # if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
53 # include <sys/ucontext.h> // for ucontext_t, mcontext_t
54 # endif
55
56 # if defined(__x86_64__)
57 # if defined(__DragonFly__)
58 # include <machine/npx.h> // for union savefpu
59 # elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \
60 defined(__NetBSD__) || defined(__OpenBSD__)
61 # include <machine/fpu.h> // for struct savefpu/fxsave64
62 # endif
63 # endif
64
65 # if defined(XP_WIN)
66 # define EIP_sig(p) ((p)->Eip)
67 # define EBP_sig(p) ((p)->Ebp)
68 # define ESP_sig(p) ((p)->Esp)
69 # define RIP_sig(p) ((p)->Rip)
70 # define RSP_sig(p) ((p)->Rsp)
71 # define RBP_sig(p) ((p)->Rbp)
72 # define R11_sig(p) ((p)->R11)
73 # define R13_sig(p) ((p)->R13)
74 # define R14_sig(p) ((p)->R14)
75 # define R15_sig(p) ((p)->R15)
76 # define EPC_sig(p) ((p)->Pc)
77 # define RFP_sig(p) ((p)->Fp)
78 # define R31_sig(p) ((p)->Sp)
79 # define RLR_sig(p) ((p)->Lr)
80 # elif defined(__OpenBSD__)
81 # define EIP_sig(p) ((p)->sc_eip)
82 # define EBP_sig(p) ((p)->sc_ebp)
83 # define ESP_sig(p) ((p)->sc_esp)
84 # define RIP_sig(p) ((p)->sc_rip)
85 # define RSP_sig(p) ((p)->sc_rsp)
86 # define RBP_sig(p) ((p)->sc_rbp)
87 # define R11_sig(p) ((p)->sc_r11)
88 # if defined(__arm__)
89 # define R13_sig(p) ((p)->sc_usr_sp)
90 # define R14_sig(p) ((p)->sc_usr_lr)
91 # define R15_sig(p) ((p)->sc_pc)
92 # else
93 # define R13_sig(p) ((p)->sc_r13)
94 # define R14_sig(p) ((p)->sc_r14)
95 # define R15_sig(p) ((p)->sc_r15)
96 # endif
97 # if defined(__aarch64__)
98 # define EPC_sig(p) ((p)->sc_elr)
99 # define RFP_sig(p) ((p)->sc_x[29])
100 # define RLR_sig(p) ((p)->sc_lr)
101 # define R31_sig(p) ((p)->sc_sp)
102 # endif
103 # if defined(__mips__)
104 # define EPC_sig(p) ((p)->sc_pc)
105 # define RFP_sig(p) ((p)->sc_regs[30])
106 # endif
107 # if defined(__ppc64__) || defined(__PPC64__) || defined(__ppc64le__) || \
108 defined(__PPC64LE__)
109 # define R01_sig(p) ((p)->sc_frame.fixreg[1])
110 # define R32_sig(p) ((p)->sc_frame.srr0)
111 # endif
•112 # elif defined(__linux__) || defined(__sun) || defined(__GNU__)
113 # if defined(__linux__)
114 # define EIP_sig(p) ((p)->uc_mcontext.gregs[REG_EIP])
115 # define EBP_sig(p) ((p)->uc_mcontext.gregs[REG_EBP])
116 # define ESP_sig(p) ((p)->uc_mcontext.gregs[REG_ESP])
117 # else
118 # define EIP_sig(p) ((p)->uc_mcontext.gregs[REG_PC])
119 # define EBP_sig(p) ((p)->uc_mcontext.gregs[REG_EBP])
120 # define ESP_sig(p) ((p)->uc_mcontext.gregs[REG_ESP])
121 # endif
122 # define RIP_sig(p) ((p)->uc_mcontext.gregs[REG_RIP])
123 # define RSP_sig(p) ((p)->uc_mcontext.gregs[REG_RSP])
124 # define RBP_sig(p) ((p)->uc_mcontext.gregs[REG_RBP])
125 # if defined(__linux__) && defined(__arm__)
126 # define R11_sig(p) ((p)->uc_mcontext.arm_fp)
127 # define R13_sig(p) ((p)->uc_mcontext.arm_sp)
128 # define R14_sig(p) ((p)->uc_mcontext.arm_lr)
129 # define R15_sig(p) ((p)->uc_mcontext.arm_pc)
130 # else
131 # define R11_sig(p) ((p)->uc_mcontext.gregs[REG_R11])
132 # define R13_sig(p) ((p)->uc_mcontext.gregs[REG_R13])
133 # define R14_sig(p) ((p)->uc_mcontext.gregs[REG_R14])
134 # define R15_sig(p) ((p)->uc_mcontext.gregs[REG_R15])
135 # endif
136 # if defined(__linux__) && defined(__aarch64__)
137 # define EPC_sig(p) ((p)->uc_mcontext.pc)
138 # define RFP_sig(p) ((p)->uc_mcontext.regs[29])
139 # define RLR_sig(p) ((p)->uc_mcontext.regs[30])
140 # define R31_sig(p) ((p)->uc_mcontext.sp)
141 # endif
142 # if defined(__linux__) && defined(__mips__)
143 # define EPC_sig(p) ((p)->uc_mcontext.pc)
144 # define RFP_sig(p) ((p)->uc_mcontext.gregs[30])
145 # define RSP_sig(p) ((p)->uc_mcontext.gregs[29])
146 # define R31_sig(p) ((p)->uc_mcontext.gregs[31])
147 # endif
148 # if defined(__linux__) && (defined(__sparc__) && defined(__arch64__))
149 # define PC_sig(p) ((p)->uc_mcontext.mc_gregs[MC_PC])
150 # define FP_sig(p) ((p)->uc_mcontext.mc_fp)
151 # define SP_sig(p) ((p)->uc_mcontext.mc_i7)
152 # endif
153 # if defined(__linux__) && (defined(__ppc64__) || defined(__PPC64__) || \
154 defined(__ppc64le__) || defined(__PPC64LE__))
155 # define R01_sig(p) ((p)->uc_mcontext.gp_regs[1])
156 # define R32_sig(p) ((p)->uc_mcontext.gp_regs[32])
157 # endif
158 # if defined(__linux__) && defined(__loongarch__)
159 # define EPC_sig(p) ((p)->uc_mcontext.__pc)
160 # define RRA_sig(p) ((p)->uc_mcontext.__gregs[1])
161 # define R03_sig(p) ((p)->uc_mcontext.__gregs[3])
162 # define RFP_sig(p) ((p)->uc_mcontext.__gregs[22])
163 # endif
164 # if defined(__linux__) && defined(__riscv)
165 # define RPC_sig(p) ((p)->uc_mcontext.__gregs[REG_PC])
166 # define RRA_sig(p) ((p)->uc_mcontext.__gregs[REG_RA])
167 # define RFP_sig(p) ((p)->uc_mcontext.__gregs[REG_S0])
168 # define R02_sig(p) ((p)->uc_mcontext.__gregs[REG_SP])
169 # endif
170 # if defined(__sun__) && defined(__sparc__)
171 # define PC_sig(p) ((p)->uc_mcontext.gregs[REG_PC])
172 # define FP_sig(p) ((p)->uc_mcontext.gregs[REG_FPRS])
173 # define SP_sig(p) ((p)->uc_mcontext.gregs[REG_SP])
174 # endif
175 # elif defined(__NetBSD__)
176 # define EIP_sig(p) ((p)->uc_mcontext.__gregs[_REG_EIP])
177 # define EBP_sig(p) ((p)->uc_mcontext.__gregs[_REG_EBP])
178 # define ESP_sig(p) ((p)->uc_mcontext.__gregs[_REG_ESP])
179 # define RIP_sig(p) ((p)->uc_mcontext.__gregs[_REG_RIP])
180 # define RSP_sig(p) ((p)->uc_mcontext.__gregs[_REG_RSP])
181 # define RBP_sig(p) ((p)->uc_mcontext.__gregs[_REG_RBP])
182 # define R11_sig(p) ((p)->uc_mcontext.__gregs[_REG_R11])
183 # define R13_sig(p) ((p)->uc_mcontext.__gregs[_REG_R13])
184 # define R14_sig(p) ((p)->uc_mcontext.__gregs[_REG_R14])
185 # define R15_sig(p) ((p)->uc_mcontext.__gregs[_REG_R15])
186 # if defined(__aarch64__)
187 # define EPC_sig(p) ((p)->uc_mcontext.__gregs[_REG_PC])
188 # define RFP_sig(p) ((p)->uc_mcontext.__gregs[_REG_X29])
189 # define RLR_sig(p) ((p)->uc_mcontext.__gregs[_REG_X30])
190 # define R31_sig(p) ((p)->uc_mcontext.__gregs[_REG_SP])
191 # endif
192 # if defined(__mips__)
193 # define EPC_sig(p) ((p)->uc_mcontext.__gregs[_REG_EPC])
194 # define RFP_sig(p) ((p)->uc_mcontext.__gregs[_REG_S8])
195 # endif
196 # if defined(__ppc64__) || defined(__PPC64__) || defined(__ppc64le__) || \
197 defined(__PPC64LE__)
198 # define R01_sig(p) ((p)->uc_mcontext.__gregs[_REG_R1])
199 # define R32_sig(p) ((p)->uc_mcontext.__gregs[_REG_PC])
200 # endif
201 # elif defined(__DragonFly__) || defined(__FreeBSD__) || \
202 defined(__FreeBSD_kernel__)
203 # define EIP_sig(p) ((p)->uc_mcontext.mc_eip)
204 # define EBP_sig(p) ((p)->uc_mcontext.mc_ebp)
205 # define ESP_sig(p) ((p)->uc_mcontext.mc_esp)
206 # define RIP_sig(p) ((p)->uc_mcontext.mc_rip)
207 # define RSP_sig(p) ((p)->uc_mcontext.mc_rsp)
208 # define RBP_sig(p) ((p)->uc_mcontext.mc_rbp)
209 # if defined(__FreeBSD__) && defined(__arm__)
210 # define R11_sig(p) ((p)->uc_mcontext.__gregs[_REG_R11])
211 # define R13_sig(p) ((p)->uc_mcontext.__gregs[_REG_R13])
212 # define R14_sig(p) ((p)->uc_mcontext.__gregs[_REG_R14])
213 # define R15_sig(p) ((p)->uc_mcontext.__gregs[_REG_R15])
214 # else
215 # define R11_sig(p) ((p)->uc_mcontext.mc_r11)
216 # define R13_sig(p) ((p)->uc_mcontext.mc_r13)
217 # define R14_sig(p) ((p)->uc_mcontext.mc_r14)
218 # define R15_sig(p) ((p)->uc_mcontext.mc_r15)
219 # endif
220 # if defined(__FreeBSD__) && defined(__aarch64__)
221 # define EPC_sig(p) ((p)->uc_mcontext.mc_gpregs.gp_elr)
222 # define RFP_sig(p) ((p)->uc_mcontext.mc_gpregs.gp_x[29])
223 # define RLR_sig(p) ((p)->uc_mcontext.mc_gpregs.gp_lr)
224 # define R31_sig(p) ((p)->uc_mcontext.mc_gpregs.gp_sp)
225 # endif
226 # if defined(__FreeBSD__) && defined(__mips__)
227 # define EPC_sig(p) ((p)->uc_mcontext.mc_pc)
228 # define RFP_sig(p) ((p)->uc_mcontext.mc_regs[30])
229 # endif
230 # if defined(__FreeBSD__) && (defined(__ppc64__) || defined(__PPC64__) || \
231 defined(__ppc64le__) || defined(__PPC64LE__))
232 # define R01_sig(p) ((p)->uc_mcontext.mc_gpr[1])
233 # define R32_sig(p) ((p)->uc_mcontext.mc_srr0)
234 # endif
235 # elif defined(XP_DARWIN)
236 # define EIP_sig(p) ((p)->thread.uts.ts32.__eip)
237 # define EBP_sig(p) ((p)->thread.uts.ts32.__ebp)
238 # define ESP_sig(p) ((p)->thread.uts.ts32.__esp)
239 # define RIP_sig(p) ((p)->thread.__rip)
240 # define RBP_sig(p) ((p)->thread.__rbp)
241 # define RSP_sig(p) ((p)->thread.__rsp)
242 # define R11_sig(p) ((p)->thread.__r[11])
243 # define R13_sig(p) ((p)->thread.__sp)
244 # define R14_sig(p) ((p)->thread.__lr)
245 # define R15_sig(p) ((p)->thread.__pc)
246 # define EPC_sig(p) ((p)->thread.__pc)
247 # define RFP_sig(p) ((p)->thread.__fp)
248 # define R31_sig(p) ((p)->thread.__sp)
249 # define RLR_sig(p) ((p)->thread.__lr)
250 # else
251 # error \
252 "Don't know how to read/write to the thread state via the mcontext_t."
253 # endif
254
255 # if defined(ANDROID)
256 // Not all versions of the Android NDK define ucontext_t or mcontext_t.
257 // Detect this and provide custom but compatible definitions. Note that these
258 // follow the GLibc naming convention to access register values from
259 // mcontext_t.
260 //
261 // See: https://chromiumcodereview.appspot.com/10829122/
262 // See: http://code.google.com/p/android/issues/detail?id=34784
263 # if !defined(__BIONIC_HAVE_UCONTEXT_T)
264 # if defined(__arm__)
265
266 // GLibc on ARM defines mcontext_t has a typedef for 'struct sigcontext'.
267 // Old versions of the C library <signal.h> didn't define the type.
268 # if !defined(__BIONIC_HAVE_STRUCT_SIGCONTEXT)
269 # include <asm/sigcontext.h>
270 # endif
271
272 typedef struct sigcontext mcontext_t;
273
274 typedef struct ucontext {
275 uint32_t uc_flags;
276 struct ucontext* uc_link;
277 stack_t uc_stack;
278 mcontext_t uc_mcontext;
279 // Other fields are not used so don't define them here.
280 } ucontext_t;
281
282 # elif defined(__mips__)
283
284 typedef struct {
285 uint32_t regmask;
286 uint32_t status;
287 uint64_t pc;
288 uint64_t gregs[32];
289 uint64_t fpregs[32];
290 uint32_t acx;
291 uint32_t fpc_csr;
292 uint32_t fpc_eir;
293 uint32_t used_math;
294 uint32_t dsp;
295 uint64_t mdhi;
296 uint64_t mdlo;
297 uint32_t hi1;
298 uint32_t lo1;
299 uint32_t hi2;
300 uint32_t lo2;
301 uint32_t hi3;
302 uint32_t lo3;
303 } mcontext_t;
304
305 typedef struct ucontext {
306 uint32_t uc_flags;
307 struct ucontext* uc_link;
308 stack_t uc_stack;
309 mcontext_t uc_mcontext;
310 // Other fields are not used so don't define them here.
311 } ucontext_t;
312
313 # elif defined(__loongarch64)
314
315 typedef struct {
316 uint64_t pc;
317 uint64_t gregs[32];
318 uint64_t fpregs[32];
319 uint32_t fpc_csr;
320 } mcontext_t;
321
322 typedef struct ucontext {
323 uint32_t uc_flags;
324 struct ucontext* uc_link;
325 stack_t uc_stack;
326 mcontext_t uc_mcontext;
327 // Other fields are not used so don't define them here.
328 } ucontext_t;
329
330 # elif defined(__i386__)
331 // x86 version for Android.
332 typedef struct {
333 uint32_t gregs[19];
334 void* fpregs;
335 uint32_t oldmask;
336 uint32_t cr2;
337 } mcontext_t;
338
339 typedef uint32_t kernel_sigset_t[2]; // x86 kernel uses 64-bit signal masks
340 typedef struct ucontext {
341 uint32_t uc_flags;
342 struct ucontext* uc_link;
343 stack_t uc_stack;
344 mcontext_t uc_mcontext;
345 // Other fields are not used by V8, don't define them here.
346 } ucontext_t;
347 enum { REG_EIP = 14 };
348 # endif // defined(__i386__)
349 # endif // !defined(__BIONIC_HAVE_UCONTEXT_T)
350 # endif // defined(ANDROID)
351
352 # if defined(XP_DARWIN)
353 # if defined(__x86_64__)
354 struct macos_x64_context {
355 x86_thread_state64_t thread;
356 x86_float_state64_t float_;
357 };
358 # define CONTEXT macos_x64_context
359 # elif defined(__i386__)
360 struct macos_x86_context {
361 x86_thread_state_t thread;
362 x86_float_state_t float_;
363 };
364 # define CONTEXT macos_x86_context
365 # elif defined(__arm__)
366 struct macos_arm_context {
367 arm_thread_state_t thread;
368 arm_neon_state_t float_;
369 };
370 # define CONTEXT macos_arm_context
371 # elif defined(__aarch64__)
372 struct macos_aarch64_context {
373 arm_thread_state64_t thread;
374 arm_neon_state64_t float_;
375 };
376 # define CONTEXT macos_aarch64_context
377 # else
378 # error Unsupported architecture
379 # endif
380 # elif !defined(XP_WIN)
381 # define CONTEXT ucontext_t
382 # endif
383
384 # if defined(_M_X64) || defined(__x86_64__)
385 # define PC_sig(p) RIP_sig(p)
386 # define FP_sig(p) RBP_sig(p)
387 # define SP_sig(p) RSP_sig(p)
388 # elif defined(_M_IX86) || defined(__i386__)
389 # define PC_sig(p) EIP_sig(p)
390 # define FP_sig(p) EBP_sig(p)
391 # define SP_sig(p) ESP_sig(p)
392 # elif defined(__arm__)
393 # define FP_sig(p) R11_sig(p)
394 # define SP_sig(p) R13_sig(p)
395 # define LR_sig(p) R14_sig(p)
396 # define PC_sig(p) R15_sig(p)
397 # elif defined(_M_ARM64) || defined(__aarch64__)
398 # define PC_sig(p) EPC_sig(p)
399 # define FP_sig(p) RFP_sig(p)
400 # define SP_sig(p) R31_sig(p)
401 # define LR_sig(p) RLR_sig(p)
402 # elif defined(__mips__)
403 # define PC_sig(p) EPC_sig(p)
404 # define FP_sig(p) RFP_sig(p)
405 # define SP_sig(p) RSP_sig(p)
406 # define LR_sig(p) R31_sig(p)
407 # elif defined(__ppc64__) || defined(__PPC64__) || defined(__ppc64le__) || \
408 defined(__PPC64LE__)
409 # define PC_sig(p) R32_sig(p)
410 # define SP_sig(p) R01_sig(p)
411 # define FP_sig(p) R01_sig(p)
412 # elif defined(__loongarch__)
413 # define PC_sig(p) EPC_sig(p)
414 # define FP_sig(p) RFP_sig(p)
415 # define SP_sig(p) R03_sig(p)
416 # define LR_sig(p) RRA_sig(p)
417 # elif defined(__riscv)
418 # define PC_sig(p) RPC_sig(p)
419 # define FP_sig(p) RFP_sig(p)
420 # define SP_sig(p) R02_sig(p)
421 # define LR_sig(p) RRA_sig(p)
422 # endif
423
424 static void SetContextPC(CONTEXT* context, uint8_t* pc) {
425 # ifdef PC_sig
426 *mozilla::BitwiseCast<uint8_t**>(&PC_sig(context)) = pc;
427 # else
428 MOZ_CRASH();
429 # endif
430 }
431
432 static uint8_t* ContextToPC(CONTEXT* context) {
433 # ifdef PC_sig
434 return mozilla::BitwiseCast<uint8_t*>(PC_sig(context));
435 # else
436 MOZ_CRASH();
437 # endif
438 }
439
440 static uint8_t* ContextToFP(CONTEXT* context) {
441 # ifdef FP_sig
442 return mozilla::BitwiseCast<uint8_t*>(FP_sig(context));
443 # else
444 MOZ_CRASH();
445 # endif
446 }
447
448 static uint8_t* ContextToSP(CONTEXT* context) {
449 # ifdef SP_sig
450 return mozilla::BitwiseCast<uint8_t*>(SP_sig(context));
451 # else
452 MOZ_CRASH();
453 # endif
454 }
455
456 # if defined(__arm__) || defined(__aarch64__) || defined(__mips__) || \
457 defined(__loongarch__) || defined(__riscv)
458 static uint8_t* ContextToLR(CONTEXT* context) {
459 # ifdef LR_sig
460 return mozilla::BitwiseCast<uint8_t*>(LR_sig(context));
461 # else
462 MOZ_CRASH();
463 # endif
464 }
465 # endif
466
467 static JS::ProfilingFrameIterator::RegisterState ToRegisterState(
468 CONTEXT* context) {
469 JS::ProfilingFrameIterator::RegisterState state;
470 state.fp = ContextToFP(context);
471 state.pc = ContextToPC(context);
472 state.sp = ContextToSP(context);
473 # if defined(__arm__) || defined(__aarch64__) || defined(__mips__) || \
474 defined(__loongarch__) || defined(__riscv)
475 state.lr = ContextToLR(context);
476 # else
477 state.lr = (void*)UINTPTR_MAX;
478 # endif
479 return state;
480 }
481
482 // =============================================================================
483 // All signals/exceptions funnel down to this one trap-handling function which
484 // tests whether the pc is in a wasm module and, if so, whether there is
485 // actually a trap expected at this pc. These tests both avoid real bugs being
486 // silently converted to wasm traps and provides the trapping wasm bytecode
487 // offset we need to report in the error.
488 //
489 // Crashing inside wasm trap handling (due to a bug in trap handling or exposed
490 // during trap handling) must be reported like a normal crash, not cause the
491 // crash report to be lost. On Windows and non-Mach Unix, a crash during the
492 // handler reenters the handler, possibly repeatedly until exhausting the stack,
493 // and so we prevent recursion with the thread-local sAlreadyHandlingTrap. On
494 // Mach, the wasm exception handler has its own thread and is installed only on
495 // the thread-level debugging ports of JSRuntime threads, so a crash on
496 // exception handler thread will not recurse; it will bubble up to the
497 // process-level debugging ports (where Breakpad is installed).
498 // =============================================================================
499
500 static MOZ_THREAD_LOCAL(bool) sAlreadyHandlingTrap;
501
502 struct AutoHandlingTrap {
503 AutoHandlingTrap() {
504 MOZ_ASSERT(!sAlreadyHandlingTrap.get());
505 sAlreadyHandlingTrap.set(true);
506 }
507
508 ~AutoHandlingTrap() {
509 MOZ_ASSERT(sAlreadyHandlingTrap.get());
510 sAlreadyHandlingTrap.set(false);
511 }
512 };
513
514 [[nodiscard]] static bool HandleTrap(CONTEXT* context,
515 JSContext* assertCx = nullptr) {
516 MOZ_ASSERT(sAlreadyHandlingTrap.get());
517
518 uint8_t* pc = ContextToPC(context);
519 const CodeBlock* codeBlock = LookupCodeBlock(pc);
520 if (!codeBlock) {
521 return false;
522 }
523
524 Trap trap;
525 TrapSite trapSite;
526 if (!codeBlock->lookupTrap(pc, &trap, &trapSite)) {
527 return false;
528 }
529
530 // We have a safe, expected wasm trap, so fp is well-defined to be a Frame*.
531 // For the first sanity check, the Trap::IndirectCallBadSig special case is
532 // due to this trap occurring in the indirect call prologue, while fp points
533 // to the caller's Frame which can be in a different Module. In any case,
534 // though, the containing JSContext is the same.
535
536 auto* frame = reinterpret_cast<Frame*>(ContextToFP(context));
537 Instance* instance = GetNearestEffectiveInstance(frame);
538 MOZ_RELEASE_ASSERT(&instance->code() == codeBlock->code ||
539 trap == Trap::IndirectCallBadSig);
540
541 JSContext* cx =
542 instance->realm()->runtimeFromAnyThread()->mainContextFromAnyThread();
543 MOZ_RELEASE_ASSERT(!assertCx || cx == assertCx);
544
545 // JitActivation::startWasmTrap() stores enough register state from the
546 // point of the trap to allow stack unwinding or resumption, both of which
547 // will call finishWasmTrap().
548 jit::JitActivation* activation = cx->activation()->asJit();
549 activation->startWasmTrap(trap, trapSite, ToRegisterState(context));
550 SetContextPC(context, codeBlock->code->trapCode());
551 return true;
552 }
553
554 // =============================================================================
555 // The following platform-specific handlers funnel all signals/exceptions into
556 // the shared HandleTrap() above.
557 // =============================================================================
558
559 # if defined(XP_WIN)
560 // Obtained empirically from thread_local codegen on x86/x64/arm64.
561 // Compiled in all user binaries, so should be stable over time.
562 static const unsigned sThreadLocalArrayPointerIndex = 11;
563
564 static LONG WINAPI WasmTrapHandler(LPEXCEPTION_POINTERS exception) {
565 // Make sure TLS is initialized before reading sAlreadyHandlingTrap.
566 if (!NtCurrentTeb()->Reserved1[sThreadLocalArrayPointerIndex]) {
567 return EXCEPTION_CONTINUE_SEARCH;
568 }
569
570 if (sAlreadyHandlingTrap.get()) {
571 return EXCEPTION_CONTINUE_SEARCH;
572 }
573 AutoHandlingTrap aht;
574
575 EXCEPTION_RECORD* record = exception->ExceptionRecord;
576 if (record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION &&
577 record->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
578 return EXCEPTION_CONTINUE_SEARCH;
579 }
580
581 JSContext* cx = TlsContext.get(); // Cold signal handling code
582 if (!HandleTrap(exception->ContextRecord, cx)) {
583 return EXCEPTION_CONTINUE_SEARCH;
584 }
585
586 return EXCEPTION_CONTINUE_EXECUTION;
587 }
588
589 # elif defined(XP_DARWIN)
590 // On OSX we are forced to use the lower-level Mach exception mechanism instead
591 // of Unix signals because breakpad uses Mach exceptions and would otherwise
592 // report a crash before wasm gets a chance to handle the exception.
593
594 // This definition was generated by mig (the Mach Interface Generator) for the
595 // routine 'exception_raise' (exc.defs).
596 # pragma pack(4)
597 typedef struct {
598 mach_msg_header_t Head;
599 /* start of the kernel processed data */
600 mach_msg_body_t msgh_body;
601 mach_msg_port_descriptor_t thread;
602 mach_msg_port_descriptor_t task;
603 /* end of the kernel processed data */
604 NDR_record_t NDR;
605 exception_type_t exception;
606 mach_msg_type_number_t codeCnt;
607 int64_t code[2];
608 } Request__mach_exception_raise_t;
609 # pragma pack()
610
611 // The full Mach message also includes a trailer.
612 struct ExceptionRequest {
613 Request__mach_exception_raise_t body;
614 mach_msg_trailer_t trailer;
615 };
616
617 static bool HandleMachException(const ExceptionRequest& request) {
618 // Get the port of the JSContext's thread from the message.
619 mach_port_t cxThread = request.body.thread.name;
620
621 // Read out the JSRuntime thread's register state.
622 CONTEXT context;
623 # if defined(__x86_64__)
624 unsigned int thread_state_count = x86_THREAD_STATE64_COUNT;
625 unsigned int float_state_count = x86_FLOAT_STATE64_COUNT;
626 int thread_state = x86_THREAD_STATE64;
627 int float_state = x86_FLOAT_STATE64;
628 # elif defined(__i386__)
629 unsigned int thread_state_count = x86_THREAD_STATE_COUNT;
630 unsigned int float_state_count = x86_FLOAT_STATE_COUNT;
631 int thread_state = x86_THREAD_STATE;
632 int float_state = x86_FLOAT_STATE;
633 # elif defined(__arm__)
634 unsigned int thread_state_count = ARM_THREAD_STATE_COUNT;
635 unsigned int float_state_count = ARM_NEON_STATE_COUNT;
636 int thread_state = ARM_THREAD_STATE;
637 int float_state = ARM_NEON_STATE;
638 # elif defined(__aarch64__)
639 unsigned int thread_state_count = ARM_THREAD_STATE64_COUNT;
640 unsigned int float_state_count = ARM_NEON_STATE64_COUNT;
641 int thread_state = ARM_THREAD_STATE64;
642 int float_state = ARM_NEON_STATE64;
643 # else
644 # error Unsupported architecture
645 # endif
646 kern_return_t kret;
647 kret = thread_get_state(cxThread, thread_state,
648 (thread_state_t)&context.thread, &thread_state_count);
649 if (kret != KERN_SUCCESS) {
650 return false;
651 }
652 kret = thread_get_state(cxThread, float_state,
653 (thread_state_t)&context.float_, &float_state_count);
654 if (kret != KERN_SUCCESS) {
655 return false;
656 }
657
658 if (request.body.exception != EXC_BAD_ACCESS &&
659 request.body.exception != EXC_BAD_INSTRUCTION) {
660 return false;
661 }
662
663 {
664 AutoNoteSingleThreadedRegion anstr;
665 AutoHandlingTrap aht;
666 if (!HandleTrap(&context)) {
667 return false;
668 }
669 }
670
671 // Update the thread state with the new pc and register values.
672 kret = thread_set_state(cxThread, float_state,
673 (thread_state_t)&context.float_, float_state_count);
674 if (kret != KERN_SUCCESS) {
675 return false;
676 }
677 kret = thread_set_state(cxThread, thread_state,
678 (thread_state_t)&context.thread, thread_state_count);
679 if (kret != KERN_SUCCESS) {
680 return false;
681 }
682
683 return true;
684 }
685
686 static mach_port_t sMachDebugPort = MACH_PORT_NULL;
687
688 static void MachExceptionHandlerThread() {
689 ThisThread::SetName("JS Wasm MachExceptionHandler");
690
691 // Taken from mach_exc in /usr/include/mach/mach_exc.defs.
692 static const unsigned EXCEPTION_MSG_ID = 2405;
693
694 while (true) {
695 ExceptionRequest request;
696 kern_return_t kret =
697 mach_msg(&request.body.Head, MACH_RCV_MSG, 0, sizeof(request),
698 sMachDebugPort, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
699
700 // If we fail even receiving the message, we can't even send a reply!
701 // Rather than hanging the faulting thread (hanging the browser), crash.
702 if (kret != KERN_SUCCESS) {
703 fprintf(stderr, "MachExceptionHandlerThread: mach_msg failed with %d\n",
704 (int)kret);
705 MOZ_CRASH();
706 }
707
708 if (request.body.Head.msgh_id != EXCEPTION_MSG_ID) {
709 fprintf(stderr, "Unexpected msg header id %d\n",
710 (int)request.body.Head.msgh_bits);
711 MOZ_CRASH();
712 }
713
714 // Some thread just commited an EXC_BAD_ACCESS and has been suspended by
715 // the kernel. The kernel is waiting for us to reply with instructions.
716 // Our default is the "not handled" reply (by setting the RetCode field
717 // of the reply to KERN_FAILURE) which tells the kernel to continue
718 // searching at the process and system level. If this is an asm.js
719 // expected exception, we handle it and return KERN_SUCCESS.
720 bool handled = HandleMachException(request);
721 kern_return_t replyCode = handled ? KERN_SUCCESS : KERN_FAILURE;
722
723 // This magic incantation to send a reply back to the kernel was
724 // derived from the exc_server generated by
725 // 'mig -v /usr/include/mach/mach_exc.defs'.
726 __Reply__exception_raise_t reply;
727 reply.Head.msgh_bits =
728 MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(request.body.Head.msgh_bits), 0);
729 reply.Head.msgh_size = sizeof(reply);
730 reply.Head.msgh_remote_port = request.body.Head.msgh_remote_port;
731 reply.Head.msgh_local_port = MACH_PORT_NULL;
732 reply.Head.msgh_id = request.body.Head.msgh_id + 100;
733 reply.NDR = NDR_record;
734 reply.RetCode = replyCode;
735 mach_msg(&reply.Head, MACH_SEND_MSG, sizeof(reply), 0, MACH_PORT_NULL,
736 MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
737 }
738 }
739
740 # else // If not Windows or Mac, assume Unix
741
742 # if defined(__mips__) || defined(__loongarch__)
743 static const uint32_t kWasmTrapSignal = SIGFPE;
744 # else
745 static const uint32_t kWasmTrapSignal = SIGILL;
746 # endif
747
748 static struct sigaction sPrevSEGVHandler;
749 static struct sigaction sPrevSIGBUSHandler;
750 static struct sigaction sPrevWasmTrapHandler;
751
752 static void WasmTrapHandler(int signum, siginfo_t* info, void* context) {
753 if (!sAlreadyHandlingTrap.get()) {
754 AutoHandlingTrap aht;
755 MOZ_RELEASE_ASSERT(signum == SIGSEGV || signum == SIGBUS ||
756 signum == kWasmTrapSignal);
757 JSContext* cx = TlsContext.get(); // Cold signal handling code
758 if (HandleTrap((CONTEXT*)context, cx)) {
759 return;
760 }
761 }
762
763 struct sigaction* previousSignal = nullptr;
764 switch (signum) {
765 case SIGSEGV:
766 previousSignal = &sPrevSEGVHandler;
767 break;
768 case SIGBUS:
769 previousSignal = &sPrevSIGBUSHandler;
770 break;
771 case kWasmTrapSignal:
772 previousSignal = &sPrevWasmTrapHandler;
773 break;
774 }
775 MOZ_ASSERT(previousSignal);
776
777 // This signal is not for any asm.js code we expect, so we need to forward
778 // the signal to the next handler. If there is no next handler (SIG_IGN or
779 // SIG_DFL), then it's time to crash. To do this, we set the signal back to
780 // its original disposition and return. This will cause the faulting op to
781 // be re-executed which will crash in the normal way. The advantage of
782 // doing this to calling _exit() is that we remove ourselves from the crash
783 // stack which improves crash reports. If there is a next handler, call it.
784 // It will either crash synchronously, fix up the instruction so that
785 // execution can continue and return, or trigger a crash by returning the
786 // signal to it's original disposition and returning.
787 //
788 // Note: the order of these tests matter.
789 if (previousSignal->sa_flags & SA_SIGINFO) {
790 previousSignal->sa_sigaction(signum, info, context);
791 } else if (previousSignal->sa_handler == SIG_DFL ||
792 previousSignal->sa_handler == SIG_IGN) {
793 sigaction(signum, previousSignal, nullptr);
794 } else {
795 previousSignal->sa_handler(signum);
796 }
797 }
798 # endif // XP_WIN || XP_DARWIN || assume unix
799
800 struct InstallState {
801 bool tried;
802 bool success;
803 InstallState() : tried(false), success(false) {}
804 };
805
806 MOZ_RUNINIT static ExclusiveData<InstallState> sEagerInstallState(
807 mutexid::WasmSignalInstallState);
808
809 #endif // !(JS_CODEGEN_NONE)
810
811 void wasm::EnsureEagerProcessSignalHandlers() {
812 #ifdef JS_CODEGEN_NONE
813 // If there is no JIT, then there should be no Wasm signal handlers.
814 return;
815 #else
816 auto eagerInstallState = sEagerInstallState.lock();
817 if (eagerInstallState->tried) {
818 return;
819 }
820
821 eagerInstallState->tried = true;
822 MOZ_RELEASE_ASSERT(eagerInstallState->success == false);
823
824 sAlreadyHandlingTrap.infallibleInit();
825
826 // Install whatever exception/signal handler is appropriate for the OS.
827 # if defined(XP_WIN)
828
829 # if defined(MOZ_ASAN)
830 // Under ASan we need to let the ASan runtime's ShadowExceptionHandler stay
831 // in the first handler position.
832 const bool firstHandler = false;
833 # else
834 // Otherwise, WasmTrapHandler needs to go first, so that we can recover
835 // from wasm faults and continue execution without triggering handlers
836 // such as Breakpad that assume we are crashing.
837 const bool firstHandler = true;
838 # endif
839 if (!AddVectoredExceptionHandler(firstHandler, WasmTrapHandler)) {
840 // Windows has all sorts of random security knobs for disabling things
841 // so make this a dynamic failure that disables wasm, not a MOZ_CRASH().
842 return;
843 }
844
845 # elif defined(XP_DARWIN)
846 // All the Mach setup in EnsureLazyProcessSignalHandlers.
847 # else
848 // SA_NODEFER allows us to reenter the signal handler if we crash while
849 // handling the signal, and fall through to the Breakpad handler by testing
850 // handlingSegFault.
851
852 // Allow handling OOB with signals on all architectures
853 struct sigaction faultHandler;
854 faultHandler.sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK;
855 faultHandler.sa_sigaction = WasmTrapHandler;
856 sigemptyset(&faultHandler.sa_mask);
857 if (sigaction(SIGSEGV, &faultHandler, &sPrevSEGVHandler)) {
858 MOZ_CRASH("unable to install segv handler");
859 }
860
861 # if defined(JS_CODEGEN_ARM)
862 // On Arm Handle Unaligned Accesses
863 struct sigaction busHandler;
864 busHandler.sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK;
865 busHandler.sa_sigaction = WasmTrapHandler;
866 sigemptyset(&busHandler.sa_mask);
867 if (sigaction(SIGBUS, &busHandler, &sPrevSIGBUSHandler)) {
868 MOZ_CRASH("unable to install sigbus handler");
869 }
870 # endif
871
872 // Install a handler to handle the instructions that are emitted to implement
873 // wasm traps.
874 struct sigaction wasmTrapHandler;
875 wasmTrapHandler.sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK;
876 wasmTrapHandler.sa_sigaction = WasmTrapHandler;
877 sigemptyset(&wasmTrapHandler.sa_mask);
878 if (sigaction(kWasmTrapSignal, &wasmTrapHandler, &sPrevWasmTrapHandler)) {
879 MOZ_CRASH("unable to install wasm trap handler");
880 }
881 # endif
882
883 eagerInstallState->success = true;
884 #endif
885 }
886
887 #ifndef JS_CODEGEN_NONE
888 MOZ_RUNINIT static ExclusiveData<InstallState> sLazyInstallState(
889 mutexid::WasmSignalInstallState);
890
891 static bool EnsureLazyProcessSignalHandlers() {
892 auto lazyInstallState = sLazyInstallState.lock();
893 if (lazyInstallState->tried) {
894 return lazyInstallState->success;
895 }
896
897 lazyInstallState->tried = true;
898 MOZ_RELEASE_ASSERT(lazyInstallState->success == false);
899
900 # ifdef XP_DARWIN
901 // Create the port that all JSContext threads will redirect their traps to.
902 kern_return_t kret;
903 kret = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE,
904 &sMachDebugPort);
905 if (kret != KERN_SUCCESS) {
906 return false;
907 }
908 kret = mach_port_insert_right(mach_task_self(), sMachDebugPort,
909 sMachDebugPort, MACH_MSG_TYPE_MAKE_SEND);
910 if (kret != KERN_SUCCESS) {
911 return false;
912 }
913
914 // Create the thread that will wait on and service sMachDebugPort.
915 // It's not useful to destroy this thread on process shutdown so
916 // immediately detach on successful start.
917 Thread handlerThread;
918 if (!handlerThread.init(MachExceptionHandlerThread)) {
919 return false;
920 }
921 handlerThread.detach();
922 # endif
923
924 lazyInstallState->success = true;
925 return true;
926 }
927 #endif // JS_CODEGEN_NONE
928
929 bool wasm::EnsureFullSignalHandlers(JSContext* cx) {
930 #ifdef JS_CODEGEN_NONE
931 return false;
932 #else
933 if (cx->wasm().triedToInstallSignalHandlers) {
934 return cx->wasm().haveSignalHandlers;
935 }
936
937 cx->wasm().triedToInstallSignalHandlers = true;
938 MOZ_RELEASE_ASSERT(!cx->wasm().haveSignalHandlers);
939
940 {
941 auto eagerInstallState = sEagerInstallState.lock();
942 MOZ_RELEASE_ASSERT(eagerInstallState->tried);
943 if (!eagerInstallState->success) {
944 return false;
945 }
946 }
947
948 if (!EnsureLazyProcessSignalHandlers()) {
949 return false;
950 }
951
952 # ifdef XP_DARWIN
953 // In addition to the process-wide signal handler setup, OSX needs each
954 // thread configured to send its exceptions to sMachDebugPort. While there
955 // are also task-level (i.e. process-level) exception ports, those are
956 // "claimed" by breakpad and chaining Mach exceptions is dark magic that we
957 // avoid by instead intercepting exceptions at the thread level before they
958 // propagate to the process-level. This works because there are no other
959 // uses of thread-level exception ports.
960 MOZ_RELEASE_ASSERT(sMachDebugPort != MACH_PORT_NULL);
961 thread_port_t thisThread = mach_thread_self();
962 kern_return_t kret = thread_set_exception_ports(
963 thisThread, EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION,
964 sMachDebugPort, EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES,
965 THREAD_STATE_NONE);
966 mach_port_deallocate(mach_task_self(), thisThread);
967 if (kret != KERN_SUCCESS) {
968 return false;
969 }
970 # endif
971
972 cx->wasm().haveSignalHandlers = true;
973 return true;
974 #endif
975 }
976
977 bool wasm::MemoryAccessTraps(const RegisterState& regs, uint8_t* addr,
978 uint32_t numBytes, uint8_t** newPC) {
979 #ifdef JS_CODEGEN_NONE
980 return false;
981 #else
982 const wasm::CodeBlock* codeBlock = wasm::LookupCodeBlock(regs.pc);
983 if (!codeBlock) {
984 return false;
985 }
986
987 Trap trap;
988 TrapSite trapSite;
989 if (!codeBlock->code->lookupTrap(regs.pc, &trap, &trapSite)) {
990 return false;
991 }
992 switch (trap) {
993 case Trap::OutOfBounds:
994 break;
995 case Trap::NullPointerDereference:
996 break;
997 # ifdef WASM_HAS_HEAPREG
998 case Trap::IndirectCallToNull:
999 // We use the null pointer exception from loading the heapreg to
1000 // handle indirect calls to null.
1001 break;
1002 # endif
1003 default:
1004 return false;
1005 }
1006
1007 const Instance& instance =
1008 *GetNearestEffectiveInstance(Frame::fromUntaggedWasmExitFP(regs.fp));
1009 MOZ_ASSERT(&instance.code() == codeBlock->code);
1010
1011 switch (trap) {
1012 case Trap::OutOfBounds:
1013 if (!instance.memoryAccessInGuardRegion((uint8_t*)addr, numBytes)) {
1014 return false;
1015 }
1016 break;
1017 case Trap::NullPointerDereference:
1018 if ((uintptr_t)addr >= NullPtrGuardSize) {
1019 return false;
1020 }
1021 break;
1022 # ifdef WASM_HAS_HEAPREG
1023 case Trap::IndirectCallToNull:
1024 // Null pointer plus the appropriate offset.
1025 if (addr !=
1026 reinterpret_cast<uint8_t*>(wasm::Instance::offsetOfMemory0Base())) {
1027 return false;
1028 }
1029 break;
1030 # endif
1031 default:
1032 MOZ_CRASH("Should not happen");
1033 }
1034
1035 JSContext* cx = TlsContext.get(); // Cold simulator helper function
1036 jit::JitActivation* activation = cx->activation()->asJit();
1037 activation->startWasmTrap(trap, trapSite, regs);
1038 *newPC = codeBlock->code->trapCode();
1039 return true;
1040 #endif
1041 }
1042
1043 bool wasm::HandleIllegalInstruction(const RegisterState& regs,
1044 uint8_t** newPC) {
1045 #ifdef JS_CODEGEN_NONE
1046 return false;
1047 #else
1048 const wasm::CodeBlock* codeBlock = wasm::LookupCodeBlock(regs.pc);
1049 if (!codeBlock) {
1050 return false;
1051 }
1052
1053 Trap trap;
1054 TrapSite trapSite;
1055 if (!codeBlock->code->lookupTrap(regs.pc, &trap, &trapSite)) {
1056 return false;
1057 }
1058
1059 JSContext* cx = TlsContext.get(); // Cold simulator helper function
1060 jit::JitActivation* activation = cx->activation()->asJit();
1061 activation->startWasmTrap(trap, trapSite, regs);
1062 *newPC = codeBlock->code->trapCode();
1063 return true;
1064 #endif
1065 }