Debian Codegraph @

js/src/wasm/WasmFrameIter.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 *
4 * Copyright 2014 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "wasm/WasmFrameIter.h"
20
21 #include "jit/JitFrames.h"
22 #include "jit/shared/IonAssemblerBuffer.h" // jit::BufferOffset
23 #include "js/ColumnNumber.h" // JS::WasmFunctionIndex, LimitedColumnNumberOneOrigin, JS::TaggedColumnNumberOneOrigin, JS::TaggedColumnNumberOneOrigin
24 #include "vm/JitActivation.h" // js::jit::JitActivation
25 #include "vm/JSAtomState.h"
26 #include "vm/JSContext.h"
27 #include "wasm/WasmBuiltinModuleGenerated.h"
28 #include "wasm/WasmDebugFrame.h"
29 #include "wasm/WasmInstance.h"
30 #include "wasm/WasmInstanceData.h"
31 #include "wasm/WasmPI.h"
32 #include "wasm/WasmStubs.h"
33
34 #include "jit/MacroAssembler-inl.h"
35 #include "wasm/WasmInstance-inl.h"
36
37 using namespace js;
38 using namespace js::jit;
39 using namespace js::wasm;
40
41 using mozilla::DebugOnly;
42 using mozilla::Maybe;
43
44 static Instance* ExtractCallerInstanceFromFrameWithInstances(Frame* fp) {
45 return *reinterpret_cast<Instance**>(
46 reinterpret_cast<uint8_t*>(fp) +
47 FrameWithInstances::callerInstanceOffset());
48 }
49
50 static const Instance* ExtractCalleeInstanceFromFrameWithInstances(
51 const Frame* fp) {
52 return *reinterpret_cast<Instance* const*>(
53 reinterpret_cast<const uint8_t*>(fp) +
54 FrameWithInstances::calleeInstanceOffset());
55 }
56
57 static uint32_t FuncIndexForLineOrBytecode(const Code& code,
58 uint32_t lineOrBytecode,
59 const CodeRange& codeRange) {
60 // If this is asm.js, then this is a line number and we also will not be
61 // doing any inlining. Report the physical func index.
62 //
63 // Or else if there is no bytecode offset in the call site, then this must be
64 // something internal we've generated and no inlining should be involved.
65 if (code.codeMeta().isAsmJS() ||
66 lineOrBytecode == CallSite::NO_LINE_OR_BYTECODE) {
67 // Fall back to the physical function index of the code range.
68 return codeRange.funcIndex();
69 }
70 return code.codeTailMeta().findFuncIndex(lineOrBytecode);
71 }
72
73 /*****************************************************************************/
74 // WasmFrameIter implementation
75
76 WasmFrameIter::WasmFrameIter(JitActivation* activation, wasm::Frame* fp)
77 : activation_(activation), fp_(fp ? fp : activation->wasmExitFP()) {
78 MOZ_ASSERT(fp_);
79 instance_ = GetNearestEffectiveInstance(fp_);
80
81 // When the stack is captured during a trap (viz., to create the .stack
82 // for an Error object), use the pc/bytecode information captured by the
83 // signal handler in the runtime. Take care not to use this trap unwind
84 // state for wasm frames in the middle of a JitActivation, i.e., wasm frames
85 // that called into JIT frames before the trap.
86
87 if (activation->isWasmTrapping() && fp_ == activation->wasmExitFP()) {
88 const TrapData& trapData = activation->wasmTrapData();
89 void* unwoundPC = trapData.unwoundPC;
90
91 code_ = &instance_->code();
92 MOZ_ASSERT(code_ == LookupCode(unwoundPC));
93
94 const CodeRange* codeRange = code_->lookupFuncRange(unwoundPC);
95 lineOrBytecode_ = trapData.trapSite.bytecodeOffset.offset();
96 funcIndex_ =
97 FuncIndexForLineOrBytecode(*code_, lineOrBytecode_, *codeRange);
98 inlinedCallerOffsets_ = trapData.trapSite.inlinedCallerOffsetsSpan();
99 failedUnwindSignatureMismatch_ = trapData.failedUnwindSignatureMismatch;
100
101 // The debugEnabled() relies on valid value of resumePCinCurrentFrame_
102 // to identify DebugFrame. Normally this field is updated at popFrame().
103 // The only case when this can happend is during IndirectCallBadSig
104 // trapping and stack unwinding. The top frame will never be at ReturnStub
105 // callsite, except during IndirectCallBadSig unwinding.
106 CallSite site;
107 if (code_->lookupCallSite(unwoundPC, &site) &&
108 site.kind() == CallSiteKind::ReturnStub) {
109 MOZ_ASSERT(trapData.trap == Trap::IndirectCallBadSig);
110 resumePCinCurrentFrame_ = (uint8_t*)unwoundPC;
111 } else {
112 resumePCinCurrentFrame_ = (uint8_t*)trapData.resumePC;
113 }
114
115 MOZ_ASSERT(!done());
116 return;
117 }
118
119 // Otherwise, execution exits wasm code via an exit stub which sets exitFP
120 // to the exit stub's frame. Thus, in this case, we want to start iteration
121 // at the caller of the exit frame, whose Code, CodeRange and CallSite are
122 // indicated by the returnAddress of the exit stub's frame. If the caller
123 // was Ion, we can just skip the wasm frames.
124
125 popFrame();
126 MOZ_ASSERT(!done() || unwoundCallerFP_);
127 }
128
129 WasmFrameIter::WasmFrameIter(FrameWithInstances* fp, void* returnAddress)
130 : lineOrBytecode_(0),
131 fp_(fp),
132 instance_(fp->calleeInstance()),
133 resumePCinCurrentFrame_((uint8_t*)returnAddress) {
134 // Specialized implementation to avoid popFrame() interation.
135 // It is expected that the iterator starts at a callsite that is in
136 // the function body and has instance reference.
137 const CodeRange* codeRange;
138 code_ = LookupCode(returnAddress, &codeRange);
139 MOZ_ASSERT(code_ && codeRange->kind() == CodeRange::Function);
140
141 CallSite site;
142 MOZ_ALWAYS_TRUE(code_->lookupCallSite(returnAddress, &site));
143 MOZ_ASSERT(site.mightBeCrossInstance());
144
145 #ifdef ENABLE_WASM_JSPI
146 currentFrameStackSwitched_ = site.isStackSwitch();
147 #endif
148
149 MOZ_ASSERT(code_ == &instance_->code());
150 lineOrBytecode_ = site.lineOrBytecode();
151 funcIndex_ =
152 FuncIndexForLineOrBytecode(*code_, site.lineOrBytecode(), *codeRange);
153 inlinedCallerOffsets_ = site.inlinedCallerOffsetsSpan();
154
155 MOZ_ASSERT(!done());
156 }
157
158 bool WasmFrameIter::done() const {
159 MOZ_ASSERT(!!fp_ == !!code_);
160 return !fp_;
161 }
162
163 void WasmFrameIter::operator++() {
164 MOZ_ASSERT(!done());
165
166 // When the iterator is set to unwind, each time the iterator pops a frame,
167 // the JitActivation is updated so that the just-popped frame is no longer
168 // visible. This is necessary since Debugger::onLeaveFrame is called before
169 // popping each frame and, once onLeaveFrame is called for a given frame,
170 // that frame must not be visible to subsequent stack iteration (or it
171 // could be added as a "new" frame just as it becomes garbage). When the
172 // frame is trapping, then exitFP is included in the callstack (otherwise,
173 // it is skipped, as explained above). So to unwind the innermost frame, we
174 // just clear the trapping state.
175
176 if (isLeavingFrames_) {
177 if (activation_->isWasmTrapping()) {
178 activation_->finishWasmTrap();
179 }
180 activation_->setWasmExitFP(fp_);
181 }
182
183 popFrame();
184 }
185
186 static inline void AssertJitExitFrame(const void* fp,
187 jit::ExitFrameType expected) {
188 // Called via a JIT to wasm call: in this case, FP is pointing in the middle
189 // of the exit frame, right before the exit footer; ensure the exit frame type
190 // is the expected one.
191 #ifdef DEBUG
192 auto* jitCaller = (ExitFrameLayout*)fp;
193 MOZ_ASSERT(jitCaller->footer()->type() == expected);
194 #endif
195 }
196
197 static inline void AssertDirectJitCall(const void* fp) {
198 AssertJitExitFrame(fp, jit::ExitFrameType::DirectWasmJitCall);
199 }
200
201 void WasmFrameIter::popFrame() {
202 // If we're visiting inlined frames, see if this frame was inlined.
203 if (enableInlinedFrames_ && inlinedCallerOffsets_.size() > 0) {
204 // We do not support inlining and debugging
205 MOZ_ASSERT(!code_->debugEnabled());
206
207 // The inlined callee offsets are ordered so that our immediate caller is
208 // the last offset.
209 //
210 // Set our current offset and func index to the last entry, then shift the
211 // span over by one.
212 const BytecodeOffset* first = inlinedCallerOffsets_.data();
213 const BytecodeOffset* last =
214 inlinedCallerOffsets_.data() + inlinedCallerOffsets_.size() - 1;
215 lineOrBytecode_ = last->offset();
216 inlinedCallerOffsets_ = BytecodeOffsetSpan(first, last);
217 MOZ_ASSERT(lineOrBytecode_ != CallSite::NO_LINE_OR_BYTECODE);
218 funcIndex_ = code_->codeTailMeta().findFuncIndex(lineOrBytecode_);
219 // An inlined frame will never do a stack switch, nor fail a signature
220 // mismatch.
221 currentFrameStackSwitched_ = false;
222 failedUnwindSignatureMismatch_ = false;
223 // Invalidate the resumePC, it should not be accessed anyways
224 resumePCinCurrentFrame_ = nullptr;
225 // Preserve fp_ for unwinding to the next frame when we're done with inline
226 // frames.
227 return;
228 }
229
230 uint8_t* returnAddress = fp_->returnAddress();
231 const CodeRange* codeRange;
232 code_ = LookupCode(returnAddress, &codeRange);
233 #ifdef ENABLE_WASM_JSPI
234 currentFrameStackSwitched_ = false;
235 #endif
236
237 if (!code_) {
238 // This is a direct call from the jit into the wasm function's body. The
239 // call stack resembles this at this point:
240 //
241 // |---------------------|
242 // | JIT FRAME |
243 // | JIT FAKE EXIT FRAME | <-- fp_->callerFP_
244 // | WASM FRAME | <-- fp_
245 // |---------------------|
246 //
247 // fp_->callerFP_ points to the fake exit frame set up by the jit caller,
248 // and the return-address-to-fp is in JIT code, thus doesn't belong to any
249 // wasm instance's code (in particular, there's no associated CodeRange).
250 // Mark the frame as such.
251 AssertDirectJitCall(fp_->jitEntryCaller());
252
253 unwoundCallerFP_ = fp_->jitEntryCaller();
254 unwoundCallerFPIsJSJit_ = true;
255 unwoundAddressOfReturnAddress_ = fp_->addressOfReturnAddress();
256
257 if (isLeavingFrames_) {
258 activation_->setJSExitFP(unwoundCallerFP_);
259 }
260
261 fp_ = nullptr;
262 code_ = nullptr;
263 funcIndex_ = UINT32_MAX;
264 lineOrBytecode_ = UINT32_MAX;
265 inlinedCallerOffsets_ = BytecodeOffsetSpan();
266 resumePCinCurrentFrame_ = nullptr;
267
268 MOZ_ASSERT(done());
269 return;
270 }
271
272 MOZ_ASSERT(codeRange);
273
274 Frame* prevFP = fp_;
275 fp_ = fp_->wasmCaller();
276 resumePCinCurrentFrame_ = returnAddress;
277
278 if (codeRange->isInterpEntry()) {
279 // Interpreter entry has a simple frame, record FP from it.
280 unwoundCallerFP_ = reinterpret_cast<uint8_t*>(fp_);
281 MOZ_ASSERT(!unwoundCallerFPIsJSJit_);
282 unwoundAddressOfReturnAddress_ = prevFP->addressOfReturnAddress();
283
284 fp_ = nullptr;
285 code_ = nullptr;
286 funcIndex_ = UINT32_MAX;
287 lineOrBytecode_ = UINT32_MAX;
288 inlinedCallerOffsets_ = BytecodeOffsetSpan();
289
290 if (isLeavingFrames_) {
291 // We're exiting via the interpreter entry; we can safely reset
292 // exitFP.
293 activation_->setWasmExitFP(nullptr);
294 }
295
296 MOZ_ASSERT(done());
297 return;
298 }
299
300 if (codeRange->isJitEntry()) {
301 // This wasm function has been called through the generic JIT entry by
302 // a JIT caller, so the call stack resembles this:
303 //
304 // |---------------------|
305 // | JIT FRAME |
306 // | JSJIT TO WASM EXIT | <-- fp_
307 // | WASM JIT ENTRY | <-- prevFP (already unwound)
308 // | WASM FRAME | (already unwound)
309 // |---------------------|
310 //
311 // The next value of FP is a jit exit frame with type WasmGenericJitEntry.
312 // This lets us transition to a JSJit frame iterator.
313 unwoundCallerFP_ = reinterpret_cast<uint8_t*>(fp_);
314 unwoundCallerFPIsJSJit_ = true;
315 AssertJitExitFrame(unwoundCallerFP_,
316 jit::ExitFrameType::WasmGenericJitEntry);
317 unwoundAddressOfReturnAddress_ = prevFP->addressOfReturnAddress();
318
319 fp_ = nullptr;
320 code_ = nullptr;
321 funcIndex_ = UINT32_MAX;
322 lineOrBytecode_ = UINT32_MAX;
323 inlinedCallerOffsets_ = BytecodeOffsetSpan();
324
325 if (isLeavingFrames_) {
326 activation_->setJSExitFP(unwoundCallerFP());
327 }
328
329 MOZ_ASSERT(done());
330 return;
331 }
332
333 MOZ_ASSERT(codeRange->kind() == CodeRange::Function);
334
335 CallSite site;
336 MOZ_ALWAYS_TRUE(code_->lookupCallSite(returnAddress, &site));
337
338 if (site.mightBeCrossInstance()) {
339 instance_ = ExtractCallerInstanceFromFrameWithInstances(prevFP);
340 }
341
342 #ifdef ENABLE_WASM_JSPI
343 currentFrameStackSwitched_ = site.isStackSwitch();
344 #endif
345
346 MOZ_ASSERT(code_ == &instance_->code());
347
348 lineOrBytecode_ = site.lineOrBytecode();
349 funcIndex_ =
350 FuncIndexForLineOrBytecode(*code_, site.lineOrBytecode(), *codeRange);
351 inlinedCallerOffsets_ = site.inlinedCallerOffsetsSpan();
352 failedUnwindSignatureMismatch_ = false;
353
354 MOZ_ASSERT(!done());
355 }
356
357 bool WasmFrameIter::hasSourceInfo() const {
358 // Source information is not available unless you're visiting inline frames,
359 // or you're debugging and therefore no inlining is happening.
360 return enableInlinedFrames_ || code_->debugEnabled();
361 }
362
363 const char* WasmFrameIter::filename() const {
364 MOZ_ASSERT(!done());
365 MOZ_ASSERT(hasSourceInfo());
366 return code_->codeMeta().scriptedCaller().filename.get();
367 }
368
369 const char16_t* WasmFrameIter::displayURL() const {
370 MOZ_ASSERT(!done());
371 MOZ_ASSERT(hasSourceInfo());
372 return code_->codeMetaForAsmJS()
373 ? code_->codeMetaForAsmJS()->displayURL() // asm.js
374 : nullptr; // wasm
375 }
376
377 bool WasmFrameIter::mutedErrors() const {
378 MOZ_ASSERT(!done());
379 MOZ_ASSERT(hasSourceInfo());
380 return code_->codeMetaForAsmJS()
381 ? code_->codeMetaForAsmJS()->mutedErrors() // asm.js
382 : false; // wasm
383 }
384
385 JSAtom* WasmFrameIter::functionDisplayAtom() const {
386 MOZ_ASSERT(!done());
387 MOZ_ASSERT(hasSourceInfo());
388
389 JSContext* cx = activation_->cx();
390 JSAtom* atom = instance_->getFuncDisplayAtom(cx, funcIndex_);
391 if (!atom) {
392 cx->clearPendingException();
393 return cx->names().empty_;
394 }
395
396 return atom;
397 }
398
399 unsigned WasmFrameIter::lineOrBytecode() const {
400 MOZ_ASSERT(!done());
401 MOZ_ASSERT(hasSourceInfo());
402 return lineOrBytecode_;
403 }
404
405 uint32_t WasmFrameIter::funcIndex() const {
406 MOZ_ASSERT(!done());
407 MOZ_ASSERT(hasSourceInfo());
408 return funcIndex_;
409 }
410
411 unsigned WasmFrameIter::computeLine(
412 JS::TaggedColumnNumberOneOrigin* column) const {
413 MOZ_ASSERT(!done());
414 MOZ_ASSERT(hasSourceInfo());
415 if (instance_->isAsmJS()) {
416 if (column) {
417 *column =
418 JS::TaggedColumnNumberOneOrigin(JS::LimitedColumnNumberOneOrigin(
419 JS::WasmFunctionIndex::DefaultBinarySourceColumnNumberOneOrigin));
420 }
421 return lineOrBytecode_;
422 }
423
424 MOZ_ASSERT(!(funcIndex_ & JS::TaggedColumnNumberOneOrigin::WasmFunctionTag));
425 if (column) {
426 *column =
427 JS::TaggedColumnNumberOneOrigin(JS::WasmFunctionIndex(funcIndex_));
428 }
429 return lineOrBytecode_;
430 }
431
432 bool WasmFrameIter::debugEnabled() const {
433 MOZ_ASSERT(!done());
434
435 // Metadata::debugEnabled is only set if debugging is actually enabled (both
436 // requested, and available via baseline compilation), and Tier::Debug code
437 // will be available.
438 if (!code_->debugEnabled()) {
439 return false;
440 }
441
442 // Debug information is not available in prologue when the iterator is
443 // failing to unwind invalid signature trap.
444 if (failedUnwindSignatureMismatch_) {
445 return false;
446 }
447
448 // Only non-imported functions can have debug frames.
449 if (funcIndex_ < code_->funcImports().length()) {
450 return false;
451 }
452
453 // Debug frame is not present at the return stub.
454 CallSite site;
455 return !(code_->lookupCallSite((void*)resumePCinCurrentFrame_, &site) &&
456 site.kind() == CallSiteKind::ReturnStub);
457 }
458
459 DebugFrame* WasmFrameIter::debugFrame() const {
460 MOZ_ASSERT(!done());
461 return DebugFrame::from(fp_);
462 }
463
464 /*****************************************************************************/
465 // Prologue/epilogue code generation
466
467 // These constants reflect statically-determined offsets in the
468 // prologue/epilogue. The offsets are dynamically asserted during code
469 // generation.
470 #if defined(JS_CODEGEN_X64)
471 static const unsigned PushedRetAddr = 0;
472 static const unsigned PushedFP = 1;
473 static const unsigned SetFP = 4;
474 static const unsigned PoppedFP = 0;
475 static const unsigned PoppedFPJitEntry = 0;
476 #elif defined(JS_CODEGEN_X86)
477 static const unsigned PushedRetAddr = 0;
478 static const unsigned PushedFP = 1;
479 static const unsigned SetFP = 3;
480 static const unsigned PoppedFP = 0;
481 static const unsigned PoppedFPJitEntry = 0;
482 #elif defined(JS_CODEGEN_ARM)
483 static const unsigned BeforePushRetAddr = 0;
484 static const unsigned PushedRetAddr = 4;
485 static const unsigned PushedFP = 8;
486 static const unsigned SetFP = 12;
487 static const unsigned PoppedFP = 0;
488 static const unsigned PoppedFPJitEntry = 0;
489 #elif defined(JS_CODEGEN_ARM64)
490 // On ARM64 we do not use push or pop; the prologues and epilogues are
491 // structured differently due to restrictions on SP alignment. Even so,
492 // PushedRetAddr and PushedFP are used in some restricted contexts
493 // and must be superficially meaningful.
494 static const unsigned BeforePushRetAddr = 0;
495 static const unsigned PushedRetAddr = 8;
496 static const unsigned PushedFP = 12;
497 static const unsigned SetFP = 16;
498 static const unsigned PoppedFP = 8;
499 static const unsigned PoppedFPJitEntry = 8;
500 static_assert(BeforePushRetAddr == 0, "Required by StartUnwinding");
501 static_assert(PushedFP > PushedRetAddr, "Required by StartUnwinding");
502 #elif defined(JS_CODEGEN_MIPS64)
503 static const unsigned PushedRetAddr = 8;
504 static const unsigned PushedFP = 16;
505 static const unsigned SetFP = 20;
506 static const unsigned PoppedFP = 4;
507 static const unsigned PoppedFPJitEntry = 0;
508 #elif defined(JS_CODEGEN_LOONG64)
509 static const unsigned PushedRetAddr = 8;
510 static const unsigned PushedFP = 16;
511 static const unsigned SetFP = 20;
512 static const unsigned PoppedFP = 4;
513 static const unsigned PoppedFPJitEntry = 0;
514 #elif defined(JS_CODEGEN_RISCV64)
515 static const unsigned PushedRetAddr = 8;
516 static const unsigned PushedFP = 16;
517 static const unsigned SetFP = 20;
518 static const unsigned PoppedFP = 4;
519 static const unsigned PoppedFPJitEntry = 0;
520 #elif defined(JS_CODEGEN_NONE) || defined(JS_CODEGEN_WASM32)
521 // Synthetic values to satisfy asserts and avoid compiler warnings.
522 static const unsigned PushedRetAddr = 0;
523 static const unsigned PushedFP = 1;
524 static const unsigned SetFP = 2;
525 static const unsigned PoppedFP = 3;
526 static const unsigned PoppedFPJitEntry = 4;
527 #else
528 # error "Unknown architecture!"
529 #endif
530
531 static void LoadActivation(MacroAssembler& masm, const Register& dest) {
532 // WasmCall pushes a JitActivation.
533 masm.loadPtr(Address(InstanceReg, wasm::Instance::offsetOfCx()), dest);
534 masm.loadPtr(Address(dest, JSContext::offsetOfActivation()), dest);
535 }
536
537 void wasm::SetExitFP(MacroAssembler& masm, ExitReason reason,
538 Register scratch) {
539 MOZ_ASSERT(!reason.isNone());
540
541 LoadActivation(masm, scratch);
542
543 masm.store32(
544 Imm32(reason.encode()),
545 Address(scratch, JitActivation::offsetOfEncodedWasmExitReason()));
546
547 masm.orPtr(Imm32(ExitFPTag), FramePointer);
548 masm.storePtr(FramePointer,
549 Address(scratch, JitActivation::offsetOfPackedExitFP()));
550 masm.andPtr(Imm32(int32_t(~ExitFPTag)), FramePointer);
551 }
552
553 void wasm::ClearExitFP(MacroAssembler& masm, Register scratch) {
554 LoadActivation(masm, scratch);
555 masm.storePtr(ImmWord(0x0),
556 Address(scratch, JitActivation::offsetOfPackedExitFP()));
557 masm.store32(
558 Imm32(0x0),
559 Address(scratch, JitActivation::offsetOfEncodedWasmExitReason()));
560 }
561
562 static void GenerateCallablePrologue(MacroAssembler& masm, uint32_t* entry) {
563 AutoCreatedBy acb(masm, "GenerateCallablePrologue");
564 masm.setFramePushed(0);
565
566 // ProfilingFrameIterator needs to know the offsets of several key
567 // instructions from entry. To save space, we make these offsets static
568 // constants and assert that they match the actual codegen below. On ARM,
569 // this requires AutoForbidPoolsAndNops to prevent a constant pool from being
570 // randomly inserted between two instructions.
571
572 #if defined(JS_CODEGEN_MIPS64)
573 {
574 *entry = masm.currentOffset();
575
576 masm.ma_push(ra);
577 MOZ_ASSERT_IF(!masm.oom(), PushedRetAddr == masm.currentOffset() - *entry);
578 masm.ma_push(FramePointer);
579 MOZ_ASSERT_IF(!masm.oom(), PushedFP == masm.currentOffset() - *entry);
580 masm.moveStackPtrTo(FramePointer);
581 MOZ_ASSERT_IF(!masm.oom(), SetFP == masm.currentOffset() - *entry);
582 }
583 #elif defined(JS_CODEGEN_LOONG64)
584 {
585 *entry = masm.currentOffset();
586
587 masm.ma_push(ra);
588 MOZ_ASSERT_IF(!masm.oom(), PushedRetAddr == masm.currentOffset() - *entry);
589 masm.ma_push(FramePointer);
590 MOZ_ASSERT_IF(!masm.oom(), PushedFP == masm.currentOffset() - *entry);
591 masm.moveStackPtrTo(FramePointer);
592 MOZ_ASSERT_IF(!masm.oom(), SetFP == masm.currentOffset() - *entry);
593 }
594 #elif defined(JS_CODEGEN_RISCV64)
595 {
596 *entry = masm.currentOffset();
597 BlockTrampolinePoolScope block_trampoline_pool(&masm, 5);
598 masm.ma_push(ra);
599 MOZ_ASSERT_IF(!masm.oom(), PushedRetAddr == masm.currentOffset() - *entry);
600 masm.ma_push(FramePointer);
601 MOZ_ASSERT_IF(!masm.oom(), PushedFP == masm.currentOffset() - *entry);
602 masm.moveStackPtrTo(FramePointer);
603 MOZ_ASSERT_IF(!masm.oom(), SetFP == masm.currentOffset() - *entry);
604 }
605 #elif defined(JS_CODEGEN_ARM64)
606 {
607 // We do not use the PseudoStackPointer. However, we may be called in a
608 // context -- compilation using Ion -- in which the PseudoStackPointer is
609 // in use. Rather than risk confusion in the uses of `masm` here, let's
610 // just switch in the real SP, do what we need to do, and restore the
611 // existing setting afterwards.
612 const vixl::Register stashedSPreg = masm.GetStackPointer64();
613 masm.SetStackPointer64(vixl::sp);
614
615 AutoForbidPoolsAndNops afp(&masm,
616 /* number of instructions in scope = */ 4);
617
618 *entry = masm.currentOffset();
619
620 masm.Sub(sp, sp, sizeof(Frame));
621 masm.Str(ARMRegister(lr, 64), MemOperand(sp, Frame::returnAddressOffset()));
622 MOZ_ASSERT_IF(!masm.oom(), PushedRetAddr == masm.currentOffset() - *entry);
623 masm.Str(ARMRegister(FramePointer, 64),
624 MemOperand(sp, Frame::callerFPOffset()));
625 MOZ_ASSERT_IF(!masm.oom(), PushedFP == masm.currentOffset() - *entry);
626 masm.Mov(ARMRegister(FramePointer, 64), sp);
627 MOZ_ASSERT_IF(!masm.oom(), SetFP == masm.currentOffset() - *entry);
628
629 // And restore the SP-reg setting, per comment above.
630 masm.SetStackPointer64(stashedSPreg);
631 }
632 #else
633 {
634 # if defined(JS_CODEGEN_ARM)
635 AutoForbidPoolsAndNops afp(&masm,
636 /* number of instructions in scope = */ 3);
637
638 *entry = masm.currentOffset();
639
640 static_assert(BeforePushRetAddr == 0);
641 masm.push(lr);
642 # else
643 *entry = masm.currentOffset();
644 // The x86/x64 call instruction pushes the return address.
645 # endif
646
647 MOZ_ASSERT_IF(!masm.oom(), PushedRetAddr == masm.currentOffset() - *entry);
648 masm.push(FramePointer);
649 MOZ_ASSERT_IF(!masm.oom(), PushedFP == masm.currentOffset() - *entry);
650 masm.moveStackPtrTo(FramePointer);
651 MOZ_ASSERT_IF(!masm.oom(), SetFP == masm.currentOffset() - *entry);
652 }
653 #endif
654 }
655
656 static void GenerateCallableEpilogue(MacroAssembler& masm, unsigned framePushed,
657 ExitReason reason, uint32_t* ret) {
658 AutoCreatedBy acb(masm, "GenerateCallableEpilogue");
659
660 if (framePushed) {
661 masm.freeStack(framePushed);
662 }
663
664 if (!reason.isNone()) {
665 ClearExitFP(masm, ABINonArgReturnVolatileReg);
666 }
667
668 DebugOnly<uint32_t> poppedFP{};
669
670 #if defined(JS_CODEGEN_MIPS64)
671
672 masm.loadPtr(Address(StackPointer, Frame::callerFPOffset()), FramePointer);
673 poppedFP = masm.currentOffset();
674 masm.loadPtr(Address(StackPointer, Frame::returnAddressOffset()), ra);
675
676 *ret = masm.currentOffset();
677 masm.as_jr(ra);
678 masm.addToStackPtr(Imm32(sizeof(Frame)));
679
680 #elif defined(JS_CODEGEN_LOONG64)
681
682 masm.loadPtr(Address(StackPointer, Frame::callerFPOffset()), FramePointer);
683 poppedFP = masm.currentOffset();
684 masm.loadPtr(Address(StackPointer, Frame::returnAddressOffset()), ra);
685
686 *ret = masm.currentOffset();
687 masm.addToStackPtr(Imm32(sizeof(Frame)));
688 masm.as_jirl(zero, ra, BOffImm16(0));
689
690 #elif defined(JS_CODEGEN_RISCV64)
691 {
692 BlockTrampolinePoolScope block_trampoline_pool(&masm, 20);
693 masm.loadPtr(Address(StackPointer, Frame::callerFPOffset()), FramePointer);
694 poppedFP = masm.currentOffset();
695 masm.loadPtr(Address(StackPointer, Frame::returnAddressOffset()), ra);
696
697 *ret = masm.currentOffset();
698 masm.addToStackPtr(Imm32(sizeof(Frame)));
699 masm.jalr(zero, ra, 0);
700 masm.nop();
701 }
702 #elif defined(JS_CODEGEN_ARM64)
703
704 // See comment at equivalent place in |GenerateCallablePrologue| above.
705 const vixl::Register stashedSPreg = masm.GetStackPointer64();
706 masm.SetStackPointer64(vixl::sp);
707
708 AutoForbidPoolsAndNops afp(&masm, /* number of instructions in scope = */ 5);
709
710 masm.Ldr(ARMRegister(lr, 64), MemOperand(sp, Frame::returnAddressOffset()));
711 masm.Ldr(ARMRegister(FramePointer, 64),
712 MemOperand(sp, Frame::callerFPOffset()));
713 poppedFP = masm.currentOffset();
714
715 masm.Add(sp, sp, sizeof(Frame));
716
717 // Reinitialise PSP from SP. This is less than elegant because the prologue
718 // operates on the raw stack pointer SP and does not keep the PSP in sync.
719 // We can't use initPseudoStackPtr here because we just set up masm to not
720 // use it. Hence we have to do it "by hand".
721 masm.Mov(PseudoStackPointer64, vixl::sp);
722
723 *ret = masm.currentOffset();
724 masm.Ret(ARMRegister(lr, 64));
725
726 // See comment at equivalent place in |GenerateCallablePrologue| above.
727 masm.SetStackPointer64(stashedSPreg);
728
729 #else
730 // Forbid pools for the same reason as described in GenerateCallablePrologue.
731 # if defined(JS_CODEGEN_ARM)
732 AutoForbidPoolsAndNops afp(&masm, /* number of instructions in scope = */ 6);
733 # endif
734
735 // There is an important ordering constraint here: fp must be repointed to
736 // the caller's frame before any field of the frame currently pointed to by
737 // fp is popped: asynchronous signal handlers (which use stack space
738 // starting at sp) could otherwise clobber these fields while they are still
739 // accessible via fp (fp fields are read during frame iteration which is
740 // *also* done asynchronously).
741
742 masm.pop(FramePointer);
743 poppedFP = masm.currentOffset();
744
745 *ret = masm.currentOffset();
746 masm.ret();
747
748 #endif
749
750 MOZ_ASSERT_IF(!masm.oom(), PoppedFP == *ret - poppedFP);
751 }
752
753 // Generate the most minimal possible prologue: `push FP; FP := SP`.
754 void wasm::GenerateMinimalPrologue(MacroAssembler& masm, uint32_t* entry) {
755 MOZ_ASSERT(masm.framePushed() == 0);
756 GenerateCallablePrologue(masm, entry);
757 }
758
759 // Generate the most minimal possible epilogue: `pop FP; return`.
760 void wasm::GenerateMinimalEpilogue(MacroAssembler& masm, uint32_t* ret) {
761 MOZ_ASSERT(masm.framePushed() == 0);
762 GenerateCallableEpilogue(masm, /*framePushed=*/0, ExitReason::None(), ret);
763 }
764
765 void wasm::GenerateFunctionPrologue(MacroAssembler& masm,
766 const CallIndirectId& callIndirectId,
767 const Maybe<uint32_t>& tier1FuncIndex,
768 FuncOffsets* offsets) {
769 AutoCreatedBy acb(masm, "wasm::GenerateFunctionPrologue");
770
771 // We are going to generate this code layout:
772 // ---------------------------------------------
773 // checked call entry: callable prologue
774 // check signature
775 // jump functionBody ──┐
776 // unchecked call entry: callable prologue │
777 // functionBody <─────┘
778 // -----------------------------------------------
779 // checked call entry - used for call_indirect when we have to check the
780 // signature.
781 //
782 // unchecked call entry - used for regular direct same-instance calls.
783
784 // The checked call entry is a call target, so must have CodeAlignment.
785 // Its offset is normally zero.
786 static_assert(WasmCheckedCallEntryOffset % CodeAlignment == 0,
787 "code aligned");
788
789 // Flush pending pools so they do not get dumped between the 'begin' and
790 // 'uncheckedCallEntry' offsets since the difference must be less than
791 // UINT8_MAX to be stored in CodeRange::funcbeginToUncheckedCallEntry_.
792 // (Pending pools can be large.)
793 masm.flushBuffer();
794 masm.haltingAlign(CodeAlignment);
795
796 Label functionBody;
797
798 offsets->begin = masm.currentOffset();
799
800 // Only first-class functions (those that can be referenced in a table) need
801 // the checked call prologue w/ signature check. It is impossible to perform
802 // a checked call otherwise.
803 //
804 // asm.js function tables are homogeneous and don't need a signature check.
805 // However, they can be put in tables which expect a checked call entry point,
806 // so we generate a no-op entry point for consistency. If asm.js performance
807 // was important we could refine this in the future.
808 if (callIndirectId.kind() != CallIndirectIdKind::None) {
809 // Generate checked call entry. The BytecodeOffset of the trap is fixed up
810 // to be the bytecode offset of the callsite by
811 // JitActivation::startWasmTrap.
812 MOZ_ASSERT_IF(!masm.oom(), masm.currentOffset() - offsets->begin ==
813 WasmCheckedCallEntryOffset);
814 uint32_t dummy;
815 GenerateCallablePrologue(masm, &dummy);
816
817 switch (callIndirectId.kind()) {
818 case CallIndirectIdKind::Global: {
819 Label fail;
820 Register scratch1 = WasmTableCallScratchReg0;
821 Register scratch2 = WasmTableCallScratchReg1;
822
823 // Check if this function's type is exactly the expected function type
824 masm.loadPtr(
825 Address(InstanceReg,
826 Instance::offsetInData(
827 callIndirectId.instanceDataOffset() +
828 offsetof(wasm::TypeDefInstanceData, superTypeVector))),
829 scratch1);
830 masm.branchPtr(Assembler::Condition::Equal, WasmTableCallSigReg,
831 scratch1, &functionBody);
832
833 // Otherwise, we need to see if this function's type is a sub type of
834 // the expected function type. This requires us to check if the
835 // expected's type is in the super type vector of this function's type.
836 //
837 // We can skip this if our function type has no super types.
838 if (callIndirectId.hasSuperType()) {
839 // Check if the expected function type was an immediate, not a
840 // type definition. Because we only allow the immediate form for
841 // final types without super types, this implies that we have a
842 // signature mismatch.
843 masm.branchTestPtr(Assembler::Condition::NonZero, WasmTableCallSigReg,
844 Imm32(FuncType::ImmediateBit), &fail);
845
846 // Load the subtyping depth of the expected function type. Re-use the
847 // index register, as it's no longer needed.
848 Register subTypingDepth = WasmTableCallIndexReg;
849 masm.load32(
850 Address(WasmTableCallSigReg,
851 int32_t(SuperTypeVector::offsetOfSubTypingDepth())),
852 subTypingDepth);
853
854 // Perform the check
855 masm.branchWasmSTVIsSubtypeDynamicDepth(scratch1, WasmTableCallSigReg,
856 subTypingDepth, scratch2,
857 &functionBody, true);
858 }
859
860 masm.bind(&fail);
861 masm.wasmTrap(Trap::IndirectCallBadSig, TrapSiteDesc());
862 break;
863 }
864 case CallIndirectIdKind::Immediate: {
865 masm.branch32(Assembler::Condition::Equal, WasmTableCallSigReg,
866 Imm32(callIndirectId.immediate()), &functionBody);
867 masm.wasmTrap(Trap::IndirectCallBadSig, TrapSiteDesc());
868 break;
869 }
870 case CallIndirectIdKind::AsmJS:
871 masm.jump(&functionBody);
872 break;
873 case CallIndirectIdKind::None:
874 break;
875 }
876
877 // The preceding code may have generated a small constant pool to support
878 // the comparison in the signature check. But if we flush the pool here we
879 // will also force the creation of an unused branch veneer in the pool for
880 // the jump to functionBody from the signature check on some platforms, thus
881 // needlessly inflating the size of the prologue.
882 //
883 // On no supported platform that uses a pool (arm, arm64) is there any risk
884 // at present of that branch or other elements in the pool going out of
885 // range while we're generating the following padding and prologue,
886 // therefore no pool elements will be emitted in the prologue, therefore it
887 // is safe not to flush here.
888 //
889 // We assert that this holds at runtime by comparing the expected entry
890 // offset to the recorded ditto; if they are not the same then
891 // GenerateCallablePrologue flushed a pool before the prologue code,
892 // contrary to assumption.
893
894 masm.nopAlign(CodeAlignment);
895 }
896
897 // Generate unchecked call entry:
898 DebugOnly<uint32_t> expectedEntry = masm.currentOffset();
899 GenerateCallablePrologue(masm, &offsets->uncheckedCallEntry);
900 MOZ_ASSERT(expectedEntry == offsets->uncheckedCallEntry);
901 masm.bind(&functionBody);
902 #ifdef JS_CODEGEN_ARM64
903 // GenerateCallablePrologue creates a prologue which operates on the raw
904 // stack pointer and does not keep the PSP in sync. So we have to resync it
905 // here. But we can't use initPseudoStackPtr here because masm may not be
906 // set up to use it, depending on which compiler is in use. Hence do it
907 // "manually".
908 masm.Mov(PseudoStackPointer64, vixl::sp);
909 #endif
910
911 // See comment block in WasmCompile.cpp for an explanation tiering.
912 if (tier1FuncIndex) {
913 Register scratch = ABINonArgReg0;
914 masm.loadPtr(Address(InstanceReg, Instance::offsetOfJumpTable()), scratch);
915 masm.jump(Address(scratch, *tier1FuncIndex * sizeof(uintptr_t)));
916 }
917
918 offsets->tierEntry = masm.currentOffset();
919
920 MOZ_ASSERT(masm.framePushed() == 0);
921 }
922
923 void wasm::GenerateFunctionEpilogue(MacroAssembler& masm, unsigned framePushed,
924 FuncOffsets* offsets) {
925 // Inverse of GenerateFunctionPrologue:
926 MOZ_ASSERT(masm.framePushed() == framePushed);
927 GenerateCallableEpilogue(masm, framePushed, ExitReason::None(),
928 &offsets->ret);
929 MOZ_ASSERT(masm.framePushed() == 0);
930 }
931
932 void wasm::GenerateExitPrologue(MacroAssembler& masm, unsigned framePushed,
933 ExitReason reason, CallableOffsets* offsets) {
934 masm.haltingAlign(CodeAlignment);
935
936 GenerateCallablePrologue(masm, &offsets->begin);
937
938 // This frame will be exiting compiled code to C++ so record the fp and
939 // reason in the JitActivation so the frame iterators can unwind.
940 SetExitFP(masm, reason, ABINonArgReturnVolatileReg);
941
942 MOZ_ASSERT(masm.framePushed() == 0);
943 masm.reserveStack(framePushed);
944 }
945
946 void wasm::GenerateExitEpilogue(MacroAssembler& masm, unsigned framePushed,
947 ExitReason reason, CallableOffsets* offsets) {
948 // Inverse of GenerateExitPrologue:
949 MOZ_ASSERT(masm.framePushed() == framePushed);
950 GenerateCallableEpilogue(masm, framePushed, reason, &offsets->ret);
951 MOZ_ASSERT(masm.framePushed() == 0);
952 }
953
954 static void AssertNoWasmExitFPInJitExit(MacroAssembler& masm) {
955 // As a general stack invariant, if Activation::packedExitFP is tagged as
956 // wasm, it must point to a valid wasm::Frame. The JIT exit stub calls into
957 // JIT code and thus does not really exit, thus, when entering/leaving the
958 // JIT exit stub from/to normal wasm code, packedExitFP is not tagged wasm.
959 #ifdef DEBUG
960 Register scratch = ABINonArgReturnReg0;
961 LoadActivation(masm, scratch);
962
963 Label ok;
964 masm.branchTestPtr(Assembler::Zero,
965 Address(scratch, JitActivation::offsetOfPackedExitFP()),
966 Imm32(ExitFPTag), &ok);
967 masm.breakpoint();
968 masm.bind(&ok);
969 #endif
970 }
971
972 void wasm::GenerateJitExitPrologue(MacroAssembler& masm, unsigned framePushed,
973 uint32_t fallbackOffset,
974 ImportOffsets* offsets) {
975 masm.haltingAlign(CodeAlignment);
976
977 #ifdef ENABLE_WASM_JSPI
978 {
979 # if defined(JS_CODEGEN_ARM64)
980 AutoForbidPoolsAndNops afp(&masm,
981 /* number of instructions in scope = */ 2);
982 # endif
983 offsets->begin = masm.currentOffset();
984 Label fallback;
985 masm.bind(&fallback, BufferOffset(fallbackOffset));
986
987 const Register scratch = ABINonArgReg0;
988 masm.load32(Address(InstanceReg, Instance::offsetOfOnSuspendableStack()),
989 scratch);
990 masm.branchTest32(Assembler::NonZero, scratch, scratch, &fallback);
991 }
992
993 uint32_t entryOffset;
994 GenerateCallablePrologue(masm, &entryOffset);
995 offsets->afterFallbackCheck = entryOffset;
996 #else
997 GenerateCallablePrologue(masm, &offsets->begin);
998 offsets->afterFallbackCheck = offsets->begin;
999 #endif // ENABLE_WASM_JSPI
1000
1001 AssertNoWasmExitFPInJitExit(masm);
1002
1003 MOZ_ASSERT(masm.framePushed() == 0);
1004 masm.reserveStack(framePushed);
1005 }
1006
1007 void wasm::GenerateJitExitEpilogue(MacroAssembler& masm, unsigned framePushed,
1008 CallableOffsets* offsets) {
1009 // Inverse of GenerateJitExitPrologue:
1010 MOZ_ASSERT(masm.framePushed() == framePushed);
1011 AssertNoWasmExitFPInJitExit(masm);
1012 GenerateCallableEpilogue(masm, framePushed, ExitReason::None(),
1013 &offsets->ret);
1014 MOZ_ASSERT(masm.framePushed() == 0);
1015 }
1016
1017 void wasm::GenerateJitEntryPrologue(MacroAssembler& masm,
1018 CallableOffsets* offsets) {
1019 masm.haltingAlign(CodeAlignment);
1020
1021 {
1022 // Push the return address.
1023 #if defined(JS_CODEGEN_ARM)
1024 AutoForbidPoolsAndNops afp(&masm,
1025 /* number of instructions in scope = */ 3);
1026 offsets->begin = masm.currentOffset();
1027 static_assert(BeforePushRetAddr == 0);
1028 masm.push(lr);
1029 #elif defined(JS_CODEGEN_MIPS64)
1030 offsets->begin = masm.currentOffset();
1031 masm.push(ra);
1032 #elif defined(JS_CODEGEN_LOONG64)
1033 offsets->begin = masm.currentOffset();
1034 masm.push(ra);
1035 #elif defined(JS_CODEGEN_RISCV64)
1036 BlockTrampolinePoolScope block_trampoline_pool(&masm, 10);
1037 offsets->begin = masm.currentOffset();
1038 masm.push(ra);
1039 #elif defined(JS_CODEGEN_ARM64)
1040 {
1041 AutoForbidPoolsAndNops afp(&masm,
1042 /* number of instructions in scope = */ 4);
1043 offsets->begin = masm.currentOffset();
1044 static_assert(BeforePushRetAddr == 0);
1045 // Subtract from SP first as SP must be aligned before offsetting.
1046 masm.Sub(sp, sp, 16);
1047 static_assert(JitFrameLayout::offsetOfReturnAddress() == 8);
1048 masm.Str(ARMRegister(lr, 64), MemOperand(sp, 8));
1049 }
1050 #else
1051 // The x86/x64 call instruction pushes the return address.
1052 offsets->begin = masm.currentOffset();
1053 #endif
1054 MOZ_ASSERT_IF(!masm.oom(),
1055 PushedRetAddr == masm.currentOffset() - offsets->begin);
1056 // Save jit frame pointer, so unwinding from wasm to jit frames is trivial.
1057 #if defined(JS_CODEGEN_ARM64)
1058 static_assert(JitFrameLayout::offsetOfCallerFramePtr() == 0);
1059 masm.Str(ARMRegister(FramePointer, 64), MemOperand(sp, 0));
1060 #else
1061 masm.Push(FramePointer);
1062 #endif
1063 MOZ_ASSERT_IF(!masm.oom(),
1064 PushedFP == masm.currentOffset() - offsets->begin);
1065
1066 masm.moveStackPtrTo(FramePointer);
1067 MOZ_ASSERT_IF(!masm.oom(), SetFP == masm.currentOffset() - offsets->begin);
1068 }
1069
1070 masm.setFramePushed(0);
1071 }
1072
1073 void wasm::GenerateJitEntryEpilogue(MacroAssembler& masm,
1074 CallableOffsets* offsets) {
1075 DebugOnly<uint32_t> poppedFP{};
1076 #ifdef JS_CODEGEN_ARM64
1077 {
1078 RegisterOrSP sp = masm.getStackPointer();
1079 AutoForbidPoolsAndNops afp(&masm,
1080 /* number of instructions in scope = */ 5);
1081 masm.loadPtr(Address(sp, 8), lr);
1082 masm.loadPtr(Address(sp, 0), FramePointer);
1083 poppedFP = masm.currentOffset();
1084
1085 masm.addToStackPtr(Imm32(2 * sizeof(void*)));
1086 // Copy SP into PSP to enforce return-point invariants (SP == PSP).
1087 // `addToStackPtr` won't sync them because SP is the active pointer here.
1088 // For the same reason, we can't use initPseudoStackPtr to do the sync, so
1089 // we have to do it "by hand". Omitting this causes many tests to segfault.
1090 masm.moveStackPtrTo(PseudoStackPointer);
1091
1092 offsets->ret = masm.currentOffset();
1093 masm.Ret(ARMRegister(lr, 64));
1094 masm.setFramePushed(0);
1095 }
1096 #else
1097 // Forbid pools for the same reason as described in GenerateCallablePrologue.
1098 # if defined(JS_CODEGEN_ARM)
1099 AutoForbidPoolsAndNops afp(&masm, /* number of instructions in scope = */ 2);
1100 # endif
1101
1102 masm.pop(FramePointer);
1103 poppedFP = masm.currentOffset();
1104
1105 offsets->ret = masm.currentOffset();
1106 masm.ret();
1107 #endif
1108 MOZ_ASSERT_IF(!masm.oom(), PoppedFPJitEntry == offsets->ret - poppedFP);
1109 }
1110
1111 /*****************************************************************************/
1112 // ProfilingFrameIterator
1113
1114 ProfilingFrameIterator::ProfilingFrameIterator()
1115 : code_(nullptr),
1116 codeRange_(nullptr),
1117 category_(Category::Other),
1118 callerFP_(nullptr),
1119 callerPC_(nullptr),
1120 stackAddress_(nullptr),
1121 unwoundJitCallerFP_(nullptr),
1122 exitReason_(ExitReason::Fixed::None) {
1123 MOZ_ASSERT(done());
1124 }
1125
1126 ProfilingFrameIterator::ProfilingFrameIterator(const JitActivation& activation)
1127 : code_(nullptr),
1128 codeRange_(nullptr),
1129 category_(Category::Other),
1130 callerFP_(nullptr),
1131 callerPC_(nullptr),
1132 stackAddress_(nullptr),
1133 unwoundJitCallerFP_(nullptr),
1134 exitReason_(activation.wasmExitReason()) {
1135 initFromExitFP(activation.wasmExitFP());
1136 }
1137
1138 ProfilingFrameIterator::ProfilingFrameIterator(const Frame* fp)
1139 : code_(nullptr),
1140 codeRange_(nullptr),
1141 category_(Category::Other),
1142 callerFP_(nullptr),
1143 callerPC_(nullptr),
1144 stackAddress_(nullptr),
1145 unwoundJitCallerFP_(nullptr),
1146 exitReason_(ExitReason::Fixed::ImportJit) {
1147 MOZ_ASSERT(fp);
1148 initFromExitFP(fp);
1149 }
1150
1151 static inline void AssertMatchesCallSite(void* callerPC, uint8_t* callerFP) {
1152 #ifdef DEBUG
1153 const CodeRange* callerCodeRange;
1154 const Code* code = LookupCode(callerPC, &callerCodeRange);
1155
1156 if (!code) {
1157 AssertDirectJitCall(callerFP);
1158 return;
1159 }
1160
1161 MOZ_ASSERT(callerCodeRange);
1162
1163 if (callerCodeRange->isInterpEntry()) {
1164 // callerFP is the value of the frame pointer register when we were called
1165 // from C++.
1166 return;
1167 }
1168
1169 if (callerCodeRange->isJitEntry()) {
1170 MOZ_ASSERT(callerFP != nullptr);
1171 return;
1172 }
1173
1174 CallSite site;
1175 MOZ_ALWAYS_TRUE(code->lookupCallSite(callerPC, &site));
1176 #endif
1177 }
1178
1179 void ProfilingFrameIterator::initFromExitFP(const Frame* fp) {
1180 MOZ_ASSERT(fp);
1181 stackAddress_ = (void*)fp;
1182 endStackAddress_ = stackAddress_;
1183 const CodeBlock* codeBlock =
1184 LookupCodeBlock(fp->returnAddress(), &codeRange_);
1185
1186 if (!codeBlock) {
1187 category_ = Category::Other;
1188 code_ = nullptr;
1189 } else {
1190 code_ = codeBlock->code;
1191 category_ = categoryFromCodeBlock(codeBlock->kind);
1192 }
1193
1194 if (!code_) {
1195 // This is a direct call from the JIT, the caller FP is pointing to the JIT
1196 // caller's frame.
1197 AssertDirectJitCall(fp->jitEntryCaller());
1198
1199 unwoundJitCallerFP_ = fp->jitEntryCaller();
1200 MOZ_ASSERT(done());
1201 return;
1202 }
1203
1204 MOZ_ASSERT(codeRange_);
1205
1206 // Since we don't have the pc for fp, start unwinding at the caller of fp.
1207 // This means that the innermost frame is skipped. This is fine because:
1208 // - for import exit calls, the innermost frame is a thunk, so the first
1209 // frame that shows up is the function calling the import;
1210 // - for Math and other builtin calls, we note the absence of an exit
1211 // reason and inject a fake "builtin" frame; and
1212 switch (codeRange_->kind()) {
1213 case CodeRange::InterpEntry:
1214 callerPC_ = nullptr;
1215 callerFP_ = nullptr;
1216 break;
1217 case CodeRange::JitEntry:
1218 callerPC_ = nullptr;
1219 callerFP_ = fp->rawCaller();
1220 break;
1221 case CodeRange::Function:
1222 fp = fp->wasmCaller();
1223 callerPC_ = fp->returnAddress();
1224 callerFP_ = fp->rawCaller();
1225 AssertMatchesCallSite(callerPC_, callerFP_);
1226 break;
1227 case CodeRange::ImportJitExit:
1228 case CodeRange::ImportInterpExit:
1229 case CodeRange::BuiltinThunk:
1230 case CodeRange::TrapExit:
1231 case CodeRange::DebugStub:
1232 case CodeRange::RequestTierUpStub:
1233 case CodeRange::UpdateCallRefMetricsStub:
1234 case CodeRange::Throw:
1235 case CodeRange::FarJumpIsland:
1236 MOZ_CRASH("Unexpected CodeRange kind");
1237 }
1238
1239 MOZ_ASSERT(!done());
1240 }
1241
1242 static bool IsSignatureCheckFail(uint32_t offsetInCode,
1243 const CodeRange* codeRange) {
1244 if (!codeRange->isFunction()) {
1245 return false;
1246 }
1247 // checked call entry: 1. push Frame
1248 // 2. set FP
1249 // 3. signature check <--- check if we are here.
1250 // 4. jump 7
1251 // unchecked call entry: 5. push Frame
1252 // 6. set FP
1253 // 7. function's code
1254 return offsetInCode < codeRange->funcUncheckedCallEntry() &&
1255 (offsetInCode - codeRange->funcCheckedCallEntry()) > SetFP;
1256 }
1257
1258 static bool CanUnwindSignatureCheck(uint8_t* fp) {
1259 const auto* frame = Frame::fromUntaggedWasmExitFP(fp);
1260 uint8_t* const pc = frame->returnAddress();
1261
1262 const CodeRange* codeRange;
1263 const Code* code = LookupCode(pc, &codeRange);
1264 // If a JIT call or JIT/interpreter entry was found,
1265 // unwinding is not possible.
1266 return code && !codeRange->isEntry();
1267 }
1268
1269 static bool GetUnwindInfo(const CodeBlock* codeBlock,
1270 const CodeRange* codeRange, uint8_t* pc,
1271 const CodeRangeUnwindInfo** info) {
1272 if (!codeRange->isFunction() || !codeRange->funcHasUnwindInfo()) {
1273 return false;
1274 }
1275
1276 *info = codeBlock->code->lookupUnwindInfo(pc);
1277 return *info;
1278 }
1279
1280 const Instance* js::wasm::GetNearestEffectiveInstance(const Frame* fp) {
1281 while (true) {
1282 uint8_t* returnAddress = fp->returnAddress();
1283 const CodeRange* codeRange = nullptr;
1284 const Code* code = LookupCode(returnAddress, &codeRange);
1285
1286 if (!code) {
1287 // It is a direct call from JIT.
1288 AssertDirectJitCall(fp->jitEntryCaller());
1289 return ExtractCalleeInstanceFromFrameWithInstances(fp);
1290 }
1291
1292 MOZ_ASSERT(codeRange);
1293
1294 if (codeRange->isEntry()) {
1295 return ExtractCalleeInstanceFromFrameWithInstances(fp);
1296 }
1297
1298 MOZ_ASSERT(codeRange->kind() == CodeRange::Function);
1299 MOZ_ASSERT(code);
1300 CallSite site;
1301 MOZ_ALWAYS_TRUE(code->lookupCallSite(returnAddress, &site));
1302 if (site.mightBeCrossInstance()) {
1303 return ExtractCalleeInstanceFromFrameWithInstances(fp);
1304 }
1305
1306 fp = fp->wasmCaller();
1307 }
1308 }
1309
1310 Instance* js::wasm::GetNearestEffectiveInstance(Frame* fp) {
1311 return const_cast<Instance*>(
1312 GetNearestEffectiveInstance(const_cast<const Frame*>(fp)));
1313 }
1314
1315 bool js::wasm::StartUnwinding(const RegisterState& registers,
1316 UnwindState* unwindState, bool* unwoundCaller) {
1317 // Shorthands.
1318 uint8_t* const pc = (uint8_t*)registers.pc;
1319 void** const sp = (void**)registers.sp;
1320
1321 // The frame pointer might be:
1322 // - in the process of tagging/untagging when calling into C++ code (this
1323 // happens in wasm::SetExitFP); make sure it's untagged.
1324 // - unreliable if it's not been set yet, in prologues.
1325 uint8_t* fp = Frame::isExitFP(registers.fp)
1326 ? Frame::untagExitFP(registers.fp)
1327 : reinterpret_cast<uint8_t*>(registers.fp);
1328
1329 // Get the CodeRange describing pc and the base address to which the
1330 // CodeRange is relative. If the pc is not in a wasm module or a builtin
1331 // thunk, then execution must be entering from or leaving to the C++ caller
1332 // that pushed the JitActivation.
1333 const CodeRange* codeRange;
1334 const uint8_t* codeBase;
1335 const Code* code = nullptr;
1336
1337 const CodeBlock* codeBlock = LookupCodeBlock(pc, &codeRange);
1338 if (codeBlock) {
1339 code = codeBlock->code;
1340 codeBase = codeBlock->base();
1341 MOZ_ASSERT(codeRange);
1342 } else if (!LookupBuiltinThunk(pc, &codeRange, &codeBase)) {
1343 return false;
1344 }
1345
1346 // When the pc is inside the prologue/epilogue, the innermost call's Frame
1347 // is not complete and thus fp points to the second-to-innermost call's
1348 // Frame. Since fp can only tell you about its caller, naively unwinding
1349 // while pc is in the prologue/epilogue would skip the second-to-innermost
1350 // call. To avoid this problem, we use the static structure of the code in
1351 // the prologue and epilogue to do the Right Thing.
1352 uint32_t offsetInCode = pc - codeBase;
1353 MOZ_ASSERT(offsetInCode >= codeRange->begin());
1354 MOZ_ASSERT(offsetInCode < codeRange->end());
1355
1356 // Compute the offset of the pc from the (unchecked call) entry of the code
1357 // range. The checked call entry and the unchecked call entry have common
1358 // prefix, so pc before signature check in the checked call entry is
1359 // equivalent to the pc of the unchecked-call-entry. Thus, we can simplify the
1360 // below case analysis by redirecting all pc-in-checked-call-entry before
1361 // signature check cases to the pc-at-unchecked-call-entry case.
1362 uint32_t offsetFromEntry;
1363 if (codeRange->isFunction()) {
1364 if (offsetInCode < codeRange->funcUncheckedCallEntry()) {
1365 offsetFromEntry = offsetInCode - codeRange->funcCheckedCallEntry();
1366 } else {
1367 offsetFromEntry = offsetInCode - codeRange->funcUncheckedCallEntry();
1368 }
1369 } else if (codeRange->isImportJitExit()) {
1370 if (offsetInCode < codeRange->importJitExitEntry()) {
1371 // Anything above entry shall not change stack/frame pointer --
1372 // collapse this code into single point.
1373 offsetFromEntry = 0;
1374 } else {
1375 offsetFromEntry = offsetInCode - codeRange->importJitExitEntry();
1376 }
1377 } else {
1378 offsetFromEntry = offsetInCode - codeRange->begin();
1379 }
1380
1381 // Most cases end up unwinding to the caller state; not unwinding is the
1382 // exception here.
1383 *unwoundCaller = true;
1384
1385 uint8_t* fixedFP = nullptr;
1386 void* fixedPC = nullptr;
1387 switch (codeRange->kind()) {
1388 case CodeRange::Function:
1389 case CodeRange::FarJumpIsland:
1390 case CodeRange::ImportJitExit:
1391 case CodeRange::ImportInterpExit:
1392 case CodeRange::BuiltinThunk:
1393 case CodeRange::DebugStub:
1394 case CodeRange::RequestTierUpStub:
1395 case CodeRange::UpdateCallRefMetricsStub:
1396 #if defined(JS_CODEGEN_MIPS64)
1397 if (codeRange->isThunk()) {
1398 // The FarJumpIsland sequence temporary scrambles ra.
1399 // Don't unwind to caller.
1400 fixedPC = pc;
1401 fixedFP = fp;
1402 *unwoundCaller = false;
1403 AssertMatchesCallSite(
1404 Frame::fromUntaggedWasmExitFP(fp)->returnAddress(),
1405 Frame::fromUntaggedWasmExitFP(fp)->rawCaller());
1406 } else if (offsetFromEntry < PushedFP) {
1407 // On MIPS we rely on register state instead of state saved on
1408 // stack until the wasm::Frame is completely built.
1409 // On entry the return address is in ra (registers.lr) and
1410 // fp holds the caller's fp.
1411 fixedPC = (uint8_t*)registers.lr;
1412 fixedFP = fp;
1413 AssertMatchesCallSite(fixedPC, fixedFP);
1414 } else
1415 #elif defined(JS_CODEGEN_LOONG64)
1416 if (codeRange->isThunk()) {
1417 // The FarJumpIsland sequence temporary scrambles ra.
1418 // Don't unwind to caller.
1419 fixedPC = pc;
1420 fixedFP = fp;
1421 *unwoundCaller = false;
1422 AssertMatchesCallSite(
1423 Frame::fromUntaggedWasmExitFP(fp)->returnAddress(),
1424 Frame::fromUntaggedWasmExitFP(fp)->rawCaller());
1425 } else if (offsetFromEntry < PushedFP) {
1426 // On LoongArch we rely on register state instead of state saved on
1427 // stack until the wasm::Frame is completely built.
1428 // On entry the return address is in ra (registers.lr) and
1429 // fp holds the caller's fp.
1430 fixedPC = (uint8_t*)registers.lr;
1431 fixedFP = fp;
1432 AssertMatchesCallSite(fixedPC, fixedFP);
1433 } else
1434 #elif defined(JS_CODEGEN_RISCV64)
1435 if (codeRange->isThunk()) {
1436 // The FarJumpIsland sequence temporary scrambles ra.
1437 // Don't unwind to caller.
1438 fixedPC = pc;
1439 fixedFP = fp;
1440 *unwoundCaller = false;
1441 AssertMatchesCallSite(
1442 Frame::fromUntaggedWasmExitFP(fp)->returnAddress(),
1443 Frame::fromUntaggedWasmExitFP(fp)->rawCaller());
1444 } else if (offsetFromEntry < PushedFP) {
1445 // On Riscv64 we rely on register state instead of state saved on
1446 // stack until the wasm::Frame is completely built.
1447 // On entry the return address is in ra (registers.lr) and
1448 // fp holds the caller's fp.
1449 fixedPC = (uint8_t*)registers.lr;
1450 fixedFP = fp;
1451 AssertMatchesCallSite(fixedPC, fixedFP);
1452 } else
1453 #elif defined(JS_CODEGEN_ARM64)
1454 if (offsetFromEntry < PushedFP || codeRange->isThunk()) {
1455 // Constraints above ensure that this covers BeforePushRetAddr and
1456 // PushedRetAddr.
1457 //
1458 // On ARM64 we subtract the size of the Frame from SP and then store
1459 // values into the stack. Execution can be interrupted at various
1460 // places in that sequence. We rely on the register state for our
1461 // values.
1462 fixedPC = (uint8_t*)registers.lr;
1463 fixedFP = fp;
1464 AssertMatchesCallSite(fixedPC, fixedFP);
1465 } else
1466 #elif defined(JS_CODEGEN_ARM)
1467 if (offsetFromEntry == BeforePushRetAddr || codeRange->isThunk()) {
1468 // The return address is still in lr and fp holds the caller's fp.
1469 fixedPC = (uint8_t*)registers.lr;
1470 fixedFP = fp;
1471 AssertMatchesCallSite(fixedPC, fixedFP);
1472 } else
1473 #endif
1474 if (offsetFromEntry == PushedRetAddr || codeRange->isThunk()) {
1475 // The return address has been pushed on the stack but fp still
1476 // points to the caller's fp.
1477 fixedPC = sp[0];
1478 fixedFP = fp;
1479 AssertMatchesCallSite(fixedPC, fixedFP);
1480 } else if (offsetFromEntry == PushedFP) {
1481 // The full Frame has been pushed; fp is still the caller's fp.
1482 const auto* frame = Frame::fromUntaggedWasmExitFP(sp);
1483 MOZ_ASSERT(frame->rawCaller() == fp);
1484 fixedPC = frame->returnAddress();
1485 fixedFP = fp;
1486 AssertMatchesCallSite(fixedPC, fixedFP);
1487 #if defined(JS_CODEGEN_MIPS64)
1488 } else if (offsetInCode >= codeRange->ret() - PoppedFP &&
1489 offsetInCode <= codeRange->ret()) {
1490 // The fixedFP field of the Frame has been loaded into fp.
1491 // The ra and instance might also be loaded, but the Frame structure is
1492 // still on stack, so we can acess the ra form there.
1493 MOZ_ASSERT(*sp == fp);
1494 fixedPC = Frame::fromUntaggedWasmExitFP(sp)->returnAddress();
1495 fixedFP = fp;
1496 AssertMatchesCallSite(fixedPC, fixedFP);
1497 #elif defined(JS_CODEGEN_LOONG64)
1498 } else if (offsetInCode >= codeRange->ret() - PoppedFP &&
1499 offsetInCode <= codeRange->ret()) {
1500 // The fixedFP field of the Frame has been loaded into fp.
1501 // The ra might also be loaded, but the Frame structure is still on
1502 // stack, so we can acess the ra from there.
1503 MOZ_ASSERT(*sp == fp);
1504 fixedPC = Frame::fromUntaggedWasmExitFP(sp)->returnAddress();
1505 fixedFP = fp;
1506 AssertMatchesCallSite(fixedPC, fixedFP);
1507 #elif defined(JS_CODEGEN_RISCV64)
1508 } else if (offsetInCode >= codeRange->ret() - PoppedFP &&
1509 offsetInCode <= codeRange->ret()) {
1510 // The fixedFP field of the Frame has been loaded into fp.
1511 // The ra might also be loaded, but the Frame structure is still on
1512 // stack, so we can acess the ra from there.
1513 MOZ_ASSERT(*sp == fp);
1514 fixedPC = Frame::fromUntaggedWasmExitFP(sp)->returnAddress();
1515 fixedFP = fp;
1516 AssertMatchesCallSite(fixedPC, fixedFP);
1517 #elif defined(JS_CODEGEN_ARM64)
1518 // The stack pointer does not move until all values have
1519 // been restored so several cases can be coalesced here.
1520 } else if (offsetInCode >= codeRange->ret() - PoppedFP &&
1521 offsetInCode <= codeRange->ret()) {
1522 fixedPC = (uint8_t*)registers.lr;
1523 fixedFP = fp;
1524 AssertMatchesCallSite(fixedPC, fixedFP);
1525 #else
1526 } else if (offsetInCode >= codeRange->ret() - PoppedFP &&
1527 offsetInCode < codeRange->ret()) {
1528 // The fixedFP field of the Frame has been popped into fp.
1529 fixedPC = sp[1];
1530 fixedFP = fp;
1531 AssertMatchesCallSite(fixedPC, fixedFP);
1532 } else if (offsetInCode == codeRange->ret()) {
1533 // Both the instance and fixedFP fields have been popped and fp now
1534 // points to the caller's frame.
1535 fixedPC = sp[0];
1536 fixedFP = fp;
1537 AssertMatchesCallSite(fixedPC, fixedFP);
1538 #endif
1539 } else {
1540 if (IsSignatureCheckFail(offsetInCode, codeRange) &&
1541 CanUnwindSignatureCheck(fp)) {
1542 // Frame has been pushed and FP has been set.
1543 const auto* frame = Frame::fromUntaggedWasmExitFP(fp);
1544 fixedFP = frame->rawCaller();
1545 fixedPC = frame->returnAddress();
1546 AssertMatchesCallSite(fixedPC, fixedFP);
1547 break;
1548 }
1549
1550 const CodeRangeUnwindInfo* unwindInfo;
1551 if (codeBlock && GetUnwindInfo(codeBlock, codeRange, pc, &unwindInfo)) {
1552 switch (unwindInfo->unwindHow()) {
1553 case CodeRangeUnwindInfo::RestoreFpRa:
1554 fixedPC = (uint8_t*)registers.tempRA;
1555 fixedFP = (uint8_t*)registers.tempFP;
1556 break;
1557 case CodeRangeUnwindInfo::RestoreFp:
1558 fixedPC = sp[0];
1559 fixedFP = (uint8_t*)registers.tempFP;
1560 break;
1561 case CodeRangeUnwindInfo::UseFpLr:
1562 fixedPC = (uint8_t*)registers.lr;
1563 fixedFP = fp;
1564 break;
1565 case CodeRangeUnwindInfo::UseFp:
1566 fixedPC = sp[0];
1567 fixedFP = fp;
1568 break;
1569 default:
1570 MOZ_CRASH();
1571 }
1572 MOZ_ASSERT(fixedPC && fixedFP);
1573 break;
1574 }
1575
1576 // Not in the prologue/epilogue.
1577 fixedPC = pc;
1578 fixedFP = fp;
1579 *unwoundCaller = false;
1580 AssertMatchesCallSite(
1581 Frame::fromUntaggedWasmExitFP(fp)->returnAddress(),
1582 Frame::fromUntaggedWasmExitFP(fp)->rawCaller());
1583 break;
1584 }
1585 break;
1586 case CodeRange::TrapExit:
1587 // These code stubs execute after the prologue/epilogue have completed
1588 // so pc/fp contains the right values here.
1589 fixedPC = pc;
1590 fixedFP = fp;
1591 *unwoundCaller = false;
1592 AssertMatchesCallSite(Frame::fromUntaggedWasmExitFP(fp)->returnAddress(),
1593 Frame::fromUntaggedWasmExitFP(fp)->rawCaller());
1594 break;
1595 case CodeRange::InterpEntry:
1596 // The entry trampoline is the final frame in an wasm JitActivation. The
1597 // entry trampoline also doesn't GeneratePrologue/Epilogue so we can't
1598 // use the general unwinding logic above.
1599 break;
1600 case CodeRange::JitEntry:
1601 // There's a jit frame above the current one; we don't care about pc
1602 // since the Jit entry frame is a jit frame which can be considered as
1603 // an exit frame.
1604 if (offsetFromEntry < PushedFP) {
1605 // We haven't pushed the jit caller's frame pointer yet, thus the jit
1606 // frame is incomplete. During profiling frame iteration, it means that
1607 // the jit profiling frame iterator won't be able to unwind this frame;
1608 // drop it.
1609 return false;
1610 }
1611 if (offsetInCode >= codeRange->ret() - PoppedFPJitEntry &&
1612 offsetInCode <= codeRange->ret()) {
1613 // We've popped FP but still have to return. Similar to the
1614 // |offsetFromEntry < PushedFP| case above, the JIT frame is now
1615 // incomplete and we can't unwind.
1616 return false;
1617 }
1618 // Set fixedFP to the address of the JitFrameLayout on the stack.
1619 if (offsetFromEntry < SetFP) {
1620 fixedFP = reinterpret_cast<uint8_t*>(sp);
1621 } else {
1622 fixedFP = fp;
1623 }
1624 fixedPC = nullptr;
1625 break;
1626 case CodeRange::Throw:
1627 // The throw stub executes a small number of instructions before popping
1628 // the entire activation. To simplify testing, we simply pretend throw
1629 // stubs have already popped the entire stack.
1630 return false;
1631 }
1632
1633 unwindState->code = code;
1634 unwindState->codeRange = codeRange;
1635 unwindState->fp = fixedFP;
1636 unwindState->pc = fixedPC;
1637 return true;
1638 }
1639
1640 ProfilingFrameIterator::ProfilingFrameIterator(const JitActivation& activation,
1641 const RegisterState& state)
1642 : code_(nullptr),
1643 codeRange_(nullptr),
1644 category_(Category::Other),
1645 callerFP_(nullptr),
1646 callerPC_(nullptr),
1647 stackAddress_(nullptr),
1648 unwoundJitCallerFP_(nullptr),
1649 exitReason_(ExitReason::Fixed::None) {
1650 // Let wasmExitFP take precedence to StartUnwinding when it is set since
1651 // during the body of an exit stub, the register state may not be valid
1652 // causing StartUnwinding() to abandon unwinding this activation.
1653 if (activation.hasWasmExitFP()) {
1654 exitReason_ = activation.wasmExitReason();
1655 initFromExitFP(activation.wasmExitFP());
1656 return;
1657 }
1658
1659 bool unwoundCaller;
1660 UnwindState unwindState;
1661 if (!StartUnwinding(state, &unwindState, &unwoundCaller)) {
1662 MOZ_ASSERT(done());
1663 return;
1664 }
1665
1666 MOZ_ASSERT(unwindState.codeRange);
1667
1668 if (unwoundCaller) {
1669 callerFP_ = unwindState.fp;
1670 callerPC_ = unwindState.pc;
1671 } else {
1672 callerFP_ = Frame::fromUntaggedWasmExitFP(unwindState.fp)->rawCaller();
1673 callerPC_ = Frame::fromUntaggedWasmExitFP(unwindState.fp)->returnAddress();
1674 }
1675
1676 code_ = unwindState.code;
1677 codeRange_ = unwindState.codeRange;
1678 stackAddress_ = state.sp;
1679 endStackAddress_ = state.sp;
1680
1681 // Initialize the category if it's not already done.
1682 if (const CodeBlock* codeBlock = LookupCodeBlock(callerPC_)) {
1683 category_ = categoryFromCodeBlock(codeBlock->kind);
1684 }
1685
1686 MOZ_ASSERT(!done());
1687 }
1688
1689 void ProfilingFrameIterator::operator++() {
1690 MOZ_ASSERT(!done());
1691 MOZ_ASSERT(!unwoundJitCallerFP_);
1692
1693 if (!exitReason_.isNone()) {
1694 if (const CodeBlock* codeBlock = LookupCodeBlock(callerPC_)) {
1695 category_ = categoryFromCodeBlock(codeBlock->kind);
1696 } else {
1697 category_ = Category::Other;
1698 }
1699 exitReason_ = ExitReason::None();
1700 MOZ_ASSERT(codeRange_);
1701 MOZ_ASSERT(!done());
1702 return;
1703 }
1704
1705 if (codeRange_->isInterpEntry()) {
1706 category_ = Category::Other;
1707 codeRange_ = nullptr;
1708 MOZ_ASSERT(done());
1709 return;
1710 }
1711
1712 if (codeRange_->isJitEntry()) {
1713 category_ = Category::Other;
1714 MOZ_ASSERT(callerFP_);
1715 unwoundJitCallerFP_ = callerFP_;
1716 callerPC_ = nullptr;
1717 callerFP_ = nullptr;
1718 codeRange_ = nullptr;
1719 MOZ_ASSERT(done());
1720 return;
1721 }
1722
1723 MOZ_RELEASE_ASSERT(callerPC_);
1724
1725 const CodeBlock* codeBlock = LookupCodeBlock(callerPC_, &codeRange_);
1726 code_ = codeBlock ? codeBlock->code : nullptr;
1727
1728 if (!code_) {
1729 category_ = Category::Other;
1730 // The parent frame is an inlined wasm call, callerFP_ points to the fake
1731 // exit frame.
1732 MOZ_ASSERT(!codeRange_);
1733 AssertDirectJitCall(callerFP_);
1734 unwoundJitCallerFP_ = callerFP_;
1735 MOZ_ASSERT(done());
1736 return;
1737 }
1738
1739 MOZ_ASSERT(codeRange_);
1740
1741 if (codeRange_->isInterpEntry()) {
1742 category_ = Category::Other;
1743 callerPC_ = nullptr;
1744 callerFP_ = nullptr;
1745 MOZ_ASSERT(!done());
1746 return;
1747 }
1748
1749 if (codeRange_->isJitEntry()) {
1750 category_ = Category::Other;
1751 MOZ_ASSERT(!done());
1752 return;
1753 }
1754
1755 MOZ_ASSERT(code_ == &GetNearestEffectiveInstance(
1756 Frame::fromUntaggedWasmExitFP(callerFP_))
1757 ->code());
1758
1759 category_ = categoryFromCodeBlock(codeBlock->kind);
1760
1761 switch (codeRange_->kind()) {
1762 case CodeRange::Function:
1763 case CodeRange::ImportJitExit:
1764 case CodeRange::ImportInterpExit:
1765 case CodeRange::BuiltinThunk:
1766 case CodeRange::TrapExit:
1767 case CodeRange::DebugStub:
1768 case CodeRange::RequestTierUpStub:
1769 case CodeRange::UpdateCallRefMetricsStub:
1770 case CodeRange::FarJumpIsland: {
1771 stackAddress_ = callerFP_;
1772 const auto* frame = Frame::fromUntaggedWasmExitFP(callerFP_);
1773 callerPC_ = frame->returnAddress();
1774 AssertMatchesCallSite(callerPC_, frame->rawCaller());
1775 callerFP_ = frame->rawCaller();
1776 break;
1777 }
1778 case CodeRange::InterpEntry:
1779 case CodeRange::JitEntry:
1780 MOZ_CRASH("should have been guarded above");
1781 case CodeRange::Throw:
1782 MOZ_CRASH("code range doesn't have frame");
1783 }
1784
1785 MOZ_ASSERT(!done());
1786 }
1787
1788 static const char* ThunkedNativeToDescription(SymbolicAddress func) {
1789 MOZ_ASSERT(NeedsBuiltinThunk(func));
1790 switch (func) {
1791 case SymbolicAddress::HandleDebugTrap:
1792 case SymbolicAddress::HandleRequestTierUp:
1793 case SymbolicAddress::HandleThrow:
1794 case SymbolicAddress::HandleTrap:
1795 case SymbolicAddress::CallImport_General:
1796 case SymbolicAddress::CoerceInPlace_ToInt32:
1797 case SymbolicAddress::CoerceInPlace_ToNumber:
1798 case SymbolicAddress::CoerceInPlace_ToBigInt:
1799 case SymbolicAddress::BoxValue_Anyref:
1800 MOZ_ASSERT(!NeedsBuiltinThunk(func),
1801 "not in sync with NeedsBuiltinThunk");
1802 break;
1803 case SymbolicAddress::ToInt32:
1804 return "call to asm.js native ToInt32 coercion (in wasm)";
1805 case SymbolicAddress::DivI64:
1806 return "call to native i64.div_s (in wasm)";
1807 case SymbolicAddress::UDivI64:
1808 return "call to native i64.div_u (in wasm)";
1809 case SymbolicAddress::ModI64:
1810 return "call to native i64.rem_s (in wasm)";
1811 case SymbolicAddress::UModI64:
1812 return "call to native i64.rem_u (in wasm)";
1813 case SymbolicAddress::TruncateDoubleToUint64:
1814 return "call to native i64.trunc_f64_u (in wasm)";
1815 case SymbolicAddress::TruncateDoubleToInt64:
1816 return "call to native i64.trunc_f64_s (in wasm)";
1817 case SymbolicAddress::SaturatingTruncateDoubleToUint64:
1818 return "call to native i64.trunc_sat_f64_u (in wasm)";
1819 case SymbolicAddress::SaturatingTruncateDoubleToInt64:
1820 return "call to native i64.trunc_sat_f64_s (in wasm)";
1821 case SymbolicAddress::Uint64ToDouble:
1822 return "call to native f64.convert_i64_u (in wasm)";
1823 case SymbolicAddress::Uint64ToFloat32:
1824 return "call to native f32.convert_i64_u (in wasm)";
1825 case SymbolicAddress::Int64ToDouble:
1826 return "call to native f64.convert_i64_s (in wasm)";
1827 case SymbolicAddress::Int64ToFloat32:
1828 return "call to native f32.convert_i64_s (in wasm)";
1829 #if defined(JS_CODEGEN_ARM)
1830 case SymbolicAddress::aeabi_idivmod:
1831 return "call to native i32.div_s (in wasm)";
1832 case SymbolicAddress::aeabi_uidivmod:
1833 return "call to native i32.div_u (in wasm)";
1834 #endif
1835 case SymbolicAddress::AllocateBigInt:
1836 return "call to native newCell<BigInt, NoGC> (in wasm)";
1837 case SymbolicAddress::ModD:
1838 return "call to asm.js native f64 % (mod)";
1839 case SymbolicAddress::SinNativeD:
1840 return "call to asm.js native f64 Math.sin";
1841 case SymbolicAddress::SinFdlibmD:
1842 return "call to asm.js fdlibm f64 Math.sin";
1843 case SymbolicAddress::CosNativeD:
1844 return "call to asm.js native f64 Math.cos";
1845 case SymbolicAddress::CosFdlibmD:
1846 return "call to asm.js fdlibm f64 Math.cos";
1847 case SymbolicAddress::TanNativeD:
1848 return "call to asm.js native f64 Math.tan";
1849 case SymbolicAddress::TanFdlibmD:
1850 return "call to asm.js fdlibm f64 Math.tan";
1851 case SymbolicAddress::ASinD:
1852 return "call to asm.js native f64 Math.asin";
1853 case SymbolicAddress::ACosD:
1854 return "call to asm.js native f64 Math.acos";
1855 case SymbolicAddress::ATanD:
1856 return "call to asm.js native f64 Math.atan";
1857 case SymbolicAddress::CeilD:
1858 return "call to native f64.ceil (in wasm)";
1859 case SymbolicAddress::CeilF:
1860 return "call to native f32.ceil (in wasm)";
1861 case SymbolicAddress::FloorD:
1862 return "call to native f64.floor (in wasm)";
1863 case SymbolicAddress::FloorF:
1864 return "call to native f32.floor (in wasm)";
1865 case SymbolicAddress::TruncD:
1866 return "call to native f64.trunc (in wasm)";
1867 case SymbolicAddress::TruncF:
1868 return "call to native f32.trunc (in wasm)";
1869 case SymbolicAddress::NearbyIntD:
1870 return "call to native f64.nearest (in wasm)";
1871 case SymbolicAddress::NearbyIntF:
1872 return "call to native f32.nearest (in wasm)";
1873 case SymbolicAddress::ExpD:
1874 return "call to asm.js native f64 Math.exp";
1875 case SymbolicAddress::LogD:
1876 return "call to asm.js native f64 Math.log";
1877 case SymbolicAddress::PowD:
1878 return "call to asm.js native f64 Math.pow";
1879 case SymbolicAddress::ATan2D:
1880 return "call to asm.js native f64 Math.atan2";
1881 case SymbolicAddress::ArrayMemMove:
1882 return "call to native array.copy (data)";
1883 case SymbolicAddress::ArrayRefsMove:
1884 return "call to native array.copy (references)";
1885 case SymbolicAddress::MemoryGrowM32:
1886 return "call to native memory.grow m32 (in wasm)";
1887 case SymbolicAddress::MemoryGrowM64:
1888 return "call to native memory.grow m64 (in wasm)";
1889 case SymbolicAddress::MemorySizeM32:
1890 return "call to native memory.size m32 (in wasm)";
1891 case SymbolicAddress::MemorySizeM64:
1892 return "call to native memory.size m64 (in wasm)";
1893 case SymbolicAddress::WaitI32M32:
1894 return "call to native i32.wait m32 (in wasm)";
1895 case SymbolicAddress::WaitI32M64:
1896 return "call to native i32.wait m64 (in wasm)";
1897 case SymbolicAddress::WaitI64M32:
1898 return "call to native i64.wait m32 (in wasm)";
1899 case SymbolicAddress::WaitI64M64:
1900 return "call to native i64.wait m64 (in wasm)";
1901 case SymbolicAddress::WakeM32:
1902 return "call to native wake m32 (in wasm)";
1903 case SymbolicAddress::WakeM64:
1904 return "call to native wake m64 (in wasm)";
1905 case SymbolicAddress::CoerceInPlace_JitEntry:
1906 return "out-of-line coercion for jit entry arguments (in wasm)";
1907 case SymbolicAddress::ReportV128JSCall:
1908 return "jit call to v128 wasm function";
1909 case SymbolicAddress::MemCopyM32:
1910 case SymbolicAddress::MemCopySharedM32:
1911 return "call to native memory.copy m32 function";
1912 case SymbolicAddress::MemCopyM64:
1913 case SymbolicAddress::MemCopySharedM64:
1914 return "call to native memory.copy m64 function";
1915 case SymbolicAddress::MemCopyAny:
1916 return "call to native memory.copy any function";
1917 case SymbolicAddress::DataDrop:
1918 return "call to native data.drop function";
1919 case SymbolicAddress::MemFillM32:
1920 case SymbolicAddress::MemFillSharedM32:
1921 return "call to native memory.fill m32 function";
1922 case SymbolicAddress::MemFillM64:
1923 case SymbolicAddress::MemFillSharedM64:
1924 return "call to native memory.fill m64 function";
1925 case SymbolicAddress::MemInitM32:
1926 return "call to native memory.init m32 function";
1927 case SymbolicAddress::MemInitM64:
1928 return "call to native memory.init m64 function";
1929 case SymbolicAddress::TableCopy:
1930 return "call to native table.copy function";
1931 case SymbolicAddress::TableFill:
1932 return "call to native table.fill function";
1933 case SymbolicAddress::MemDiscardM32:
1934 case SymbolicAddress::MemDiscardSharedM32:
1935 return "call to native memory.discard m32 function";
1936 case SymbolicAddress::MemDiscardM64:
1937 case SymbolicAddress::MemDiscardSharedM64:
1938 return "call to native memory.discard m64 function";
1939 case SymbolicAddress::ElemDrop:
1940 return "call to native elem.drop function";
1941 case SymbolicAddress::TableGet:
1942 return "call to native table.get function";
1943 case SymbolicAddress::TableGrow:
1944 return "call to native table.grow function";
1945 case SymbolicAddress::TableInit:
1946 return "call to native table.init function";
1947 case SymbolicAddress::TableSet:
1948 return "call to native table.set function";
1949 case SymbolicAddress::TableSize:
1950 return "call to native table.size function";
1951 case SymbolicAddress::RefFunc:
1952 return "call to native ref.func function";
1953 case SymbolicAddress::PostBarrierEdge:
1954 case SymbolicAddress::PostBarrierEdgePrecise:
1955 case SymbolicAddress::PostBarrierWholeCell:
1956 return "call to native GC postbarrier (in wasm)";
1957 case SymbolicAddress::ExceptionNew:
1958 return "call to native exception new (in wasm)";
1959 case SymbolicAddress::ThrowException:
1960 return "call to native throw exception (in wasm)";
1961 case SymbolicAddress::StructNewIL_true:
1962 case SymbolicAddress::StructNewIL_false:
1963 case SymbolicAddress::StructNewOOL_true:
1964 case SymbolicAddress::StructNewOOL_false:
1965 return "call to native struct.new (in wasm)";
1966 case SymbolicAddress::ArrayNew_true:
1967 case SymbolicAddress::ArrayNew_false:
1968 return "call to native array.new (in wasm)";
1969 case SymbolicAddress::ArrayNewData:
1970 return "call to native array.new_data function";
1971 case SymbolicAddress::ArrayNewElem:
1972 return "call to native array.new_elem function";
1973 case SymbolicAddress::ArrayInitData:
1974 return "call to native array.init_data function";
1975 case SymbolicAddress::ArrayInitElem:
1976 return "call to native array.init_elem function";
1977 case SymbolicAddress::ArrayCopy:
1978 return "call to native array.copy function";
1979 case SymbolicAddress::SlotsToAllocKindBytesTable:
1980 MOZ_CRASH(
1981 "symbolic address was not code and should not have appeared here");
1982 #define VISIT_BUILTIN_FUNC(op, export, sa_name, ...) \
1983 case SymbolicAddress::sa_name: \
1984 return "call to native " #op " builtin (in wasm)";
1985 FOR_EACH_BUILTIN_MODULE_FUNC(VISIT_BUILTIN_FUNC)
1986 #undef VISIT_BUILTIN_FUNC
1987 #ifdef ENABLE_WASM_JSPI
1988 case SymbolicAddress::UpdateSuspenderState:
1989 return "call to native update suspender state util";
1990 #endif
1991 #ifdef WASM_CODEGEN_DEBUG
1992 case SymbolicAddress::PrintI32:
1993 case SymbolicAddress::PrintPtr:
1994 case SymbolicAddress::PrintF32:
1995 case SymbolicAddress::PrintF64:
1996 case SymbolicAddress::PrintText:
1997 #endif
1998 case SymbolicAddress::Limit:
1999 break;
2000 }
2001 return "?";
2002 }
2003
2004 const char* ProfilingFrameIterator::label() const {
2005 MOZ_ASSERT(!done());
2006
2007 // Use the same string for both time inside and under so that the two
2008 // entries will be coalesced by the profiler.
2009 // Must be kept in sync with /tools/profiler/tests/test_asm.js
2010 static const char importJitDescription[] = "fast exit trampoline (in wasm)";
2011 static const char importInterpDescription[] =
2012 "slow exit trampoline (in wasm)";
2013 static const char builtinNativeDescription[] =
2014 "fast exit trampoline to native (in wasm)";
2015 static const char trapDescription[] = "trap handling (in wasm)";
2016 static const char debugStubDescription[] = "debug trap handling (in wasm)";
2017 static const char requestTierUpDescription[] = "tier-up request (in wasm)";
2018 static const char updateCallRefMetricsDescription[] =
2019 "update call_ref metrics (in wasm)";
2020
2021 if (!exitReason_.isFixed()) {
2022 return ThunkedNativeToDescription(exitReason_.symbolic());
2023 }
2024
2025 switch (exitReason_.fixed()) {
2026 case ExitReason::Fixed::None:
2027 break;
2028 case ExitReason::Fixed::ImportJit:
2029 return importJitDescription;
2030 case ExitReason::Fixed::ImportInterp:
2031 return importInterpDescription;
2032 case ExitReason::Fixed::BuiltinNative:
2033 return builtinNativeDescription;
2034 case ExitReason::Fixed::Trap:
2035 return trapDescription;
2036 case ExitReason::Fixed::DebugStub:
2037 return debugStubDescription;
2038 case ExitReason::Fixed::RequestTierUp:
2039 return requestTierUpDescription;
2040 }
2041
2042 switch (codeRange_->kind()) {
2043 case CodeRange::Function:
2044 return code_->profilingLabel(codeRange_->funcIndex());
2045 case CodeRange::InterpEntry:
2046 return "slow entry trampoline (in wasm)";
2047 case CodeRange::JitEntry:
2048 return "fast entry trampoline (in wasm)";
2049 case CodeRange::ImportJitExit:
2050 return importJitDescription;
2051 case CodeRange::BuiltinThunk:
2052 return builtinNativeDescription;
2053 case CodeRange::ImportInterpExit:
2054 return importInterpDescription;
2055 case CodeRange::TrapExit:
2056 return trapDescription;
2057 case CodeRange::DebugStub:
2058 return debugStubDescription;
2059 case CodeRange::RequestTierUpStub:
2060 return requestTierUpDescription;
2061 case CodeRange::UpdateCallRefMetricsStub:
2062 return updateCallRefMetricsDescription;
2063 case CodeRange::FarJumpIsland:
2064 return "interstitial (in wasm)";
2065 case CodeRange::Throw:
2066 MOZ_CRASH("does not have a frame");
2067 }
2068
2069 MOZ_CRASH("bad code range kind");
2070 }
2071
2072 ProfilingFrameIterator::Category ProfilingFrameIterator::category() const {
2073 MOZ_ASSERT(!done());
2074 return category_;
2075 }