Debian Codegraph @

js/src/jit/JitFrames.cpp

raw
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 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "jit/JitFrames-inl.h"
8
9 #include "mozilla/ScopeExit.h"
10
11 #include <algorithm>
12
13 #include "builtin/ModuleObject.h"
14 #include "builtin/Sorting.h"
15 #include "gc/GC.h"
16 #include "jit/BaselineFrame.h"
17 #include "jit/BaselineIC.h"
18 #include "jit/BaselineJIT.h"
19 #include "jit/Ion.h"
20 #include "jit/IonScript.h"
21 #include "jit/JitRuntime.h"
22 #include "jit/JitSpewer.h"
23 #include "jit/LIR.h"
24 #include "jit/Recover.h"
25 #include "jit/Safepoints.h"
26 #include "jit/ScriptFromCalleeToken.h"
27 #include "jit/Snapshots.h"
28 #include "jit/VMFunctions.h"
29 #include "js/Exception.h"
30 #include "js/friend/DumpFunctions.h" // js::DumpObject, js::DumpValue
31 #include "vm/Interpreter.h"
32 #include "vm/JSContext.h"
33 #include "vm/JSFunction.h"
34 #include "vm/JSObject.h"
35 #include "vm/JSScript.h"
36 #include "wasm/WasmBuiltins.h"
37 #include "wasm/WasmInstance.h"
38
39 #include "builtin/Sorting-inl.h"
40 #include "debugger/DebugAPI-inl.h"
41 #include "jit/JSJitFrameIter-inl.h"
42 #include "vm/GeckoProfiler-inl.h"
43 #include "vm/JSScript-inl.h"
44 #include "vm/Probes-inl.h"
45
46 namespace js {
47 namespace jit {
48
49 // Given a slot index, returns the offset, in bytes, of that slot from an
50 // JitFrameLayout. Slot distances are uniform across architectures, however,
51 // the distance does depend on the size of the frame header.
52 static inline int32_t OffsetOfFrameSlot(int32_t slot) { return -slot; }
53
54 static inline uint8_t* AddressOfFrameSlot(JitFrameLayout* fp, int32_t slot) {
55 return (uint8_t*)fp + OffsetOfFrameSlot(slot);
56 }
57
58 static inline uintptr_t ReadFrameSlot(JitFrameLayout* fp, int32_t slot) {
59 return *(uintptr_t*)AddressOfFrameSlot(fp, slot);
60 }
61
62 static inline void WriteFrameSlot(JitFrameLayout* fp, int32_t slot,
63 uintptr_t value) {
64 *(uintptr_t*)AddressOfFrameSlot(fp, slot) = value;
65 }
66
67 static inline double ReadFrameDoubleSlot(JitFrameLayout* fp, int32_t slot) {
68 return *(double*)AddressOfFrameSlot(fp, slot);
69 }
70
71 static inline float ReadFrameFloat32Slot(JitFrameLayout* fp, int32_t slot) {
72 return *(float*)AddressOfFrameSlot(fp, slot);
73 }
74
75 static inline int32_t ReadFrameInt32Slot(JitFrameLayout* fp, int32_t slot) {
76 return *(int32_t*)AddressOfFrameSlot(fp, slot);
77 }
78
79 static inline bool ReadFrameBooleanSlot(JitFrameLayout* fp, int32_t slot) {
80 return *(bool*)AddressOfFrameSlot(fp, slot);
81 }
82
83 static uint32_t NumArgAndLocalSlots(const InlineFrameIterator& frame) {
84 JSScript* script = frame.script();
85 return CountArgSlots(script, frame.maybeCalleeTemplate()) + script->nfixed();
86 }
87
88 static TrampolineNative TrampolineNativeForFrame(
89 JSRuntime* rt, TrampolineNativeFrameLayout* layout) {
90 JSFunction* nativeFun = CalleeTokenToFunction(layout->calleeToken());
91 MOZ_ASSERT(nativeFun->isBuiltinNative());
92 void** jitEntry = nativeFun->nativeJitEntry();
93 return rt->jitRuntime()->trampolineNativeForJitEntry(jitEntry);
94 }
95
96 static void UnwindTrampolineNativeFrame(JSRuntime* rt,
97 const JSJitFrameIter& frame) {
98 auto* layout = (TrampolineNativeFrameLayout*)frame.fp();
99 TrampolineNative native = TrampolineNativeForFrame(rt, layout);
100 switch (native) {
101 case TrampolineNative::ArraySort:
102 case TrampolineNative::TypedArraySort:
103 layout->getFrameData<ArraySortData>()->freeMallocData();
104 break;
105 case TrampolineNative::Count:
106 MOZ_CRASH("Invalid value");
107 }
108 }
109
110 static void CloseLiveIteratorIon(JSContext* cx,
111 const InlineFrameIterator& frame,
112 const TryNote* tn) {
113 MOZ_ASSERT(tn->kind() == TryNoteKind::ForIn ||
114 tn->kind() == TryNoteKind::Destructuring);
115
116 bool isDestructuring = tn->kind() == TryNoteKind::Destructuring;
117 MOZ_ASSERT_IF(!isDestructuring, tn->stackDepth > 0);
118 MOZ_ASSERT_IF(isDestructuring, tn->stackDepth > 1);
119
120 // Save any pending exception, because some recover operations call into
121 // AutoUnsafeCallWithABI functions, which don't allow pending exceptions.
122 JS::AutoSaveExceptionState savedExc(cx);
123
124 SnapshotIterator si = frame.snapshotIterator();
125
126 // Skip stack slots until we reach the iterator object on the stack. For
127 // the destructuring case, we also need to get the "done" value.
128 uint32_t stackSlot = tn->stackDepth;
129 uint32_t adjust = isDestructuring ? 2 : 1;
130 uint32_t skipSlots = NumArgAndLocalSlots(frame) + stackSlot - adjust;
131
132 for (unsigned i = 0; i < skipSlots; i++) {
133 si.skip();
134 }
135
136 MaybeReadFallback recover(cx, cx->activation()->asJit(), &frame.frame(),
137 MaybeReadFallback::Fallback_DoNothing);
138 Value v = si.maybeRead(recover);
139 MOZ_RELEASE_ASSERT(v.isObject());
140 RootedObject iterObject(cx, &v.toObject());
141
142 if (isDestructuring) {
143 RootedValue doneValue(cx, si.read());
144 MOZ_RELEASE_ASSERT(!doneValue.isMagic());
145 bool done = ToBoolean(doneValue);
146 // Do not call IteratorClose if the destructuring iterator is already
147 // done.
148 if (done) {
149 return;
150 }
151 }
152
153 // Restore any pending exception before the closing the iterator.
154 savedExc.restore();
155
156 if (cx->isExceptionPending()) {
157 if (tn->kind() == TryNoteKind::ForIn) {
158 CloseIterator(iterObject);
159 } else {
160 IteratorCloseForException(cx, iterObject);
161 }
162 } else {
163 UnwindIteratorForUncatchableException(iterObject);
164 }
165 }
166
167 class IonTryNoteFilter {
168 uint32_t depth_;
169
170 public:
171 explicit IonTryNoteFilter(const InlineFrameIterator& frame) {
172 uint32_t base = NumArgAndLocalSlots(frame);
173 SnapshotIterator si = frame.snapshotIterator();
174 MOZ_ASSERT(si.numAllocations() >= base);
175 depth_ = si.numAllocations() - base;
176 }
177
178 bool operator()(const TryNote* note) { return note->stackDepth <= depth_; }
179 };
180
181 class TryNoteIterIon : public TryNoteIter<IonTryNoteFilter> {
182 public:
183 TryNoteIterIon(JSContext* cx, const InlineFrameIterator& frame)
184 : TryNoteIter(cx, frame.script(), frame.pc(), IonTryNoteFilter(frame)) {}
185 };
186
187 static bool ShouldBailoutForDebugger(JSContext* cx,
188 const InlineFrameIterator& frame,
189 bool hitBailoutException) {
190 if (hitBailoutException) {
191 MOZ_ASSERT(!cx->isPropagatingForcedReturn());
192 return false;
193 }
194
195 // Bail out if we're propagating a forced return from an inlined frame,
196 // even if the realm is no longer a debuggee.
197 if (cx->isPropagatingForcedReturn() && frame.more()) {
198 return true;
199 }
200
201 if (!cx->realm()->isDebuggee()) {
202 return false;
203 }
204
205 // Bail out if there's a catchable exception and we are the debuggee of a
206 // Debugger with a live onExceptionUnwind hook.
207 if (cx->isExceptionPending() &&
208 DebugAPI::hasExceptionUnwindHook(cx->global())) {
209 return true;
210 }
211
212 // Bail out if a Debugger has observed this frame (e.g., for onPop).
213 JitActivation* act = cx->activation()->asJit();
214 RematerializedFrame* rematFrame =
215 act->lookupRematerializedFrame(frame.frame().fp(), frame.frameNo());
216 return rematFrame && rematFrame->isDebuggee();
217 }
218
219 static void OnLeaveIonFrame(JSContext* cx, const InlineFrameIterator& frame,
220 ResumeFromException* rfe) {
221 bool returnFromThisFrame =
222 cx->isPropagatingForcedReturn() || cx->isClosingGenerator();
223 if (!returnFromThisFrame) {
224 return;
225 }
226
227 JitActivation* act = cx->activation()->asJit();
228 RematerializedFrame* rematFrame = nullptr;
229 {
230 JS::AutoSaveExceptionState savedExc(cx);
231 rematFrame = act->getRematerializedFrame(cx, frame.frame(), frame.frameNo(),
232 IsLeavingFrame::Yes);
233 if (!rematFrame) {
234 return;
235 }
236 }
237
238 MOZ_ASSERT(!frame.more());
239
240 if (cx->isClosingGenerator()) {
241 HandleClosingGeneratorReturn(cx, rematFrame, /*frameOk=*/true);
242 } else {
243 cx->clearPropagatingForcedReturn();
244 }
245
246 Value& rval = rematFrame->returnValue();
247 MOZ_RELEASE_ASSERT(!rval.isMagic());
248
249 // Set both framePointer and stackPointer to the address of the
250 // JitFrameLayout.
251 rfe->kind = ExceptionResumeKind::ForcedReturnIon;
252 rfe->framePointer = frame.frame().fp();
253 rfe->stackPointer = frame.frame().fp();
254 rfe->exception = rval;
255 rfe->exceptionStack = NullValue();
256
257 act->removeIonFrameRecovery(frame.frame().jsFrame());
258 act->removeRematerializedFrame(frame.frame().fp());
259 }
260
261 static void HandleExceptionIon(JSContext* cx, const InlineFrameIterator& frame,
262 ResumeFromException* rfe,
263 bool* hitBailoutException) {
264 if (ShouldBailoutForDebugger(cx, frame, *hitBailoutException)) {
265 // We do the following:
266 //
267 // 1. Bailout to baseline to reconstruct a baseline frame.
268 // 2. Resume immediately into the exception tail afterwards, and
269 // handle the exception again with the top frame now a baseline
270 // frame.
271 //
272 // An empty exception info denotes that we're propagating an Ion
273 // exception due to debug mode, which BailoutIonToBaseline needs to
274 // know. This is because we might not be able to fully reconstruct up
275 // to the stack depth at the snapshot, as we could've thrown in the
276 // middle of a call.
277 ExceptionBailoutInfo propagateInfo(cx);
278 if (ExceptionHandlerBailout(cx, frame, rfe, propagateInfo)) {
279 return;
280 }
281 *hitBailoutException = true;
282 }
283
284 RootedScript script(cx, frame.script());
285
286 for (TryNoteIterIon tni(cx, frame); !tni.done(); ++tni) {
287 const TryNote* tn = *tni;
288 switch (tn->kind()) {
289 case TryNoteKind::ForIn:
290 case TryNoteKind::Destructuring:
291 CloseLiveIteratorIon(cx, frame, tn);
292 break;
293
294 case TryNoteKind::Catch:
295 // If we're closing a generator, we have to skip catch blocks.
296 if (cx->isClosingGenerator()) {
297 break;
298 }
299
300 if (cx->isExceptionPending()) {
301 // Ion can compile try-catch, but bailing out to catch
302 // exceptions is slow. Reset the warm-up counter so that if we
303 // catch many exceptions we won't Ion-compile the script.
304 script->resetWarmUpCounterToDelayIonCompilation();
305
306 if (*hitBailoutException) {
307 break;
308 }
309
310 // Bailout at the start of the catch block.
311 jsbytecode* catchPC = script->offsetToPC(tn->start + tn->length);
312 ExceptionBailoutInfo excInfo(cx, frame.frameNo(), catchPC,
313 tn->stackDepth);
314 if (ExceptionHandlerBailout(cx, frame, rfe, excInfo)) {
315 // Record exception locations to allow scope unwinding in
316 // |FinishBailoutToBaseline|
317 MOZ_ASSERT(cx->isExceptionPending());
318 rfe->bailoutInfo->tryPC =
319 UnwindEnvironmentToTryPc(frame.script(), tn);
320 rfe->bailoutInfo->faultPC = frame.pc();
321 return;
322 }
323
324 *hitBailoutException = true;
325 MOZ_ASSERT(cx->isExceptionPending() || cx->hadUncatchableException());
326 }
327 break;
328
329 case TryNoteKind::Finally: {
330 if (!cx->isExceptionPending()) {
331 // We don't catch uncatchable exceptions.
332 break;
333 }
334
335 script->resetWarmUpCounterToDelayIonCompilation();
336
337 if (*hitBailoutException) {
338 break;
339 }
340
341 // Bailout at the start of the finally block.
342 jsbytecode* finallyPC = script->offsetToPC(tn->start + tn->length);
343 ExceptionBailoutInfo excInfo(cx, frame.frameNo(), finallyPC,
344 tn->stackDepth);
345
346 RootedValue exception(cx);
347 RootedValue exceptionStack(cx);
348 if (!cx->getPendingException(&exception) ||
349 !cx->getPendingExceptionStack(&exceptionStack)) {
350 exception = UndefinedValue();
351 exceptionStack = NullValue();
352 }
353 excInfo.setFinallyException(exception.get(), exceptionStack.get());
354 cx->clearPendingException();
355
356 if (ExceptionHandlerBailout(cx, frame, rfe, excInfo)) {
357 // Record exception locations to allow scope unwinding in
358 // |FinishBailoutToBaseline|
359 rfe->bailoutInfo->tryPC =
360 UnwindEnvironmentToTryPc(frame.script(), tn);
361 rfe->bailoutInfo->faultPC = frame.pc();
362 return;
363 }
364
365 *hitBailoutException = true;
366 MOZ_ASSERT(cx->isExceptionPending());
367 break;
368 }
369
370 case TryNoteKind::ForOf:
371 case TryNoteKind::Loop:
372 break;
373
374 // TryNoteKind::ForOfIterclose is handled internally by the try note
375 // iterator.
376 default:
377 MOZ_CRASH("Unexpected try note");
378 }
379 }
380
381 OnLeaveIonFrame(cx, frame, rfe);
382 }
383
384 static void OnLeaveBaselineFrame(JSContext* cx, const JSJitFrameIter& frame,
385 jsbytecode* pc, ResumeFromException* rfe,
386 bool frameOk) {
387 BaselineFrame* baselineFrame = frame.baselineFrame();
388 bool returnFromThisFrame = jit::DebugEpilogue(cx, baselineFrame, pc, frameOk);
389 if (returnFromThisFrame) {
390 if (!baselineFrame->hasReturnValue()) {
391 baselineFrame->setReturnValue(UndefinedValue());
392 }
393 rfe->kind = ExceptionResumeKind::ForcedReturnBaseline;
394 rfe->framePointer = frame.fp();
395 rfe->stackPointer = reinterpret_cast<uint8_t*>(baselineFrame);
396 }
397 }
398
399 static inline void BaselineFrameAndStackPointersFromTryNote(
400 const TryNote* tn, const JSJitFrameIter& frame, uint8_t** framePointer,
401 uint8_t** stackPointer) {
402 JSScript* script = frame.baselineFrame()->script();
403 *framePointer = frame.fp();
404 *stackPointer = *framePointer - BaselineFrame::Size() -
405 (script->nfixed() + tn->stackDepth) * sizeof(Value);
406 }
407
408 static void SettleOnTryNote(JSContext* cx, const TryNote* tn,
409 const JSJitFrameIter& frame, EnvironmentIter& ei,
410 ResumeFromException* rfe, jsbytecode** pc) {
411 RootedScript script(cx, frame.baselineFrame()->script());
412
413 // Unwind environment chain (pop block objects).
414 if (cx->isExceptionPending()) {
415 UnwindEnvironment(cx, ei, UnwindEnvironmentToTryPc(script, tn));
416 }
417
418 // Compute base pointer and stack pointer.
419 BaselineFrameAndStackPointersFromTryNote(tn, frame, &rfe->framePointer,
420 &rfe->stackPointer);
421
422 // Compute the pc.
423 *pc = script->offsetToPC(tn->start + tn->length);
424 }
425
426 class BaselineTryNoteFilter {
427 const JSJitFrameIter& frame_;
428
429 public:
430 explicit BaselineTryNoteFilter(const JSJitFrameIter& frame) : frame_(frame) {}
431 bool operator()(const TryNote* note) {
432 BaselineFrame* frame = frame_.baselineFrame();
433
434 uint32_t numValueSlots = frame_.baselineFrameNumValueSlots();
435 MOZ_RELEASE_ASSERT(numValueSlots >= frame->script()->nfixed());
436
437 uint32_t currDepth = numValueSlots - frame->script()->nfixed();
438 return note->stackDepth <= currDepth;
439 }
440 };
441
442 class TryNoteIterBaseline : public TryNoteIter<BaselineTryNoteFilter> {
443 public:
444 TryNoteIterBaseline(JSContext* cx, const JSJitFrameIter& frame,
445 jsbytecode* pc)
446 : TryNoteIter(cx, frame.script(), pc, BaselineTryNoteFilter(frame)) {}
447 };
448
449 // Close all live iterators on a BaselineFrame due to exception unwinding. The
450 // pc parameter is updated to where the envs have been unwound to.
451 static void CloseLiveIteratorsBaselineForUncatchableException(
452 JSContext* cx, const JSJitFrameIter& frame, jsbytecode* pc) {
453 for (TryNoteIterBaseline tni(cx, frame, pc); !tni.done(); ++tni) {
454 const TryNote* tn = *tni;
455 switch (tn->kind()) {
456 case TryNoteKind::ForIn: {
457 uint8_t* framePointer;
458 uint8_t* stackPointer;
459 BaselineFrameAndStackPointersFromTryNote(tn, frame, &framePointer,
460 &stackPointer);
461 Value iterValue(*(Value*)stackPointer);
462 RootedObject iterObject(cx, &iterValue.toObject());
463 UnwindIteratorForUncatchableException(iterObject);
464 break;
465 }
466
467 default:
468 break;
469 }
470 }
471 }
472
473 static bool ProcessTryNotesBaseline(JSContext* cx, const JSJitFrameIter& frame,
474 EnvironmentIter& ei,
475 ResumeFromException* rfe, jsbytecode** pc) {
476 MOZ_ASSERT(frame.baselineFrame()->runningInInterpreter(),
477 "Caller must ensure frame is an interpreter frame");
478
479 RootedScript script(cx, frame.baselineFrame()->script());
480
481 for (TryNoteIterBaseline tni(cx, frame, *pc); !tni.done(); ++tni) {
482 const TryNote* tn = *tni;
483
484 MOZ_ASSERT(cx->isExceptionPending());
485 switch (tn->kind()) {
486 case TryNoteKind::Catch: {
487 // If we're closing a generator, we have to skip catch blocks.
488 if (cx->isClosingGenerator()) {
489 break;
490 }
491
492 SettleOnTryNote(cx, tn, frame, ei, rfe, pc);
493
494 // Ion can compile try-catch, but bailing out to catch
495 // exceptions is slow. Reset the warm-up counter so that if we
496 // catch many exceptions we won't Ion-compile the script.
497 script->resetWarmUpCounterToDelayIonCompilation();
498
499 // Resume at the start of the catch block.
500 frame.baselineFrame()->setInterpreterFields(*pc);
501 rfe->kind = ExceptionResumeKind::Catch;
502 if (IsBaselineInterpreterEnabled()) {
503 const BaselineInterpreter& interp =
504 cx->runtime()->jitRuntime()->baselineInterpreter();
505 rfe->target = interp.interpretOpAddr().value;
506 }
507 return true;
508 }
509
510 case TryNoteKind::Finally: {
511 SettleOnTryNote(cx, tn, frame, ei, rfe, pc);
512
513 frame.baselineFrame()->setInterpreterFields(*pc);
514 rfe->kind = ExceptionResumeKind::Finally;
515 if (IsBaselineInterpreterEnabled()) {
516 const BaselineInterpreter& interp =
517 cx->runtime()->jitRuntime()->baselineInterpreter();
518 rfe->target = interp.interpretOpAddr().value;
519 }
520
521 // Drop the exception instead of leaking cross compartment data.
522 RootedValue exception(cx);
523 RootedValue exceptionStack(cx);
524 if (!cx->getPendingException(&exception) ||
525 !cx->getPendingExceptionStack(&exceptionStack)) {
526 rfe->exception = UndefinedValue();
527 rfe->exceptionStack = NullValue();
528 } else {
529 rfe->exception = exception;
530 rfe->exceptionStack = exceptionStack;
531 }
532 cx->clearPendingException();
533 return true;
534 }
535
536 case TryNoteKind::ForIn: {
537 uint8_t* framePointer;
538 uint8_t* stackPointer;
539 BaselineFrameAndStackPointersFromTryNote(tn, frame, &framePointer,
540 &stackPointer);
541 Value iterValue(*reinterpret_cast<Value*>(stackPointer));
542 JSObject* iterObject = &iterValue.toObject();
543 CloseIterator(iterObject);
544 break;
545 }
546
547 case TryNoteKind::Destructuring: {
548 uint8_t* framePointer;
549 uint8_t* stackPointer;
550 BaselineFrameAndStackPointersFromTryNote(tn, frame, &framePointer,
551 &stackPointer);
552 // Note: if this ever changes, also update the
553 // TryNoteKind::Destructuring code in WarpBuilder.cpp!
554 RootedValue doneValue(cx, *(reinterpret_cast<Value*>(stackPointer)));
555 MOZ_RELEASE_ASSERT(!doneValue.isMagic());
556 bool done = ToBoolean(doneValue);
557 if (!done) {
558 Value iterValue(*(reinterpret_cast<Value*>(stackPointer) + 1));
559 RootedObject iterObject(cx, &iterValue.toObject());
560 if (!IteratorCloseForException(cx, iterObject)) {
561 SettleOnTryNote(cx, tn, frame, ei, rfe, pc);
562 return false;
563 }
564 }
565 break;
566 }
567
568 case TryNoteKind::ForOf:
569 case TryNoteKind::Loop:
570 break;
571
572 // TryNoteKind::ForOfIterClose is handled internally by the try note
573 // iterator.
574 default:
575 MOZ_CRASH("Invalid try note");
576 }
577 }
578 return true;
579 }
580
581 static void HandleExceptionBaseline(JSContext* cx, JSJitFrameIter& frame,
582 CommonFrameLayout* prevFrame,
583 ResumeFromException* rfe) {
584 MOZ_ASSERT(frame.isBaselineJS());
585 MOZ_ASSERT(prevFrame);
586
587 jsbytecode* pc;
588 frame.baselineScriptAndPc(nullptr, &pc);
589
590 // Ensure the BaselineFrame is an interpreter frame. This is easy to do and
591 // simplifies the code below and interaction with DebugModeOSR.
592 //
593 // Note that we never return to this frame via the previous frame's return
594 // address. We could set the return address to nullptr to ensure it's never
595 // used, but the profiler expects a non-null return value for its JitCode map
596 // lookup so we have to use an address in the interpreter code instead.
597 if (!frame.baselineFrame()->runningInInterpreter()) {
598 const BaselineInterpreter& interp =
599 cx->runtime()->jitRuntime()->baselineInterpreter();
600 uint8_t* retAddr = interp.codeRaw();
601 BaselineFrame* baselineFrame = frame.baselineFrame();
602
603 // Suppress profiler sampling while we fix up the frame to ensure the
604 // sampler thread doesn't see an inconsistent state.
605 AutoSuppressProfilerSampling suppressProfilerSampling(cx);
606 baselineFrame->switchFromJitToInterpreterForExceptionHandler(cx, pc);
607 prevFrame->setReturnAddress(retAddr);
608
609 // Ensure the current iterator's resumePCInCurrentFrame_ isn't used
610 // anywhere.
611 frame.setResumePCInCurrentFrame(nullptr);
612 }
613
614 bool frameOk = false;
615 RootedScript script(cx, frame.baselineFrame()->script());
616
617 if (script->hasScriptCounts()) {
618 PCCounts* counts = script->getThrowCounts(pc);
619 // If we failed to allocate, then skip the increment and continue to
620 // handle the exception.
621 if (counts) {
622 counts->numExec()++;
623 }
624 }
625
626 bool hasTryNotes = !script->trynotes().empty();
627
628 again:
629 if (cx->isExceptionPending()) {
630 if (!cx->isClosingGenerator()) {
631 if (!DebugAPI::onExceptionUnwind(cx, frame.baselineFrame())) {
632 if (!cx->isExceptionPending()) {
633 goto again;
634 }
635 }
636 // Ensure that the debugger hasn't returned 'true' while clearing the
637 // exception state.
638 MOZ_ASSERT(cx->isExceptionPending());
639 }
640
641 if (hasTryNotes) {
642 EnvironmentIter ei(cx, frame.baselineFrame(), pc);
643 if (!ProcessTryNotesBaseline(cx, frame, ei, rfe, &pc)) {
644 goto again;
645 }
646 if (rfe->kind != ExceptionResumeKind::EntryFrame) {
647 // No need to increment the PCCounts number of execution here,
648 // as the interpreter increments any PCCounts if present.
649 MOZ_ASSERT_IF(script->hasScriptCounts(), script->maybeGetPCCounts(pc));
650 return;
651 }
652 }
653
654 frameOk = HandleClosingGeneratorReturn(cx, frame.baselineFrame(), frameOk);
655 } else {
656 if (hasTryNotes) {
657 CloseLiveIteratorsBaselineForUncatchableException(cx, frame, pc);
658 }
659
660 // We may be propagating a forced return from a debugger hook function.
661 if (MOZ_UNLIKELY(cx->isPropagatingForcedReturn())) {
662 cx->clearPropagatingForcedReturn();
663 frameOk = true;
664 }
665 }
666
667 OnLeaveBaselineFrame(cx, frame, pc, rfe, frameOk);
668 }
669
670 static JitFrameLayout* GetLastProfilingFrame(ResumeFromException* rfe) {
671 switch (rfe->kind) {
672 case ExceptionResumeKind::EntryFrame:
673 case ExceptionResumeKind::WasmInterpEntry:
674 case ExceptionResumeKind::WasmCatch:
675 return nullptr;
676
677 // The following all return into Baseline or Ion frames.
678 case ExceptionResumeKind::Catch:
679 case ExceptionResumeKind::Finally:
680 case ExceptionResumeKind::ForcedReturnBaseline:
681 case ExceptionResumeKind::ForcedReturnIon:
682 return reinterpret_cast<JitFrameLayout*>(rfe->framePointer);
683
684 // When resuming into a bailed-out ion frame, use the bailout info to
685 // find the frame we are resuming into.
686 case ExceptionResumeKind::Bailout:
687 return reinterpret_cast<JitFrameLayout*>(rfe->bailoutInfo->incomingStack);
688 }
689
690 MOZ_CRASH("Invalid ResumeFromException type!");
691 return nullptr;
692 }
693
694 void HandleException(ResumeFromException* rfe) {
695 JSContext* cx = TlsContext.get();
696
697 cx->realm()->localAllocSite = nullptr;
698 #ifdef DEBUG
699 if (!IsPortableBaselineInterpreterEnabled()) {
700 cx->runtime()->jitRuntime()->clearDisallowArbitraryCode();
701 }
702
703 // Reset the counter when we bailed after MDebugEnterGCUnsafeRegion, but
704 // before the matching MDebugLeaveGCUnsafeRegion.
705 //
706 // NOTE: EnterJit ensures the counter is zero when we enter JIT code.
707 cx->resetInUnsafeRegion();
708 #endif
709
710 auto resetProfilerFrame = mozilla::MakeScopeExit([=] {
711 if (!IsPortableBaselineInterpreterEnabled()) {
712 if (!cx->runtime()->jitRuntime()->isProfilerInstrumentationEnabled(
713 cx->runtime())) {
714 return;
715 }
716 }
717
718 MOZ_ASSERT(cx->jitActivation == cx->profilingActivation());
719
720 auto* lastProfilingFrame = GetLastProfilingFrame(rfe);
721 cx->jitActivation->setLastProfilingFrame(lastProfilingFrame);
722 });
723
724 rfe->kind = ExceptionResumeKind::EntryFrame;
725
726 JitSpew(JitSpew_IonInvalidate, "handling exception");
727
728 JitActivation* activation = cx->activation()->asJit();
729
730 #ifdef CHECK_OSIPOINT_REGISTERS
731 if (JitOptions.checkOsiPointRegisters) {
732 activation->setCheckRegs(false);
733 }
734 #endif
735
736 JitFrameIter iter(cx->activation()->asJit(),
737 /* mustUnwindActivation = */ true);
738
739 // Live wasm code on the stack is kept alive (in TraceJitActivation) by
740 // marking the instance of every wasm::Frame found by WasmFrameIter.
741 // However, we're going to pop frames while iterating which means that a GC
742 // during this loop could collect the code of frames whose code is still on
743 // the stack.
744 //
745 // This is actually mostly fine: after we return to the Wasm throw stub, we'll
746 // jump to the JIT's exception handling trampoline. However, we must keep the
747 // throw stub alive itself which is owned by the innermost instance.
748 Rooted<WasmInstanceObject*> keepAlive(cx);
749 if (iter.isWasm()) {
750 keepAlive = iter.asWasm().instance()->object();
751 }
752
753 CommonFrameLayout* prevJitFrame = nullptr;
754 while (!iter.done()) {
755 if (iter.isWasm()) {
756 prevJitFrame = nullptr;
757 wasm::HandleExceptionWasm(cx, iter, rfe);
758 if (rfe->kind == ExceptionResumeKind::WasmCatch) {
759 // Jump to a Wasm try-catch handler.
760 return;
761 }
762 // We either reached a JS JIT frame or we stopped at the activation's Wasm
763 // interpreter entry frame.
764 MOZ_ASSERT(iter.isJSJit() || (iter.isWasm() && iter.done()));
765 continue;
766 }
767
768 JSJitFrameIter& frame = iter.asJSJit();
769
770 // JIT code can enter same-compartment realms, so reset cx->realm to
771 // this frame's realm.
772 if (frame.isScripted() || frame.isTrampolineNative()) {
773 cx->setRealmForJitExceptionHandler(iter.realm());
774 }
775
776 if (frame.isIonJS()) {
777 // Search each inlined frame for live iterator objects, and close
778 // them.
779 InlineFrameIterator frames(cx, &frame);
780
781 // Invalidation state will be the same for all inlined scripts in the
782 // frame.
783 IonScript* ionScript = nullptr;
784 bool invalidated = frame.checkInvalidation(&ionScript);
785
786 // If we hit OOM or overrecursion while bailing out, we don't
787 // attempt to bail out a second time for this Ion frame. Just unwind
788 // and continue at the next frame.
789 bool hitBailoutException = false;
790 for (;;) {
791 HandleExceptionIon(cx, frames, rfe, &hitBailoutException);
792
793 if (rfe->kind == ExceptionResumeKind::Bailout ||
794 rfe->kind == ExceptionResumeKind::ForcedReturnIon) {
795 if (invalidated) {
796 ionScript->decrementInvalidationCount(cx->gcContext());
797 }
798 return;
799 }
800
801 MOZ_ASSERT(rfe->kind == ExceptionResumeKind::EntryFrame);
802
803 // When profiling, each frame popped needs a notification that
804 // the function has exited, so invoke the probe that a function
805 // is exiting.
806
807 JSScript* script = frames.script();
808 probes::ExitScript(cx, script, script->function(),
809 /* popProfilerFrame = */ false);
810 if (!frames.more()) {
811 break;
812 }
813 ++frames;
814 }
815
816 // Remove left-over state which might have been needed for bailout.
817 activation->removeIonFrameRecovery(frame.jsFrame());
818 activation->removeRematerializedFrame(frame.fp());
819
820 // If invalidated, decrement the number of frames remaining on the
821 // stack for the given IonScript.
822 if (invalidated) {
823 ionScript->decrementInvalidationCount(cx->gcContext());
824 }
825
826 } else if (frame.isBaselineJS()) {
827 HandleExceptionBaseline(cx, frame, prevJitFrame, rfe);
828
829 if (rfe->kind != ExceptionResumeKind::EntryFrame &&
830 rfe->kind != ExceptionResumeKind::ForcedReturnBaseline) {
831 return;
832 }
833
834 // Unwind profiler pseudo-stack
835 JSScript* script = frame.script();
836 probes::ExitScript(cx, script, script->function(),
837 /* popProfilerFrame = */ false);
838
839 if (rfe->kind == ExceptionResumeKind::ForcedReturnBaseline) {
840 return;
841 }
842 } else if (frame.isTrampolineNative()) {
843 UnwindTrampolineNativeFrame(cx->runtime(), frame);
844 }
845
846 prevJitFrame = frame.current();
847 ++iter;
848 }
849
850 // Return to C++ code by returning to the activation's JS or Wasm entry frame.
851 if (iter.isJSJit()) {
852 MOZ_ASSERT(rfe->kind == ExceptionResumeKind::EntryFrame);
853 rfe->framePointer = iter.asJSJit().current()->callerFramePtr();
854 rfe->stackPointer =
855 iter.asJSJit().fp() + CommonFrameLayout::offsetOfReturnAddress();
856 } else {
857 MOZ_ASSERT(iter.isWasm());
858 // In case of no handler, exit wasm via ret(). The exception handling
859 // trampoline will return InterpFailInstanceReg in InstanceReg to signal
860 // to the interpreter entry stub to do a failure return.
861 rfe->kind = ExceptionResumeKind::WasmInterpEntry;
862 rfe->framePointer = (uint8_t*)iter.asWasm().unwoundCallerFP();
863 rfe->stackPointer = (uint8_t*)iter.asWasm().unwoundAddressOfReturnAddress();
864 rfe->instance = nullptr;
865 rfe->target = nullptr;
866 }
867 }
868
869 // Turns a JitFrameLayout into an UnwoundJit ExitFrameLayout.
870 void EnsureUnwoundJitExitFrame(JitActivation* act, JitFrameLayout* frame) {
871 ExitFrameLayout* exitFrame = reinterpret_cast<ExitFrameLayout*>(frame);
872
873 if (act->jsExitFP() == (uint8_t*)frame) {
874 // If we already called this function for the current frame, do
875 // nothing.
876 MOZ_ASSERT(exitFrame->isUnwoundJitExit());
877 return;
878 }
879
880 #ifdef DEBUG
881 JSJitFrameIter iter(act);
882 while (!iter.isScripted()) {
883 ++iter;
884 }
885 MOZ_ASSERT(iter.current() == frame, "|frame| must be the top JS frame");
886
887 MOZ_ASSERT(!!act->jsExitFP());
888 MOZ_ASSERT((uint8_t*)exitFrame->footer() >= act->jsExitFP(),
889 "Must have space for ExitFooterFrame before jsExitFP");
890 #endif
891
892 act->setJSExitFP((uint8_t*)frame);
893 exitFrame->footer()->setUnwoundJitExitFrame();
894 MOZ_ASSERT(exitFrame->isUnwoundJitExit());
895 }
896
897 JSScript* MaybeForwardedScriptFromCalleeToken(CalleeToken token) {
898 switch (GetCalleeTokenTag(token)) {
899 case CalleeToken_Script:
900 return MaybeForwarded(CalleeTokenToScript(token));
901 case CalleeToken_Function:
902 case CalleeToken_FunctionConstructing: {
903 JSFunction* fun = MaybeForwarded(CalleeTokenToFunction(token));
904 return MaybeForwarded(fun)->nonLazyScript();
905 }
906 }
907 MOZ_CRASH("invalid callee token tag");
908 }
909
910 CalleeToken TraceCalleeToken(JSTracer* trc, CalleeToken token) {
911 switch (CalleeTokenTag tag = GetCalleeTokenTag(token)) {
912 case CalleeToken_Function:
913 case CalleeToken_FunctionConstructing: {
914 JSFunction* fun = CalleeTokenToFunction(token);
915 TraceRoot(trc, &fun, "jit-callee");
916 return CalleeToToken(fun, tag == CalleeToken_FunctionConstructing);
917 }
918 case CalleeToken_Script: {
919 JSScript* script = CalleeTokenToScript(token);
920 TraceRoot(trc, &script, "jit-script");
921 return CalleeToToken(script);
922 }
923 default:
924 MOZ_CRASH("unknown callee token type");
925 }
926 }
927
928 uintptr_t* JitFrameLayout::slotRef(SafepointSlotEntry where) {
929 if (where.stack) {
930 return (uintptr_t*)((uint8_t*)this - where.slot);
931 }
932 return (uintptr_t*)((uint8_t*)thisAndActualArgs() + where.slot);
933 }
934
935 #ifdef DEBUG
936 void ExitFooterFrame::assertValidVMFunctionId() const {
937 MOZ_ASSERT(data_ >= uintptr_t(ExitFrameType::VMFunction));
938 MOZ_ASSERT(data_ - uintptr_t(ExitFrameType::VMFunction) < NumVMFunctions());
939 }
940 #endif
941
942 #ifdef JS_NUNBOX32
943 static inline uintptr_t ReadAllocation(const JSJitFrameIter& frame,
944 const LAllocation* a) {
945 if (a->isGeneralReg()) {
946 Register reg = a->toGeneralReg()->reg();
947 return frame.machineState().read(reg);
948 }
949 return *frame.jsFrame()->slotRef(SafepointSlotEntry(a));
950 }
951 #endif
952
953 static void TraceThisAndArguments(JSTracer* trc, const JSJitFrameIter& frame,
954 JitFrameLayout* layout) {
955 // Trace |this| and the actual and formal arguments of a JIT frame.
956 //
957 // Tracing of formal arguments of an Ion frame is taken care of by the frame's
958 // safepoint/snapshot. We skip tracing formal arguments if the script doesn't
959 // use |arguments| or rest, because the register allocator can spill values to
960 // argument slots in this case.
961 //
962 // For other frames such as LazyLink frames or InterpreterStub frames, we
963 // always trace all actual and formal arguments.
964
965 if (!CalleeTokenIsFunction(layout->calleeToken())) {
966 return;
967 }
968
969 JSFunction* fun = CalleeTokenToFunction(layout->calleeToken());
970
971 size_t numFormals = fun->nargs();
972 size_t numArgs = std::max(layout->numActualArgs(), numFormals);
973 size_t firstArg = 0;
974
975 if (frame.isIonScripted() &&
976 !fun->nonLazyScript()->mayReadFrameArgsDirectly()) {
977 firstArg = numFormals;
978 }
979
980 Value* argv = layout->thisAndActualArgs();
981
982 // Trace |this|.
983 TraceRoot(trc, argv, "jit-thisv");
984
985 // Trace arguments. Note + 1 for thisv.
986 for (size_t i = firstArg; i < numArgs; i++) {
987 TraceRoot(trc, &argv[i + 1], "jit-argv");
988 }
989
990 // Always trace the new.target from the frame. It's not in the snapshots.
991 // +1 to pass |this|
992 if (CalleeTokenIsConstructing(layout->calleeToken())) {
993 TraceRoot(trc, &argv[1 + numArgs], "jit-newTarget");
994 }
995 }
996
997 #ifdef JS_NUNBOX32
998 static inline void WriteAllocation(const JSJitFrameIter& frame,
999 const LAllocation* a, uintptr_t value) {
1000 if (a->isGeneralReg()) {
1001 Register reg = a->toGeneralReg()->reg();
1002 frame.machineState().write(reg, value);
1003 } else {
1004 *frame.jsFrame()->slotRef(SafepointSlotEntry(a)) = value;
1005 }
1006 }
1007 #endif
1008
1009 static void TraceIonJSFrame(JSTracer* trc, const JSJitFrameIter& frame) {
1010 JitFrameLayout* layout = (JitFrameLayout*)frame.fp();
1011
1012 layout->replaceCalleeToken(TraceCalleeToken(trc, layout->calleeToken()));
1013
1014 IonScript* ionScript = nullptr;
1015 if (frame.checkInvalidation(&ionScript)) {
1016 // This frame has been invalidated, meaning that its IonScript is no
1017 // longer reachable through the callee token (JSFunction/JSScript->ion
1018 // is now nullptr or recompiled). Manually trace it here.
1019 ionScript->trace(trc);
1020 } else {
1021 ionScript = frame.ionScriptFromCalleeToken();
1022 }
1023
1024 TraceThisAndArguments(trc, frame, frame.jsFrame());
1025
1026 const SafepointIndex* si =
1027 ionScript->getSafepointIndex(frame.resumePCinCurrentFrame());
1028
1029 SafepointReader safepoint(ionScript, si);
1030
1031 // Scan through slots which contain pointers (or on punboxing systems,
1032 // actual values).
1033 SafepointSlotEntry entry;
1034
1035 while (safepoint.getGcSlot(&entry)) {
1036 uintptr_t* ref = layout->slotRef(entry);
1037 TraceGenericPointerRoot(trc, reinterpret_cast<gc::Cell**>(ref),
1038 "ion-gc-slot");
1039 }
1040
1041 uintptr_t* spill = frame.spillBase();
1042 LiveGeneralRegisterSet gcRegs = safepoint.gcSpills();
1043 LiveGeneralRegisterSet valueRegs = safepoint.valueSpills();
1044 LiveGeneralRegisterSet wasmAnyRefRegs = safepoint.wasmAnyRefSpills();
1045 for (GeneralRegisterBackwardIterator iter(safepoint.allGprSpills());
1046 iter.more(); ++iter) {
1047 --spill;
1048 if (gcRegs.has(*iter)) {
1049 TraceGenericPointerRoot(trc, reinterpret_cast<gc::Cell**>(spill),
1050 "ion-gc-spill");
1051 } else if (valueRegs.has(*iter)) {
1052 TraceRoot(trc, reinterpret_cast<Value*>(spill), "ion-value-spill");
1053 } else if (wasmAnyRefRegs.has(*iter)) {
1054 TraceRoot(trc, reinterpret_cast<wasm::AnyRef*>(spill),
1055 "ion-anyref-spill");
1056 }
1057 }
1058
1059 #ifdef JS_PUNBOX64
1060 while (safepoint.getValueSlot(&entry)) {
1061 Value* v = (Value*)layout->slotRef(entry);
1062 TraceRoot(trc, v, "ion-gc-slot");
1063 }
1064 #else
1065 LAllocation type, payload;
1066 while (safepoint.getNunboxSlot(&type, &payload)) {
1067 JSValueTag tag = JSValueTag(ReadAllocation(frame, &type));
1068 uintptr_t rawPayload = ReadAllocation(frame, &payload);
1069
1070 Value v = Value::fromTagAndPayload(tag, rawPayload);
1071 TraceRoot(trc, &v, "ion-torn-value");
1072
1073 if (v != Value::fromTagAndPayload(tag, rawPayload)) {
1074 // GC moved the value, replace the stored payload.
1075 rawPayload = v.toNunboxPayload();
1076 WriteAllocation(frame, &payload, rawPayload);
1077 }
1078 }
1079 #endif
1080
1081 // Skip over slots/elements to get to wasm anyrefs
1082 while (safepoint.getSlotsOrElementsSlot(&entry)) {
1083 }
1084
1085 while (safepoint.getWasmAnyRefSlot(&entry)) {
1086 wasm::AnyRef* v = (wasm::AnyRef*)layout->slotRef(entry);
1087 TraceRoot(trc, v, "ion-wasm-anyref-slot");
1088 }
1089 }
1090
1091 static void TraceBailoutFrame(JSTracer* trc, const JSJitFrameIter& frame) {
1092 JitFrameLayout* layout = (JitFrameLayout*)frame.fp();
1093
1094 layout->replaceCalleeToken(TraceCalleeToken(trc, layout->calleeToken()));
1095
1096 // We have to trace the list of actual arguments, as only formal arguments
1097 // are represented in the Snapshot.
1098 TraceThisAndArguments(trc, frame, frame.jsFrame());
1099
1100 // Under a bailout, do not have a Safepoint to only iterate over GC-things.
1101 // Thus we use a SnapshotIterator to trace all the locations which would be
1102 // used to reconstruct the Baseline frame.
1103 //
1104 // Note that at the time where this function is called, we have not yet
1105 // started to reconstruct baseline frames.
1106
1107 // The vector of recover instructions is already traced as part of the
1108 // JitActivation.
1109 SnapshotIterator snapIter(frame,
1110 frame.activation()->bailoutData()->machineState());
1111
1112 // For each instruction, we read the allocations without evaluating the
1113 // recover instruction, nor reconstructing the frame. We are only looking at
1114 // tracing readable allocations.
1115 while (true) {
1116 while (snapIter.moreAllocations()) {
1117 snapIter.traceAllocation(trc);
1118 }
1119
1120 if (!snapIter.moreInstructions()) {
1121 break;
1122 }
1123 snapIter.nextInstruction();
1124 }
1125 }
1126
1127 static void UpdateIonJSFrameForMinorGC(JSRuntime* rt,
1128 const JSJitFrameIter& frame) {
1129 // Minor GCs may move slots/elements allocated in the nursery. Update
1130 // any slots/elements pointers stored in this frame.
1131
1132 JitFrameLayout* layout = (JitFrameLayout*)frame.fp();
1133
1134 IonScript* ionScript = nullptr;
1135 if (frame.checkInvalidation(&ionScript)) {
1136 // This frame has been invalidated, meaning that its IonScript is no
1137 // longer reachable through the callee token (JSFunction/JSScript->ion
1138 // is now nullptr or recompiled).
1139 } else {
1140 ionScript = frame.ionScriptFromCalleeToken();
1141 }
1142
1143 Nursery& nursery = rt->gc.nursery();
1144
1145 const SafepointIndex* si =
1146 ionScript->getSafepointIndex(frame.resumePCinCurrentFrame());
1147 SafepointReader safepoint(ionScript, si);
1148
1149 LiveGeneralRegisterSet slotsRegs = safepoint.slotsOrElementsSpills();
1150 uintptr_t* spill = frame.spillBase();
1151 for (GeneralRegisterBackwardIterator iter(safepoint.allGprSpills());
1152 iter.more(); ++iter) {
1153 --spill;
1154 if (slotsRegs.has(*iter)) {
1155 nursery.forwardBufferPointer(spill);
1156 }
1157 }
1158
1159 // Skip to the right place in the safepoint
1160 SafepointSlotEntry entry;
1161 while (safepoint.getGcSlot(&entry)) {
1162 }
1163
1164 #ifdef JS_PUNBOX64
1165 while (safepoint.getValueSlot(&entry)) {
1166 }
1167 #else
1168 LAllocation type, payload;
1169 while (safepoint.getNunboxSlot(&type, &payload)) {
1170 }
1171 #endif
1172
1173 while (safepoint.getSlotsOrElementsSlot(&entry)) {
1174 nursery.forwardBufferPointer(layout->slotRef(entry));
1175 }
1176 }
1177
1178 static void TraceBaselineStubFrame(JSTracer* trc, const JSJitFrameIter& frame) {
1179 // Trace the ICStub pointer stored in the stub frame. This is necessary
1180 // so that we don't destroy the stub code after unlinking the stub.
1181
1182 MOZ_ASSERT(frame.type() == FrameType::BaselineStub);
1183 BaselineStubFrameLayout* layout = (BaselineStubFrameLayout*)frame.fp();
1184
1185 if (ICStub* stub = layout->maybeStubPtr()) {
1186 if (stub->isFallback()) {
1187 // Fallback stubs use runtime-wide trampoline code we don't need to trace.
1188 MOZ_ASSERT(stub->usesTrampolineCode());
1189 } else {
1190 MOZ_ASSERT(stub->toCacheIRStub()->makesGCCalls());
1191 stub->toCacheIRStub()->trace(trc);
1192
1193 #ifndef ENABLE_PORTABLE_BASELINE_INTERP
1194 for (int i = 0; i < stub->jitCode()->localTracingSlots(); ++i) {
1195 TraceRoot(trc, layout->locallyTracedValuePtr(i),
1196 "baseline-local-tracing-slot");
1197 }
1198 #endif
1199 }
1200 }
1201 }
1202
1203 static void TraceWeakBaselineStubFrame(JSTracer* trc,
1204 const JSJitFrameIter& frame) {
1205 MOZ_ASSERT(frame.type() == FrameType::BaselineStub);
1206 BaselineStubFrameLayout* layout = (BaselineStubFrameLayout*)frame.fp();
1207
1208 if (ICStub* stub = layout->maybeStubPtr()) {
1209 if (!stub->isFallback()) {
1210 MOZ_ASSERT(stub->toCacheIRStub()->makesGCCalls());
1211 stub->toCacheIRStub()->traceWeak(trc);
1212 }
1213 }
1214 }
1215
1216 static void TraceIonICCallFrame(JSTracer* trc, const JSJitFrameIter& frame) {
1217 MOZ_ASSERT(frame.type() == FrameType::IonICCall);
1218 IonICCallFrameLayout* layout = (IonICCallFrameLayout*)frame.fp();
1219 TraceRoot(trc, layout->stubCode(), "ion-ic-call-code");
1220
1221 for (int i = 0; i < (*layout->stubCode())->localTracingSlots(); ++i) {
1222 TraceRoot(trc, layout->locallyTracedValuePtr(i),
1223 "ion-ic-local-tracing-slot");
1224 }
1225 }
1226
1227 #if defined(JS_CODEGEN_ARM64)
1228 uint8_t* alignDoubleSpill(uint8_t* pointer) {
1229 uintptr_t address = reinterpret_cast<uintptr_t>(pointer);
1230 address &= ~(uintptr_t(ABIStackAlignment) - 1);
1231 return reinterpret_cast<uint8_t*>(address);
1232 }
1233 #endif
1234
1235 static void TraceJitExitFrame(JSTracer* trc, const JSJitFrameIter& frame) {
1236 ExitFooterFrame* footer = frame.exitFrame()->footer();
1237
1238 // This corresponds to the case where we have build a fake exit frame which
1239 // handles the case of a native function call. We need to trace the argument
1240 // vector of the function call, and also new.target if it was a constructing
1241 // call.
1242 if (frame.isExitFrameLayout<NativeExitFrameLayout>()) {
1243 NativeExitFrameLayout* native =
1244 frame.exitFrame()->as<NativeExitFrameLayout>();
1245 size_t len = native->argc() + 2;
1246 Value* vp = native->vp();
1247 TraceRootRange(trc, len, vp, "ion-native-args");
1248 if (frame.isExitFrameLayout<ConstructNativeExitFrameLayout>()) {
1249 TraceRoot(trc, vp + len, "ion-native-new-target");
1250 }
1251 return;
1252 }
1253
1254 if (frame.isExitFrameLayout<IonOOLNativeExitFrameLayout>()) {
1255 IonOOLNativeExitFrameLayout* oolnative =
1256 frame.exitFrame()->as<IonOOLNativeExitFrameLayout>();
1257 TraceRoot(trc, oolnative->stubCode(), "ion-ool-native-code");
1258 TraceRoot(trc, oolnative->vp(), "iol-ool-native-vp");
1259 size_t len = oolnative->argc() + 1;
1260 TraceRootRange(trc, len, oolnative->thisp(), "ion-ool-native-thisargs");
1261 return;
1262 }
1263
1264 if (frame.isExitFrameLayout<IonOOLProxyExitFrameLayout>()) {
1265 IonOOLProxyExitFrameLayout* oolproxy =
1266 frame.exitFrame()->as<IonOOLProxyExitFrameLayout>();
1267 TraceRoot(trc, oolproxy->stubCode(), "ion-ool-proxy-code");
1268 TraceRoot(trc, oolproxy->vp(), "ion-ool-proxy-vp");
1269 TraceRoot(trc, oolproxy->id(), "ion-ool-proxy-id");
1270 TraceRoot(trc, oolproxy->proxy(), "ion-ool-proxy-proxy");
1271 return;
1272 }
1273
1274 if (frame.isExitFrameLayout<IonDOMExitFrameLayout>()) {
1275 IonDOMExitFrameLayout* dom = frame.exitFrame()->as<IonDOMExitFrameLayout>();
1276 TraceRoot(trc, dom->thisObjAddress(), "ion-dom-args");
1277 if (dom->isMethodFrame()) {
1278 IonDOMMethodExitFrameLayout* method =
1279 reinterpret_cast<IonDOMMethodExitFrameLayout*>(dom);
1280 size_t len = method->argc() + 2;
1281 Value* vp = method->vp();
1282 TraceRootRange(trc, len, vp, "ion-dom-args");
1283 } else {
1284 TraceRoot(trc, dom->vp(), "ion-dom-args");
1285 }
1286 return;
1287 }
1288
1289 if (frame.isExitFrameLayout<CalledFromJitExitFrameLayout>()) {
1290 auto* layout = frame.exitFrame()->as<CalledFromJitExitFrameLayout>();
1291 JitFrameLayout* jsLayout = layout->jsFrame();
1292 jsLayout->replaceCalleeToken(
1293 TraceCalleeToken(trc, jsLayout->calleeToken()));
1294 TraceThisAndArguments(trc, frame, jsLayout);
1295 return;
1296 }
1297
1298 if (frame.isExitFrameLayout<DirectWasmJitCallFrameLayout>()) {
1299 // Nothing needs to be traced here at the moment -- the arguments to the
1300 // callee are traced by the callee, and the inlined caller does not push
1301 // anything else.
1302 return;
1303 }
1304
1305 if (frame.isBareExit() || frame.isUnwoundJitExit()) {
1306 // Nothing to trace. Fake exit frame pushed for VM functions with
1307 // nothing to trace on the stack or unwound JitFrameLayout.
1308 return;
1309 }
1310
1311 MOZ_ASSERT(frame.exitFrame()->isWrapperExit());
1312
1313 const VMFunctionData& f = GetVMFunction(footer->functionId());
1314
1315 // Trace arguments of the VM wrapper.
1316 uint8_t* argBase = frame.exitFrame()->argBase();
1317 for (uint32_t explicitArg = 0; explicitArg < f.explicitArgs; explicitArg++) {
1318 switch (f.argRootType(explicitArg)) {
1319 case VMFunctionData::RootNone:
1320 break;
1321 case VMFunctionData::RootObject: {
1322 // Sometimes we can bake in HandleObjects to nullptr.
1323 JSObject** pobj = reinterpret_cast<JSObject**>(argBase);
1324 if (*pobj) {
1325 TraceRoot(trc, pobj, "ion-vm-args");
1326 }
1327 break;
1328 }
1329 case VMFunctionData::RootString:
1330 TraceRoot(trc, reinterpret_cast<JSString**>(argBase), "ion-vm-args");
1331 break;
1332 case VMFunctionData::RootValue:
1333 TraceRoot(trc, reinterpret_cast<Value*>(argBase), "ion-vm-args");
1334 break;
1335 case VMFunctionData::RootId:
1336 TraceRoot(trc, reinterpret_cast<jsid*>(argBase), "ion-vm-args");
1337 break;
1338 case VMFunctionData::RootCell:
1339 TraceGenericPointerRoot(trc, reinterpret_cast<gc::Cell**>(argBase),
1340 "ion-vm-args");
1341 break;
1342 case VMFunctionData::RootBigInt:
1343 TraceRoot(trc, reinterpret_cast<JS::BigInt**>(argBase), "ion-vm-args");
1344 break;
1345 }
1346
1347 switch (f.argProperties(explicitArg)) {
1348 case VMFunctionData::WordByValue:
1349 case VMFunctionData::WordByRef:
1350 argBase += sizeof(void*);
1351 break;
1352 case VMFunctionData::DoubleByValue:
1353 case VMFunctionData::DoubleByRef:
1354 argBase += 2 * sizeof(void*);
1355 break;
1356 }
1357 }
1358
1359 if (f.outParam == Type_Handle) {
1360 switch (f.outParamRootType) {
1361 case VMFunctionData::RootNone:
1362 MOZ_CRASH("Handle outparam must have root type");
1363 case VMFunctionData::RootObject:
1364 TraceRoot(trc, footer->outParam<JSObject*>(), "ion-vm-out");
1365 break;
1366 case VMFunctionData::RootString:
1367 TraceRoot(trc, footer->outParam<JSString*>(), "ion-vm-out");
1368 break;
1369 case VMFunctionData::RootValue:
1370 TraceRoot(trc, footer->outParam<Value>(), "ion-vm-outvp");
1371 break;
1372 case VMFunctionData::RootId:
1373 TraceRoot(trc, footer->outParam<jsid>(), "ion-vm-outvp");
1374 break;
1375 case VMFunctionData::RootCell:
1376 TraceGenericPointerRoot(trc, footer->outParam<gc::Cell*>(),
1377 "ion-vm-out");
1378 break;
1379 case VMFunctionData::RootBigInt:
1380 TraceRoot(trc, footer->outParam<JS::BigInt*>(), "ion-vm-out");
1381 break;
1382 }
1383 }
1384 }
1385
1386 static void TraceBaselineInterpreterEntryFrame(JSTracer* trc,
1387 const JSJitFrameIter& frame) {
1388 // Baseline Interpreter entry code generated under --emit-interpreter-entry.
1389 BaselineInterpreterEntryFrameLayout* layout =
1390 (BaselineInterpreterEntryFrameLayout*)frame.fp();
1391 layout->replaceCalleeToken(TraceCalleeToken(trc, layout->calleeToken()));
1392 TraceThisAndArguments(trc, frame, layout);
1393 }
1394
1395 static void TraceRectifierFrame(JSTracer* trc, const JSJitFrameIter& frame) {
1396 // Trace thisv.
1397 //
1398 // Baseline JIT code generated as part of the ICCall_Fallback stub may use
1399 // it if we're calling a constructor that returns a primitive value.
1400 RectifierFrameLayout* layout = (RectifierFrameLayout*)frame.fp();
1401 TraceRoot(trc, &layout->thisv(), "rectifier-thisv");
1402 }
1403
1404 static void TraceTrampolineNativeFrame(JSTracer* trc,
1405 const JSJitFrameIter& frame) {
1406 auto* layout = (TrampolineNativeFrameLayout*)frame.fp();
1407 layout->replaceCalleeToken(TraceCalleeToken(trc, layout->calleeToken()));
1408 TraceThisAndArguments(trc, frame, layout);
1409
1410 TrampolineNative native = TrampolineNativeForFrame(trc->runtime(), layout);
1411 switch (native) {
1412 case TrampolineNative::ArraySort:
1413 case TrampolineNative::TypedArraySort:
1414 layout->getFrameData<ArraySortData>()->trace(trc);
1415 break;
1416 case TrampolineNative::Count:
1417 MOZ_CRASH("Invalid value");
1418 }
1419 }
1420
1421 static void TraceJitActivation(JSTracer* trc, JitActivation* activation) {
1422 #ifdef CHECK_OSIPOINT_REGISTERS
1423 if (JitOptions.checkOsiPointRegisters) {
1424 // GC can modify spilled registers, breaking our register checks.
1425 // To handle this, we disable these checks for the current VM call
1426 // when a GC happens.
1427 activation->setCheckRegs(false);
1428 }
1429 #endif
1430
1431 activation->traceRematerializedFrames(trc);
1432 activation->traceIonRecovery(trc);
1433
1434 // This is used for sanity checking continuity of the sequence of wasm stack
1435 // maps as we unwind. It has no functional purpose.
1436 uintptr_t highestByteVisitedInPrevWasmFrame = 0;
1437
1438 for (JitFrameIter frames(activation); !frames.done(); ++frames) {
1439 if (frames.isJSJit()) {
1440 const JSJitFrameIter& jitFrame = frames.asJSJit();
1441 switch (jitFrame.type()) {
1442 case FrameType::Exit:
1443 TraceJitExitFrame(trc, jitFrame);
1444 break;
1445 case FrameType::BaselineJS:
1446 jitFrame.baselineFrame()->trace(trc, jitFrame);
1447 break;
1448 case FrameType::IonJS:
1449 TraceIonJSFrame(trc, jitFrame);
1450 break;
1451 case FrameType::BaselineStub:
1452 TraceBaselineStubFrame(trc, jitFrame);
1453 break;
1454 case FrameType::Bailout:
1455 TraceBailoutFrame(trc, jitFrame);
1456 break;
1457 case FrameType::BaselineInterpreterEntry:
1458 TraceBaselineInterpreterEntryFrame(trc, jitFrame);
1459 break;
1460 case FrameType::Rectifier:
1461 TraceRectifierFrame(trc, jitFrame);
1462 break;
1463 case FrameType::TrampolineNative:
1464 TraceTrampolineNativeFrame(trc, jitFrame);
1465 break;
1466 case FrameType::IonICCall:
1467 TraceIonICCallFrame(trc, jitFrame);
1468 break;
1469 case FrameType::WasmToJSJit:
1470 // Ignore: this is a special marker used to let the
1471 // JitFrameIter know the frame above is a wasm frame, handled
1472 // in the next iteration.
1473 break;
1474 default:
1475 MOZ_CRASH("unexpected frame type");
1476 }
1477 highestByteVisitedInPrevWasmFrame = 0; /* "unknown" */
1478 } else {
1479 gc::AssertRootMarkingPhase(trc);
1480 MOZ_ASSERT(frames.isWasm());
1481 uint8_t* nextPC = frames.resumePCinCurrentFrame();
1482 MOZ_ASSERT(nextPC != 0);
1483 wasm::WasmFrameIter& wasmFrameIter = frames.asWasm();
1484 #ifdef ENABLE_WASM_JSPI
1485 if (wasmFrameIter.currentFrameStackSwitched()) {
1486 highestByteVisitedInPrevWasmFrame = 0;
1487 }
1488 #endif
1489 wasm::Instance* instance = wasmFrameIter.instance();
1490 wasm::TraceInstanceEdge(trc, instance, "WasmFrameIter instance");
1491 highestByteVisitedInPrevWasmFrame = instance->traceFrame(
1492 trc, wasmFrameIter, nextPC, highestByteVisitedInPrevWasmFrame);
1493 }
1494 }
1495 }
1496
1497 void TraceJitActivations(JSContext* cx, JSTracer* trc) {
1498 for (JitActivationIterator activations(cx); !activations.done();
1499 ++activations) {
1500 TraceJitActivation(trc, activations->asJit());
1501 }
1502 #ifdef ENABLE_WASM_JSPI
1503 cx->wasm().promiseIntegration.traceRoots(trc);
1504 #endif
1505 }
1506
1507 void TraceWeakJitActivationsInSweepingZones(JSContext* cx, JSTracer* trc) {
1508 for (JitActivationIterator activation(cx); !activation.done(); ++activation) {
1509 if (activation->compartment()->zone()->isGCSweeping()) {
1510 for (JitFrameIter frame(activation->asJit()); !frame.done(); ++frame) {
1511 if (frame.isJSJit()) {
1512 const JSJitFrameIter& jitFrame = frame.asJSJit();
1513 if (jitFrame.type() == FrameType::BaselineStub) {
1514 TraceWeakBaselineStubFrame(trc, jitFrame);
1515 }
1516 }
1517 }
1518 }
1519 }
1520 }
1521
1522 void UpdateJitActivationsForMinorGC(JSRuntime* rt) {
1523 MOZ_ASSERT(JS::RuntimeHeapIsMinorCollecting());
1524 JSContext* cx = rt->mainContextFromOwnThread();
1525 for (JitActivationIterator activations(cx); !activations.done();
1526 ++activations) {
1527 for (JitFrameIter iter(activations->asJit()); !iter.done(); ++iter) {
1528 if (iter.isJSJit()) {
1529 const JSJitFrameIter& jitFrame = iter.asJSJit();
1530 if (jitFrame.type() == FrameType::IonJS) {
1531 UpdateIonJSFrameForMinorGC(rt, jitFrame);
1532 }
1533 } else if (iter.isWasm()) {
1534 const wasm::WasmFrameIter& frame = iter.asWasm();
1535 frame.instance()->updateFrameForMovingGC(
1536 frame, frame.resumePCinCurrentFrame());
1537 }
1538 }
1539 }
1540 }
1541
1542 void UpdateJitActivationsForCompactingGC(JSRuntime* rt) {
1543 MOZ_ASSERT(JS::RuntimeHeapIsMajorCollecting());
1544 JSContext* cx = rt->mainContextFromOwnThread();
1545 for (JitActivationIterator activations(cx); !activations.done();
1546 ++activations) {
1547 for (JitFrameIter iter(activations->asJit()); !iter.done(); ++iter) {
1548 if (iter.isWasm()) {
1549 const wasm::WasmFrameIter& frame = iter.asWasm();
1550 frame.instance()->updateFrameForMovingGC(
1551 frame, frame.resumePCinCurrentFrame());
1552 }
1553 }
1554 }
1555 }
1556
1557 JSScript* GetTopJitJSScript(JSContext* cx) {
1558 JSJitFrameIter frame(cx->activation()->asJit());
1559 MOZ_ASSERT(frame.type() == FrameType::Exit);
1560 ++frame;
1561
1562 if (frame.isBaselineStub()) {
1563 ++frame;
1564 MOZ_ASSERT(frame.isBaselineJS());
1565 }
1566
1567 MOZ_ASSERT(frame.isScripted());
1568 return frame.script();
1569 }
1570
1571 RInstructionResults::RInstructionResults(JitFrameLayout* fp)
1572 : results_(nullptr), fp_(fp), initialized_(false) {}
1573
1574 RInstructionResults::RInstructionResults(RInstructionResults&& src)
1575 : results_(std::move(src.results_)),
1576 fp_(src.fp_),
1577 initialized_(src.initialized_) {
1578 src.initialized_ = false;
1579 }
1580
1581 RInstructionResults& RInstructionResults::operator=(RInstructionResults&& rhs) {
1582 MOZ_ASSERT(&rhs != this, "self-moves are prohibited");
1583 this->~RInstructionResults();
1584 new (this) RInstructionResults(std::move(rhs));
1585 return *this;
1586 }
1587
1588 RInstructionResults::~RInstructionResults() {
1589 // results_ is freed by the UniquePtr.
1590 }
1591
1592 bool RInstructionResults::init(JSContext* cx, uint32_t numResults) {
1593 if (numResults) {
1594 results_ = cx->make_unique<Values>();
1595 if (!results_) {
1596 return false;
1597 }
1598 if (!results_->growBy(numResults)) {
1599 ReportOutOfMemory(cx);
1600 return false;
1601 }
1602
1603 Value guard = MagicValue(JS_ION_BAILOUT);
1604 for (size_t i = 0; i < numResults; i++) {
1605 (*results_)[i].init(guard);
1606 }
1607 }
1608
1609 initialized_ = true;
1610 return true;
1611 }
1612
1613 bool RInstructionResults::isInitialized() const { return initialized_; }
1614
1615 size_t RInstructionResults::length() const { return results_->length(); }
1616
1617 JitFrameLayout* RInstructionResults::frame() const {
1618 MOZ_ASSERT(fp_);
1619 return fp_;
1620 }
1621
1622 HeapPtr<Value>& RInstructionResults::operator[](size_t index) {
1623 return (*results_)[index];
1624 }
1625
1626 void RInstructionResults::trace(JSTracer* trc) {
1627 // Note: The vector necessary exists, otherwise this object would not have
1628 // been stored on the activation from where the trace function is called.
1629 TraceRange(trc, results_->length(), results_->begin(), "ion-recover-results");
1630 }
1631
1632 SnapshotIterator::SnapshotIterator(const JSJitFrameIter& iter,
1633 const MachineState* machineState)
1634 : snapshot_(iter.ionScript()->snapshots(), iter.snapshotOffset(),
1635 iter.ionScript()->snapshotsRVATableSize(),
1636 iter.ionScript()->snapshotsListSize()),
1637 recover_(snapshot_, iter.ionScript()->recovers(),
1638 iter.ionScript()->recoversSize()),
1639 fp_(iter.jsFrame()),
1640 machine_(machineState),
1641 ionScript_(iter.ionScript()),
1642 instructionResults_(nullptr) {}
1643
1644 SnapshotIterator::SnapshotIterator()
1645 : snapshot_(nullptr, 0, 0, 0),
1646 recover_(snapshot_, nullptr, 0),
1647 fp_(nullptr),
1648 machine_(nullptr),
1649 ionScript_(nullptr),
1650 instructionResults_(nullptr) {}
1651
1652 uintptr_t SnapshotIterator::fromStack(int32_t offset) const {
1653 return ReadFrameSlot(fp_, offset);
1654 }
1655
1656 static Value FromObjectPayload(uintptr_t payload) {
1657 MOZ_ASSERT(payload != 0);
1658 return ObjectValue(*reinterpret_cast<JSObject*>(payload));
1659 }
1660
1661 static Value FromStringPayload(uintptr_t payload) {
1662 return StringValue(reinterpret_cast<JSString*>(payload));
1663 }
1664
1665 static Value FromSymbolPayload(uintptr_t payload) {
1666 return SymbolValue(reinterpret_cast<JS::Symbol*>(payload));
1667 }
1668
1669 static Value FromBigIntPayload(uintptr_t payload) {
1670 return BigIntValue(reinterpret_cast<JS::BigInt*>(payload));
1671 }
1672
1673 static Value FromTypedPayload(JSValueType type, uintptr_t payload) {
1674 switch (type) {
1675 case JSVAL_TYPE_INT32:
1676 return Int32Value(payload);
1677 case JSVAL_TYPE_BOOLEAN:
1678 return BooleanValue(!!payload);
1679 case JSVAL_TYPE_STRING:
1680 return FromStringPayload(payload);
1681 case JSVAL_TYPE_SYMBOL:
1682 return FromSymbolPayload(payload);
1683 case JSVAL_TYPE_BIGINT:
1684 return FromBigIntPayload(payload);
1685 case JSVAL_TYPE_OBJECT:
1686 return FromObjectPayload(payload);
1687 default:
1688 MOZ_CRASH("unexpected type - needs payload");
1689 }
1690 }
1691
1692 bool SnapshotIterator::allocationReadable(const RValueAllocation& alloc,
1693 ReadMethod rm) {
1694 // If we have to recover stores, and if we are not interested in the
1695 // default value of the instruction, then we have to check if the recover
1696 // instruction results are available.
1697 if (alloc.needSideEffect() && rm != ReadMethod::AlwaysDefault) {
1698 if (!hasInstructionResults()) {
1699 return false;
1700 }
1701 }
1702
1703 switch (alloc.mode()) {
1704 case RValueAllocation::DOUBLE_REG:
1705 return hasRegister(alloc.fpuReg());
1706
1707 case RValueAllocation::TYPED_REG:
1708 return hasRegister(alloc.reg2());
1709
1710 #if defined(JS_NUNBOX32)
1711 case RValueAllocation::UNTYPED_REG_REG:
1712 return hasRegister(alloc.reg()) && hasRegister(alloc.reg2());
1713 case RValueAllocation::UNTYPED_REG_STACK:
1714 return hasRegister(alloc.reg()) && hasStack(alloc.stackOffset2());
1715 case RValueAllocation::UNTYPED_STACK_REG:
1716 return hasStack(alloc.stackOffset()) && hasRegister(alloc.reg2());
1717 case RValueAllocation::UNTYPED_STACK_STACK:
1718 return hasStack(alloc.stackOffset()) && hasStack(alloc.stackOffset2());
1719 #elif defined(JS_PUNBOX64)
1720 case RValueAllocation::UNTYPED_REG:
1721 return hasRegister(alloc.reg());
1722 case RValueAllocation::UNTYPED_STACK:
1723 return hasStack(alloc.stackOffset());
1724 #endif
1725
1726 case RValueAllocation::RECOVER_INSTRUCTION:
1727 return hasInstructionResult(alloc.index());
1728 case RValueAllocation::RI_WITH_DEFAULT_CST:
1729 return rm == ReadMethod::AlwaysDefault ||
1730 hasInstructionResult(alloc.index());
1731
1732 case RValueAllocation::INTPTR_REG:
1733 return hasRegister(alloc.reg());
1734 case RValueAllocation::INTPTR_STACK:
1735 case RValueAllocation::INTPTR_INT32_STACK:
1736 return hasStack(alloc.stackOffset());
1737
1738 #if defined(JS_NUNBOX32)
1739 case RValueAllocation::INT64_REG_REG:
1740 return hasRegister(alloc.reg()) && hasRegister(alloc.reg2());
1741 case RValueAllocation::INT64_REG_STACK:
1742 return hasRegister(alloc.reg()) && hasStack(alloc.stackOffset2());
1743 case RValueAllocation::INT64_STACK_REG:
1744 return hasStack(alloc.stackOffset()) && hasRegister(alloc.reg2());
1745 case RValueAllocation::INT64_STACK_STACK:
1746 return hasStack(alloc.stackOffset()) && hasStack(alloc.stackOffset2());
1747 #elif defined(JS_PUNBOX64)
1748 case RValueAllocation::INT64_REG:
1749 return hasRegister(alloc.reg());
1750 case RValueAllocation::INT64_STACK:
1751 case RValueAllocation::INT64_INT32_STACK:
1752 return hasStack(alloc.stackOffset());
1753 #endif
1754
1755 default:
1756 return true;
1757 }
1758 }
1759
1760 Value SnapshotIterator::allocationValue(const RValueAllocation& alloc,
1761 ReadMethod rm) {
1762 switch (alloc.mode()) {
1763 case RValueAllocation::CONSTANT:
1764 return ionScript_->getConstant(alloc.index());
1765
1766 case RValueAllocation::CST_UNDEFINED:
1767 return UndefinedValue();
1768
1769 case RValueAllocation::CST_NULL:
1770 return NullValue();
1771
1772 case RValueAllocation::DOUBLE_REG:
1773 return DoubleValue(fromRegister<double>(alloc.fpuReg()));
1774
1775 case RValueAllocation::FLOAT32_REG:
1776 return Float32Value(fromRegister<float>(alloc.fpuReg()));
1777
1778 case RValueAllocation::FLOAT32_STACK:
1779 return Float32Value(ReadFrameFloat32Slot(fp_, alloc.stackOffset()));
1780
1781 case RValueAllocation::TYPED_REG:
1782 return FromTypedPayload(alloc.knownType(), fromRegister(alloc.reg2()));
1783
1784 case RValueAllocation::TYPED_STACK: {
1785 switch (alloc.knownType()) {
1786 case JSVAL_TYPE_DOUBLE:
1787 return DoubleValue(ReadFrameDoubleSlot(fp_, alloc.stackOffset2()));
1788 case JSVAL_TYPE_INT32:
1789 return Int32Value(ReadFrameInt32Slot(fp_, alloc.stackOffset2()));
1790 case JSVAL_TYPE_BOOLEAN:
1791 return BooleanValue(ReadFrameBooleanSlot(fp_, alloc.stackOffset2()));
1792 case JSVAL_TYPE_STRING:
1793 return FromStringPayload(fromStack(alloc.stackOffset2()));
1794 case JSVAL_TYPE_SYMBOL:
1795 return FromSymbolPayload(fromStack(alloc.stackOffset2()));
1796 case JSVAL_TYPE_BIGINT:
1797 return FromBigIntPayload(fromStack(alloc.stackOffset2()));
1798 case JSVAL_TYPE_OBJECT:
1799 return FromObjectPayload(fromStack(alloc.stackOffset2()));
1800 default:
1801 MOZ_CRASH("Unexpected type");
1802 }
1803 }
1804
1805 #if defined(JS_NUNBOX32)
1806 case RValueAllocation::UNTYPED_REG_REG: {
1807 return Value::fromTagAndPayload(JSValueTag(fromRegister(alloc.reg())),
1808 fromRegister(alloc.reg2()));
1809 }
1810
1811 case RValueAllocation::UNTYPED_REG_STACK: {
1812 return Value::fromTagAndPayload(JSValueTag(fromRegister(alloc.reg())),
1813 fromStack(alloc.stackOffset2()));
1814 }
1815
1816 case RValueAllocation::UNTYPED_STACK_REG: {
1817 return Value::fromTagAndPayload(
1818 JSValueTag(fromStack(alloc.stackOffset())),
1819 fromRegister(alloc.reg2()));
1820 }
1821
1822 case RValueAllocation::UNTYPED_STACK_STACK: {
1823 return Value::fromTagAndPayload(
1824 JSValueTag(fromStack(alloc.stackOffset())),
1825 fromStack(alloc.stackOffset2()));
1826 }
1827 #elif defined(JS_PUNBOX64)
1828 case RValueAllocation::UNTYPED_REG: {
1829 return Value::fromRawBits(fromRegister(alloc.reg()));
1830 }
1831
1832 case RValueAllocation::UNTYPED_STACK: {
1833 return Value::fromRawBits(fromStack(alloc.stackOffset()));
1834 }
1835 #endif
1836
1837 case RValueAllocation::RECOVER_INSTRUCTION:
1838 return fromInstructionResult(alloc.index());
1839
1840 case RValueAllocation::RI_WITH_DEFAULT_CST:
1841 if (rm == ReadMethod::Normal && hasInstructionResult(alloc.index())) {
1842 return fromInstructionResult(alloc.index());
1843 }
1844 MOZ_ASSERT(rm == ReadMethod::AlwaysDefault);
1845 return ionScript_->getConstant(alloc.index2());
1846
1847 case RValueAllocation::INTPTR_CST:
1848 case RValueAllocation::INTPTR_REG:
1849 case RValueAllocation::INTPTR_STACK:
1850 case RValueAllocation::INTPTR_INT32_STACK:
1851 MOZ_CRASH("Can't read IntPtr as Value");
1852
1853 case RValueAllocation::INT64_CST:
1854 #if defined(JS_NUNBOX32)
1855 case RValueAllocation::INT64_REG_REG:
1856 case RValueAllocation::INT64_REG_STACK:
1857 case RValueAllocation::INT64_STACK_REG:
1858 case RValueAllocation::INT64_STACK_STACK:
1859 #elif defined(JS_PUNBOX64)
1860 case RValueAllocation::INT64_REG:
1861 case RValueAllocation::INT64_STACK:
1862 case RValueAllocation::INT64_INT32_STACK:
1863 #endif
1864 MOZ_CRASH("Can't read Int64 as Value");
1865
1866 default:
1867 MOZ_CRASH("huh?");
1868 }
1869 }
1870
1871 Value SnapshotIterator::maybeRead(const RValueAllocation& a,
1872 MaybeReadFallback& fallback) {
1873 if (allocationReadable(a)) {
1874 return allocationValue(a);
1875 }
1876
1877 if (fallback.canRecoverResults()) {
1878 // Code paths which are calling maybeRead are not always capable of
1879 // returning an error code, as these code paths used to be infallible.
1880 AutoEnterOOMUnsafeRegion oomUnsafe;
1881 if (!initInstructionResults(fallback)) {
1882 oomUnsafe.crash("js::jit::SnapshotIterator::maybeRead");
1883 }
1884
1885 if (allocationReadable(a)) {
1886 return allocationValue(a);
1887 }
1888
1889 MOZ_ASSERT_UNREACHABLE("All allocations should be readable.");
1890 }
1891
1892 return UndefinedValue();
1893 }
1894
1895 bool SnapshotIterator::tryRead(Value* result) {
1896 RValueAllocation a = readAllocation();
1897 if (allocationReadable(a)) {
1898 *result = allocationValue(a);
1899 return true;
1900 }
1901 return false;
1902 }
1903
1904 bool SnapshotIterator::readMaybeUnpackedBigInt(JSContext* cx,
1905 MutableHandle<Value> result) {
1906 RValueAllocation alloc = readAllocation();
1907 MOZ_ASSERT(allocationReadable(alloc));
1908
1909 switch (alloc.mode()) {
1910 case RValueAllocation::INT64_CST:
1911 #if defined(JS_NUNBOX32)
1912 case RValueAllocation::INT64_REG_REG:
1913 case RValueAllocation::INT64_REG_STACK:
1914 case RValueAllocation::INT64_STACK_REG:
1915 case RValueAllocation::INT64_STACK_STACK:
1916 #elif defined(JS_PUNBOX64)
1917 case RValueAllocation::INT64_REG:
1918 case RValueAllocation::INT64_STACK:
1919 case RValueAllocation::INT64_INT32_STACK:
1920 #endif
1921 {
1922 auto* bigInt = JS::BigInt::createFromInt64(cx, allocationInt64(alloc));
1923 if (!bigInt) {
1924 return false;
1925 }
1926 result.setBigInt(bigInt);
1927 return true;
1928 }
1929 case RValueAllocation::INTPTR_CST:
1930 case RValueAllocation::INTPTR_REG:
1931 case RValueAllocation::INTPTR_STACK:
1932 case RValueAllocation::INTPTR_INT32_STACK: {
1933 auto* bigInt = JS::BigInt::createFromIntPtr(cx, allocationIntPtr(alloc));
1934 if (!bigInt) {
1935 return false;
1936 }
1937 result.setBigInt(bigInt);
1938 return true;
1939 }
1940 default:
1941 result.set(allocationValue(alloc));
1942 return true;
1943 }
1944 }
1945
1946 int64_t SnapshotIterator::allocationInt64(const RValueAllocation& alloc) {
1947 MOZ_ASSERT(allocationReadable(alloc));
1948
1949 auto fromParts = [](uint32_t hi, uint32_t lo) {
1950 return static_cast<int64_t>((static_cast<uint64_t>(hi) << 32) | lo);
1951 };
1952
1953 switch (alloc.mode()) {
1954 case RValueAllocation::INT64_CST: {
1955 uint32_t lo = ionScript_->getConstant(alloc.index()).toInt32();
1956 uint32_t hi = ionScript_->getConstant(alloc.index2()).toInt32();
1957 return fromParts(hi, lo);
1958 }
1959 #if defined(JS_NUNBOX32)
1960 case RValueAllocation::INT64_REG_REG: {
1961 uintptr_t lo = fromRegister(alloc.reg());
1962 uintptr_t hi = fromRegister(alloc.reg2());
1963 return fromParts(hi, lo);
1964 }
1965 case RValueAllocation::INT64_REG_STACK: {
1966 uintptr_t lo = fromRegister(alloc.reg());
1967 uintptr_t hi = fromStack(alloc.stackOffset2());
1968 return fromParts(hi, lo);
1969 }
1970 case RValueAllocation::INT64_STACK_REG: {
1971 uintptr_t lo = fromStack(alloc.stackOffset());
1972 uintptr_t hi = fromRegister(alloc.reg2());
1973 return fromParts(hi, lo);
1974 }
1975 case RValueAllocation::INT64_STACK_STACK: {
1976 uintptr_t lo = fromStack(alloc.stackOffset());
1977 uintptr_t hi = fromStack(alloc.stackOffset2());
1978 return fromParts(hi, lo);
1979 }
1980 #elif defined(JS_PUNBOX64)
1981 case RValueAllocation::INT64_REG: {
1982 return static_cast<int64_t>(fromRegister(alloc.reg()));
1983 }
1984 case RValueAllocation::INT64_STACK: {
1985 return static_cast<int64_t>(fromStack(alloc.stackOffset()));
1986 }
1987 case RValueAllocation::INT64_INT32_STACK: {
1988 return static_cast<int64_t>(ReadFrameInt32Slot(fp_, alloc.stackOffset()));
1989 }
1990 #endif
1991 default:
1992 break;
1993 }
1994 MOZ_CRASH("invalid int64 allocation");
1995 }
1996
1997 intptr_t SnapshotIterator::allocationIntPtr(const RValueAllocation& alloc) {
1998 MOZ_ASSERT(allocationReadable(alloc));
1999 switch (alloc.mode()) {
2000 case RValueAllocation::INTPTR_CST: {
2001 #if !defined(JS_64BIT)
2002 int32_t cst = ionScript_->getConstant(alloc.index()).toInt32();
2003 return static_cast<intptr_t>(cst);
2004 #else
2005 uint32_t lo = ionScript_->getConstant(alloc.index()).toInt32();
2006 uint32_t hi = ionScript_->getConstant(alloc.index2()).toInt32();
2007 return static_cast<intptr_t>((static_cast<uint64_t>(hi) << 32) | lo);
2008 #endif
2009 }
2010 case RValueAllocation::INTPTR_REG:
2011 return static_cast<intptr_t>(fromRegister(alloc.reg()));
2012 case RValueAllocation::INTPTR_STACK:
2013 return static_cast<intptr_t>(fromStack(alloc.stackOffset()));
2014 case RValueAllocation::INTPTR_INT32_STACK:
2015 return static_cast<intptr_t>(
2016 ReadFrameInt32Slot(fp_, alloc.stackOffset()));
2017 default:
2018 break;
2019 }
2020 MOZ_CRASH("invalid intptr allocation");
2021 }
2022
2023 JS::BigInt* SnapshotIterator::readBigInt(JSContext* cx) {
2024 RValueAllocation alloc = readAllocation();
2025 switch (alloc.mode()) {
2026 case RValueAllocation::INTPTR_CST:
2027 case RValueAllocation::INTPTR_REG:
2028 case RValueAllocation::INTPTR_STACK:
2029 case RValueAllocation::INTPTR_INT32_STACK:
2030 return JS::BigInt::createFromIntPtr(cx, allocationIntPtr(alloc));
2031 default:
2032 return allocationValue(alloc).toBigInt();
2033 }
2034 }
2035
2036 void SnapshotIterator::writeAllocationValuePayload(
2037 const RValueAllocation& alloc, const Value& v) {
2038 MOZ_ASSERT(v.isGCThing());
2039
2040 switch (alloc.mode()) {
2041 case RValueAllocation::CONSTANT:
2042 ionScript_->getConstant(alloc.index()) = v;
2043 break;
2044
2045 case RValueAllocation::CST_UNDEFINED:
2046 case RValueAllocation::CST_NULL:
2047 case RValueAllocation::DOUBLE_REG:
2048 case RValueAllocation::FLOAT32_REG:
2049 case RValueAllocation::FLOAT32_STACK:
2050 case RValueAllocation::INTPTR_CST:
2051 case RValueAllocation::INTPTR_REG:
2052 case RValueAllocation::INTPTR_STACK:
2053 case RValueAllocation::INTPTR_INT32_STACK:
2054 case RValueAllocation::INT64_CST:
2055 #if defined(JS_NUNBOX32)
2056 case RValueAllocation::INT64_REG_REG:
2057 case RValueAllocation::INT64_REG_STACK:
2058 case RValueAllocation::INT64_STACK_REG:
2059 case RValueAllocation::INT64_STACK_STACK:
2060 #elif defined(JS_PUNBOX64)
2061 case RValueAllocation::INT64_REG:
2062 case RValueAllocation::INT64_STACK:
2063 case RValueAllocation::INT64_INT32_STACK:
2064 #endif
2065 MOZ_CRASH("Not a GC thing: Unexpected write");
2066 break;
2067
2068 case RValueAllocation::TYPED_REG:
2069 machine_->write(alloc.reg2(), uintptr_t(v.toGCThing()));
2070 break;
2071
2072 case RValueAllocation::TYPED_STACK:
2073 switch (alloc.knownType()) {
2074 default:
2075 MOZ_CRASH("Not a GC thing: Unexpected write");
2076 break;
2077 case JSVAL_TYPE_STRING:
2078 case JSVAL_TYPE_SYMBOL:
2079 case JSVAL_TYPE_BIGINT:
2080 case JSVAL_TYPE_OBJECT:
2081 WriteFrameSlot(fp_, alloc.stackOffset2(), uintptr_t(v.toGCThing()));
2082 break;
2083 }
2084 break;
2085
2086 #if defined(JS_NUNBOX32)
2087 case RValueAllocation::UNTYPED_REG_REG:
2088 case RValueAllocation::UNTYPED_STACK_REG:
2089 machine_->write(alloc.reg2(), uintptr_t(v.toGCThing()));
2090 break;
2091
2092 case RValueAllocation::UNTYPED_REG_STACK:
2093 case RValueAllocation::UNTYPED_STACK_STACK:
2094 WriteFrameSlot(fp_, alloc.stackOffset2(), uintptr_t(v.toGCThing()));
2095 break;
2096 #elif defined(JS_PUNBOX64)
2097 case RValueAllocation::UNTYPED_REG:
2098 machine_->write(alloc.reg(), v.asRawBits());
2099 break;
2100
2101 case RValueAllocation::UNTYPED_STACK:
2102 WriteFrameSlot(fp_, alloc.stackOffset(), v.asRawBits());
2103 break;
2104 #endif
2105
2106 case RValueAllocation::RECOVER_INSTRUCTION:
2107 MOZ_CRASH("Recover instructions are handled by the JitActivation.");
2108 break;
2109
2110 case RValueAllocation::RI_WITH_DEFAULT_CST:
2111 // Assume that we are always going to be writing on the default value
2112 // while tracing.
2113 ionScript_->getConstant(alloc.index2()) = v;
2114 break;
2115
2116 default:
2117 MOZ_CRASH("huh?");
2118 }
2119 }
2120
2121 void SnapshotIterator::traceAllocation(JSTracer* trc) {
2122 RValueAllocation alloc = readAllocation();
2123 if (!allocationReadable(alloc, ReadMethod::AlwaysDefault)) {
2124 return;
2125 }
2126
2127 Value v = allocationValue(alloc, ReadMethod::AlwaysDefault);
2128 if (!v.isGCThing()) {
2129 return;
2130 }
2131
2132 Value copy = v;
2133 TraceRoot(trc, &v, "ion-typed-reg");
2134 if (v != copy) {
2135 MOZ_ASSERT(SameType(v, copy));
2136 writeAllocationValuePayload(alloc, v);
2137 }
2138 }
2139
2140 const RResumePoint* SnapshotIterator::resumePoint() const {
2141 return instruction()->toResumePoint();
2142 }
2143
2144 uint32_t SnapshotIterator::numAllocations() const {
2145 return instruction()->numOperands();
2146 }
2147
2148 uint32_t SnapshotIterator::pcOffset() const {
2149 return resumePoint()->pcOffset();
2150 }
2151
2152 ResumeMode SnapshotIterator::resumeMode() const {
2153 return resumePoint()->mode();
2154 }
2155
2156 void SnapshotIterator::skipInstruction() {
2157 MOZ_ASSERT(snapshot_.numAllocationsRead() == 0);
2158 size_t numOperands = instruction()->numOperands();
2159 for (size_t i = 0; i < numOperands; i++) {
2160 skip();
2161 }
2162 nextInstruction();
2163 }
2164
2165 bool SnapshotIterator::initInstructionResults(MaybeReadFallback& fallback) {
2166 MOZ_ASSERT(fallback.canRecoverResults());
2167 JSContext* cx = fallback.maybeCx;
2168
2169 // If there is only one resume point in the list of instructions, then there
2170 // is no instruction to recover, and thus no need to register any results.
2171 if (recover_.numInstructions() == 1) {
2172 return true;
2173 }
2174
2175 JitFrameLayout* fp = fallback.frame->jsFrame();
2176 RInstructionResults* results = fallback.activation->maybeIonFrameRecovery(fp);
2177 if (!results) {
2178 AutoRealm ar(cx, fallback.frame->script());
2179
2180 // We are going to run recover instructions. To avoid problems where recover
2181 // instructions are not idempotent (for example, if we allocate an object,
2182 // object identity may be observable), we should not execute code in the
2183 // Ion stack frame afterwards. To avoid doing so, we invalidate the script.
2184 // This is not necessary for bailouts or other cases where we are leaving
2185 // the frame anyway. We only need it for niche cases like debugger
2186 // introspection or Function.arguments.
2187 if (fallback.consequence == MaybeReadFallback::Fallback_Invalidate) {
2188 ionScript_->invalidate(cx, fallback.frame->script(),
2189 /* resetUses = */ false,
2190 "Observe recovered instruction.");
2191 }
2192
2193 // Register the list of result on the activation. We need to do that
2194 // before we initialize the list such as if any recover instruction
2195 // cause a GC, we can ensure that the results are properly traced by the
2196 // activation.
2197 RInstructionResults tmp(fallback.frame->jsFrame());
2198 if (!fallback.activation->registerIonFrameRecovery(std::move(tmp))) {
2199 return false;
2200 }
2201
2202 results = fallback.activation->maybeIonFrameRecovery(fp);
2203
2204 // Start a new snapshot at the beginning of the JSJitFrameIter. This
2205 // SnapshotIterator is used for evaluating the content of all recover
2206 // instructions. The result is then saved on the JitActivation.
2207 MachineState machine = fallback.frame->machineState();
2208 SnapshotIterator s(*fallback.frame, &machine);
2209 if (!s.computeInstructionResults(cx, results)) {
2210 // If the evaluation failed because of OOMs, then we discard the
2211 // current set of result that we collected so far.
2212 fallback.activation->removeIonFrameRecovery(fp);
2213 return false;
2214 }
2215 }
2216
2217 MOZ_ASSERT(results->isInitialized());
2218 MOZ_RELEASE_ASSERT(results->length() == recover_.numInstructions() - 1);
2219 instructionResults_ = results;
2220 return true;
2221 }
2222
2223 bool SnapshotIterator::computeInstructionResults(
2224 JSContext* cx, RInstructionResults* results) const {
2225 MOZ_ASSERT(!results->isInitialized());
2226 MOZ_ASSERT(recover_.numInstructionsRead() == 1);
2227
2228 // The last instruction will always be a resume point.
2229 size_t numResults = recover_.numInstructions() - 1;
2230 if (!results->isInitialized()) {
2231 if (!results->init(cx, numResults)) {
2232 return false;
2233 }
2234
2235 // No need to iterate over the only resume point.
2236 if (!numResults) {
2237 MOZ_ASSERT(results->isInitialized());
2238 return true;
2239 }
2240
2241 // Avoid invoking the object metadata callback, which could try to walk the
2242 // stack while bailing out.
2243 gc::AutoSuppressGC suppressGC(cx);
2244 js::AutoSuppressAllocationMetadataBuilder suppressMetadata(cx);
2245
2246 // Fill with the results of recover instructions.
2247 SnapshotIterator s(*this);
2248 s.instructionResults_ = results;
2249 while (s.moreInstructions()) {
2250 // Skip resume point and only interpret recover instructions.
2251 if (s.instruction()->isResumePoint()) {
2252 s.skipInstruction();
2253 continue;
2254 }
2255
2256 if (!s.instruction()->recover(cx, s)) {
2257 return false;
2258 }
2259 s.nextInstruction();
2260 }
2261 }
2262
2263 MOZ_ASSERT(results->isInitialized());
2264 return true;
2265 }
2266
2267 void SnapshotIterator::storeInstructionResult(const Value& v) {
2268 uint32_t currIns = recover_.numInstructionsRead() - 1;
2269 MOZ_ASSERT((*instructionResults_)[currIns].isMagic(JS_ION_BAILOUT));
2270 (*instructionResults_)[currIns] = v;
2271 }
2272
2273 Value SnapshotIterator::fromInstructionResult(uint32_t index) const {
2274 MOZ_ASSERT(!(*instructionResults_)[index].isMagic(JS_ION_BAILOUT));
2275 return (*instructionResults_)[index];
2276 }
2277
2278 void SnapshotIterator::settleOnFrame() {
2279 // Check that the current instruction can still be use.
2280 MOZ_ASSERT(snapshot_.numAllocationsRead() == 0);
2281 while (!instruction()->isResumePoint()) {
2282 skipInstruction();
2283 }
2284 }
2285
2286 void SnapshotIterator::nextFrame() {
2287 nextInstruction();
2288 settleOnFrame();
2289 }
2290
2291 Value SnapshotIterator::maybeReadAllocByIndex(size_t index) {
2292 while (index--) {
2293 MOZ_ASSERT(moreAllocations());
2294 skip();
2295 }
2296
2297 Value s;
2298 {
2299 // This MaybeReadFallback method cannot GC.
2300 JS::AutoSuppressGCAnalysis nogc;
2301 MaybeReadFallback fallback;
2302 s = maybeRead(fallback);
2303 }
2304
2305 while (moreAllocations()) {
2306 skip();
2307 }
2308
2309 return s;
2310 }
2311
2312 InlineFrameIterator::InlineFrameIterator(JSContext* cx,
2313 const JSJitFrameIter* iter)
2314 : calleeTemplate_(cx), script_(cx), pc_(nullptr), numActualArgs_(0) {
2315 resetOn(iter);
2316 }
2317
2318 InlineFrameIterator::InlineFrameIterator(JSContext* cx,
2319 const InlineFrameIterator* iter)
2320 : frame_(iter ? iter->frame_ : nullptr),
2321 framesRead_(0),
2322 frameCount_(iter ? iter->frameCount_ : UINT32_MAX),
2323 calleeTemplate_(cx),
2324 script_(cx),
2325 pc_(nullptr),
2326 numActualArgs_(0) {
2327 if (frame_) {
2328 machine_ = iter->machine_;
2329 start_ = SnapshotIterator(*frame_, &machine_);
2330
2331 // findNextFrame will iterate to the next frame and init. everything.
2332 // Therefore to settle on the same frame, we report one frame less readed.
2333 framesRead_ = iter->framesRead_ - 1;
2334 findNextFrame();
2335 }
2336 }
2337
2338 void InlineFrameIterator::resetOn(const JSJitFrameIter* iter) {
2339 frame_ = iter;
2340 framesRead_ = 0;
2341 frameCount_ = UINT32_MAX;
2342
2343 if (iter) {
2344 machine_ = iter->machineState();
2345 start_ = SnapshotIterator(*iter, &machine_);
2346 findNextFrame();
2347 }
2348 }
2349
2350 void InlineFrameIterator::findNextFrame() {
2351 MOZ_ASSERT(more());
2352
2353 si_ = start_;
2354
2355 // Read the initial frame out of the C stack.
2356 calleeTemplate_ = frame_->maybeCallee();
2357 calleeRVA_ = RValueAllocation();
2358 script_ = frame_->script();
2359 MOZ_ASSERT(script_->hasBaselineScript());
2360
2361 // Settle on the outermost frame without evaluating any instructions before
2362 // looking for a pc.
2363 si_.settleOnFrame();
2364
2365 pc_ = script_->offsetToPC(si_.pcOffset());
2366 numActualArgs_ = 0xbadbad;
2367
2368 // This unfortunately is O(n*m), because we must skip over outer frames
2369 // before reading inner ones.
2370
2371 // The first time (frameCount_ == UINT32_MAX) we do not know the number of
2372 // frames that we are going to inspect. So we are iterating until there is
2373 // no more frames, to settle on the inner most frame and to count the number
2374 // of frames.
2375 size_t remaining = (frameCount_ != UINT32_MAX) ? frameNo() - 1 : SIZE_MAX;
2376
2377 size_t i = 1;
2378 for (; i <= remaining && si_.moreFrames(); i++) {
2379 ResumeMode mode = si_.resumeMode();
2380 MOZ_ASSERT(IsIonInlinableOp(JSOp(*pc_)));
2381
2382 // Recover the number of actual arguments from the script.
2383 if (IsInvokeOp(JSOp(*pc_))) {
2384 MOZ_ASSERT(mode == ResumeMode::InlinedStandardCall ||
2385 mode == ResumeMode::InlinedFunCall);
2386 numActualArgs_ = GET_ARGC(pc_);
2387 if (mode == ResumeMode::InlinedFunCall && numActualArgs_ > 0) {
2388 numActualArgs_--;
2389 }
2390 } else if (IsGetPropPC(pc_) || IsGetElemPC(pc_)) {
2391 MOZ_ASSERT(mode == ResumeMode::InlinedAccessor);
2392 numActualArgs_ = 0;
2393 } else {
2394 MOZ_RELEASE_ASSERT(IsSetPropPC(pc_));
2395 MOZ_ASSERT(mode == ResumeMode::InlinedAccessor);
2396 numActualArgs_ = 1;
2397 }
2398
2399 // Skip over non-argument slots, as well as |this|.
2400 bool skipNewTarget = IsConstructPC(pc_);
2401 unsigned skipCount =
2402 (si_.numAllocations() - 1) - numActualArgs_ - 1 - skipNewTarget;
2403 for (unsigned j = 0; j < skipCount; j++) {
2404 si_.skip();
2405 }
2406
2407 // This value should correspond to the function which is being inlined.
2408 // The value must be readable to iterate over the inline frame. Most of
2409 // the time, these functions are stored as JSFunction constants,
2410 // register which are holding the JSFunction pointer, or recover
2411 // instruction with Default value.
2412 Value funval = si_.readWithDefault(&calleeRVA_);
2413
2414 // Skip extra value allocations.
2415 while (si_.moreAllocations()) {
2416 si_.skip();
2417 }
2418
2419 si_.nextFrame();
2420
2421 calleeTemplate_ = &funval.toObject().as<JSFunction>();
2422 script_ = calleeTemplate_->nonLazyScript();
2423 MOZ_ASSERT(script_->hasBaselineScript());
2424
2425 pc_ = script_->offsetToPC(si_.pcOffset());
2426 }
2427
2428 // The first time we do not know the number of frames, we only settle on the
2429 // last frame, and update the number of frames based on the number of
2430 // iteration that we have done.
2431 if (frameCount_ == UINT32_MAX) {
2432 MOZ_ASSERT(!si_.moreFrames());
2433 frameCount_ = i;
2434 }
2435
2436 framesRead_++;
2437 }
2438
2439 JSFunction* InlineFrameIterator::callee(MaybeReadFallback& fallback) const {
2440 MOZ_ASSERT(isFunctionFrame());
2441 if (calleeRVA_.mode() == RValueAllocation::INVALID ||
2442 !fallback.canRecoverResults()) {
2443 return calleeTemplate_;
2444 }
2445
2446 SnapshotIterator s(si_);
2447 // :TODO: Handle allocation failures from recover instruction.
2448 Value funval = s.maybeRead(calleeRVA_, fallback);
2449 return &funval.toObject().as<JSFunction>();
2450 }
2451
2452 JSObject* InlineFrameIterator::computeEnvironmentChain(
2453 const Value& envChainValue, MaybeReadFallback& fallback,
2454 bool* hasInitialEnv) const {
2455 if (envChainValue.isObject()) {
2456 if (hasInitialEnv) {
2457 if (fallback.canRecoverResults()) {
2458 RootedObject obj(fallback.maybeCx, &envChainValue.toObject());
2459 *hasInitialEnv = isFunctionFrame() &&
2460 callee(fallback)->needsFunctionEnvironmentObjects();
2461 return obj;
2462 }
2463 JS::AutoSuppressGCAnalysis
2464 nogc; // If we cannot recover then we cannot GC.
2465 *hasInitialEnv = isFunctionFrame() &&
2466 callee(fallback)->needsFunctionEnvironmentObjects();
2467 }
2468
2469 return &envChainValue.toObject();
2470 }
2471
2472 // Note we can hit this case even for functions with a CallObject, in case
2473 // we are walking the frame during the function prologue, before the env
2474 // chain has been initialized.
2475 if (isFunctionFrame()) {
2476 return callee(fallback)->environment();
2477 }
2478
2479 if (isModuleFrame()) {
2480 return script()->module()->environment();
2481 }
2482
2483 // Ion does not handle non-function scripts that have anything other than
2484 // the global on their env chain.
2485 MOZ_ASSERT(!script()->isForEval());
2486 MOZ_ASSERT(!script()->hasNonSyntacticScope());
2487 return &script()->global().lexicalEnvironment();
2488 }
2489
2490 bool InlineFrameIterator::isFunctionFrame() const { return !!calleeTemplate_; }
2491
2492 bool InlineFrameIterator::isModuleFrame() const { return script()->isModule(); }
2493
2494 uintptr_t* MachineState::SafepointState::addressOfRegister(Register reg) const {
2495 size_t offset = regs.offsetOfPushedRegister(reg);
2496
2497 MOZ_ASSERT((offset % sizeof(uintptr_t)) == 0);
2498 uint32_t index = offset / sizeof(uintptr_t);
2499
2500 #ifdef DEBUG
2501 // Assert correctness with a slower algorithm in debug builds.
2502 uint32_t expectedIndex = 0;
2503 bool found = false;
2504 for (GeneralRegisterBackwardIterator iter(regs); iter.more(); ++iter) {
2505 expectedIndex++;
2506 if (*iter == reg) {
2507 found = true;
2508 break;
2509 }
2510 }
2511 MOZ_ASSERT(found);
2512 MOZ_ASSERT(expectedIndex == index);
2513 #endif
2514
2515 return spillBase - index;
2516 }
2517
2518 char* MachineState::SafepointState::addressOfRegister(FloatRegister reg) const {
2519 // Note: this could be optimized similar to the GPR case above by implementing
2520 // offsetOfPushedRegister for FloatRegisterSet. Float register sets are
2521 // complicated though and this case is very uncommon: it's only reachable for
2522 // exception bailouts with live float registers.
2523 MOZ_ASSERT(!reg.isSimd128());
2524 char* ptr = floatSpillBase;
2525 for (FloatRegisterBackwardIterator iter(floatRegs); iter.more(); ++iter) {
2526 ptr -= (*iter).size();
2527 for (uint32_t a = 0; a < (*iter).numAlignedAliased(); a++) {
2528 // Only say that registers that actually start here start here.
2529 // e.g. d0 should not start at s1, only at s0.
2530 FloatRegister ftmp = (*iter).alignedAliased(a);
2531 if (ftmp == reg) {
2532 return ptr;
2533 }
2534 }
2535 }
2536 MOZ_CRASH("Invalid register");
2537 }
2538
2539 uintptr_t MachineState::read(Register reg) const {
2540 if (state_.is<BailoutState>()) {
2541 return state_.as<BailoutState>().regs[reg.code()].r;
2542 }
2543 if (state_.is<SafepointState>()) {
2544 uintptr_t* addr = state_.as<SafepointState>().addressOfRegister(reg);
2545 return *addr;
2546 }
2547 MOZ_CRASH("Invalid state");
2548 }
2549
2550 template <typename T>
2551 T MachineState::read(FloatRegister reg) const {
2552 #if !defined(JS_CODEGEN_RISCV64)
2553 MOZ_ASSERT(reg.size() == sizeof(T));
2554 #else
2555 // RISCV64 always store FloatRegister as 64bit.
2556 MOZ_ASSERT(reg.size() == sizeof(double));
2557 #endif
2558
2559 #if !defined(JS_CODEGEN_NONE) && !defined(JS_CODEGEN_WASM32)
2560 if (state_.is<BailoutState>()) {
2561 uint32_t offset = reg.getRegisterDumpOffsetInBytes();
2562 MOZ_ASSERT((offset % sizeof(T)) == 0);
2563 MOZ_ASSERT((offset + sizeof(T)) <= sizeof(RegisterDump::FPUArray));
2564
2565 const BailoutState& state = state_.as<BailoutState>();
2566 char* addr = reinterpret_cast<char*>(state.floatRegs.begin()) + offset;
2567 return *reinterpret_cast<T*>(addr);
2568 }
2569 if (state_.is<SafepointState>()) {
2570 char* addr = state_.as<SafepointState>().addressOfRegister(reg);
2571 return *reinterpret_cast<T*>(addr);
2572 }
2573 #endif
2574 MOZ_CRASH("Invalid state");
2575 }
2576
2577 void MachineState::write(Register reg, uintptr_t value) const {
2578 if (state_.is<SafepointState>()) {
2579 uintptr_t* addr = state_.as<SafepointState>().addressOfRegister(reg);
2580 *addr = value;
2581 return;
2582 }
2583 MOZ_CRASH("Invalid state");
2584 }
2585
2586 bool InlineFrameIterator::isConstructing() const {
2587 // Skip the current frame and look at the caller's.
2588 if (more()) {
2589 InlineFrameIterator parent(TlsContext.get(), this);
2590 ++parent;
2591
2592 // In the case of a JS frame, look up the pc from the snapshot.
2593 JSOp parentOp = JSOp(*parent.pc());
2594
2595 // Inlined Getters and Setters are never constructing.
2596 if (IsIonInlinableGetterOrSetterOp(parentOp)) {
2597 return false;
2598 }
2599
2600 MOZ_ASSERT(IsInvokeOp(parentOp) && !IsSpreadOp(parentOp));
2601
2602 return IsConstructOp(parentOp);
2603 }
2604
2605 return frame_->isConstructing();
2606 }
2607
2608 void SnapshotIterator::warnUnreadableAllocation() {
2609 fprintf(stderr,
2610 "Warning! Tried to access unreadable value allocation (possible "
2611 "f.arguments).\n");
2612 }
2613
2614 struct DumpOverflownOp {
2615 const unsigned numFormals_;
2616 unsigned i_ = 0;
2617
2618 explicit DumpOverflownOp(unsigned numFormals) : numFormals_(numFormals) {}
2619
2620 void operator()(const Value& v) {
2621 if (i_ >= numFormals_) {
2622 fprintf(stderr, " actual (arg %u): ", i_);
2623 #if defined(DEBUG) || defined(JS_JITSPEW)
2624 DumpValue(v);
2625 #else
2626 fprintf(stderr, "?\n");
2627 #endif
2628 }
2629 i_++;
2630 }
2631 };
2632
2633 void InlineFrameIterator::dump() const {
2634 MaybeReadFallback fallback;
2635
2636 if (more()) {
2637 fprintf(stderr, " JS frame (inlined)\n");
2638 } else {
2639 fprintf(stderr, " JS frame\n");
2640 }
2641
2642 bool isFunction = false;
2643 if (isFunctionFrame()) {
2644 isFunction = true;
2645 fprintf(stderr, " callee fun: ");
2646 #if defined(DEBUG) || defined(JS_JITSPEW)
2647 DumpObject(callee(fallback));
2648 #else
2649 fprintf(stderr, "?\n");
2650 #endif
2651 } else {
2652 fprintf(stderr, " global frame, no callee\n");
2653 }
2654
2655 fprintf(stderr, " file %s line %u\n", script()->filename(),
2656 script()->lineno());
2657
2658 fprintf(stderr, " script = %p, pc = %p\n", (void*)script(), pc());
2659 fprintf(stderr, " current op: %s\n", CodeName(JSOp(*pc())));
2660
2661 if (!more()) {
2662 numActualArgs();
2663 }
2664
2665 SnapshotIterator si = snapshotIterator();
2666 fprintf(stderr, " slots: %u\n", si.numAllocations() - 1);
2667 for (unsigned i = 0; i < si.numAllocations() - 1; i++) {
2668 if (isFunction) {
2669 if (i == 0) {
2670 fprintf(stderr, " env chain: ");
2671 } else if (i == 1) {
2672 fprintf(stderr, " this: ");
2673 } else if (i - 2 < calleeTemplate()->nargs()) {
2674 fprintf(stderr, " formal (arg %u): ", i - 2);
2675 } else {
2676 if (i - 2 == calleeTemplate()->nargs() &&
2677 numActualArgs() > calleeTemplate()->nargs()) {
2678 DumpOverflownOp d(calleeTemplate()->nargs());
2679 unaliasedForEachActual(TlsContext.get(), d, fallback);
2680 }
2681
2682 fprintf(stderr, " slot %d: ", int(i - 2 - calleeTemplate()->nargs()));
2683 }
2684 } else
2685 fprintf(stderr, " slot %u: ", i);
2686 #if defined(DEBUG) || defined(JS_JITSPEW)
2687 DumpValue(si.maybeRead(fallback));
2688 #else
2689 fprintf(stderr, "?\n");
2690 #endif
2691 }
2692
2693 fputc('\n', stderr);
2694 }
2695
2696 JitFrameLayout* InvalidationBailoutStack::fp() const {
2697 return (JitFrameLayout*)(sp() + ionScript_->frameSize());
2698 }
2699
2700 void InvalidationBailoutStack::checkInvariants() const {
2701 #ifdef DEBUG
2702 JitFrameLayout* frame = fp();
2703 CalleeToken token = frame->calleeToken();
2704 MOZ_ASSERT(token);
2705
2706 uint8_t* rawBase = ionScript()->method()->raw();
2707 uint8_t* rawLimit = rawBase + ionScript()->method()->instructionsSize();
2708 uint8_t* osiPoint = osiPointReturnAddress();
2709 MOZ_ASSERT(rawBase <= osiPoint && osiPoint <= rawLimit);
2710 #endif
2711 }
2712
2713 void AssertJitStackInvariants(JSContext* cx) {
2714 for (JitActivationIterator activations(cx); !activations.done();
2715 ++activations) {
2716 JitFrameIter iter(activations->asJit());
2717 if (iter.isJSJit()) {
2718 JSJitFrameIter& frames = iter.asJSJit();
2719 size_t prevFrameSize = 0;
2720 size_t frameSize = 0;
2721 bool isScriptedCallee = false;
2722 for (; !frames.done(); ++frames) {
2723 size_t calleeFp = reinterpret_cast<size_t>(frames.fp());
2724 size_t callerFp = reinterpret_cast<size_t>(frames.prevFp());
2725 MOZ_ASSERT(callerFp >= calleeFp);
2726 prevFrameSize = frameSize;
2727 frameSize = callerFp - calleeFp;
2728
2729 if (frames.isScripted() &&
2730 (frames.prevType() == FrameType::Rectifier ||
2731 frames.prevType() == FrameType::BaselineInterpreterEntry)) {
2732 MOZ_RELEASE_ASSERT(
2733 frameSize % JitStackAlignment == 0,
2734 "The rectifier and bli entry frame should keep the alignment");
2735
2736 size_t expectedFrameSize =
2737 sizeof(Value) *
2738 (frames.callee()->nargs() + 1 /* |this| argument */ +
2739 frames.isConstructing() /* new.target */) +
2740 sizeof(JitFrameLayout);
2741 MOZ_RELEASE_ASSERT(frameSize >= expectedFrameSize,
2742 "The frame is large enough to hold all arguments");
2743 MOZ_RELEASE_ASSERT(expectedFrameSize + JitStackAlignment > frameSize,
2744 "The frame size is optimal");
2745 }
2746
2747 if (frames.isExitFrame()) {
2748 // For the moment, we do not keep the JitStackAlignment
2749 // alignment for exit frames.
2750 frameSize -= ExitFrameLayout::Size();
2751 }
2752
2753 if (frames.isIonJS()) {
2754 // Ideally, we should not have such requirement, but keep the
2755 // alignment-delta as part of the Safepoint such that we can pad
2756 // accordingly when making out-of-line calls. In the mean time,
2757 // let us have check-points where we can garantee that
2758 // everything can properly be aligned before adding complexity.
2759 MOZ_RELEASE_ASSERT(
2760 frames.ionScript()->frameSize() % JitStackAlignment == 0,
2761 "Ensure that if the Ion frame is aligned, then the spill base is "
2762 "also aligned");
2763
2764 if (isScriptedCallee) {
2765 MOZ_RELEASE_ASSERT(prevFrameSize % JitStackAlignment == 0,
2766 "The ion frame should keep the alignment");
2767 }
2768 }
2769
2770 // The stack is dynamically aligned by baseline stubs before calling
2771 // any jitted code.
2772 if (frames.prevType() == FrameType::BaselineStub && isScriptedCallee) {
2773 MOZ_RELEASE_ASSERT(calleeFp % JitStackAlignment == 0,
2774 "The baseline stub restores the stack alignment");
2775 }
2776
2777 isScriptedCallee =
2778 frames.isScripted() || frames.type() == FrameType::Rectifier;
2779 }
2780
2781 MOZ_RELEASE_ASSERT(
2782 JSJitFrameIter::isEntry(frames.type()),
2783 "The first frame of a Jit activation should be an entry frame");
2784 MOZ_RELEASE_ASSERT(
2785 reinterpret_cast<size_t>(frames.fp()) % JitStackAlignment == 0,
2786 "The entry frame should be properly aligned");
2787 } else {
2788 MOZ_ASSERT(iter.isWasm());
2789 wasm::WasmFrameIter& frames = iter.asWasm();
2790 while (!frames.done()) {
2791 ++frames;
2792 }
2793 }
2794 }
2795 }
2796
2797 } // namespace jit
2798 } // namespace js