Debian Codegraph @

js/src/wasm/WasmCode.h

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 2016 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 #ifndef wasm_code_h
20 #define wasm_code_h
21
22 #include "mozilla/Assertions.h"
23 #include "mozilla/Atomics.h"
24 #include "mozilla/Attributes.h"
25 #include "mozilla/DebugOnly.h"
26 #include "mozilla/EnumeratedArray.h"
27 #include "mozilla/Maybe.h"
28 #include "mozilla/MemoryReporting.h"
29 #include "mozilla/PodOperations.h"
30 #include "mozilla/RefPtr.h"
31 #include "mozilla/ScopeExit.h"
32 #include "mozilla/Span.h"
33 #include "mozilla/UniquePtr.h"
34
35 #include <stddef.h>
36 #include <stdint.h>
37 #include <string.h>
38 #include <utility>
39
40 #include "jstypes.h"
41
42 #include "gc/Memory.h"
43 #include "jit/ProcessExecutableMemory.h"
44 #include "js/AllocPolicy.h"
45 #include "js/UniquePtr.h"
46 #include "js/Utility.h"
47 #include "js/Vector.h"
48 #include "threading/ExclusiveData.h"
49 #include "util/Memory.h"
50 #include "vm/MutexIDs.h"
51 #include "wasm/AsmJS.h" // CodeMetadataForAsmJS::SeenSet
52 #include "wasm/WasmBuiltinModule.h"
53 #include "wasm/WasmBuiltins.h"
54 #include "wasm/WasmCodegenConstants.h"
55 #include "wasm/WasmCodegenTypes.h"
56 #include "wasm/WasmCompileArgs.h"
57 #include "wasm/WasmConstants.h"
58 #include "wasm/WasmExprType.h"
59 #include "wasm/WasmGC.h"
60 #include "wasm/WasmLog.h"
61 #include "wasm/WasmMetadata.h"
62 #include "wasm/WasmModuleTypes.h"
63 #include "wasm/WasmSerialize.h"
64 #include "wasm/WasmShareable.h"
65 #include "wasm/WasmTypeDecls.h"
66 #include "wasm/WasmTypeDef.h"
67 #include "wasm/WasmValType.h"
68
69 struct JS_PUBLIC_API JSContext;
70 class JSFunction;
71
72 namespace js {
73
74 namespace jit {
75 class MacroAssembler;
76 };
77
78 namespace wasm {
79
80 // LinkData contains all the metadata necessary to patch all the locations
81 // that depend on the absolute address of a CodeSegment. This happens in a
82 // "linking" step after compilation and after the module's code is serialized.
83 // The LinkData is serialized along with the Module but does not (normally, see
84 // Module::debugLinkData_ comment) persist after (de)serialization, which
85 // distinguishes it from Metadata, which is stored in the Code object.
86
87 struct LinkDataCacheablePod {
88 uint32_t trapOffset = 0;
89
90 WASM_CHECK_CACHEABLE_POD(trapOffset);
91
92 LinkDataCacheablePod() = default;
93 };
94
95 WASM_DECLARE_CACHEABLE_POD(LinkDataCacheablePod);
96
97 WASM_CHECK_CACHEABLE_POD_PADDING(LinkDataCacheablePod)
98
99 struct LinkData : LinkDataCacheablePod {
100 LinkData() = default;
101
102 LinkDataCacheablePod& pod() { return *this; }
103 const LinkDataCacheablePod& pod() const { return *this; }
104
105 struct InternalLink {
106 uint32_t patchAtOffset;
107 uint32_t targetOffset;
108 #ifdef JS_CODELABEL_LINKMODE
109 uint32_t mode;
110 #endif
111
112 WASM_CHECK_CACHEABLE_POD(patchAtOffset, targetOffset);
113 #ifdef JS_CODELABEL_LINKMODE
114 WASM_CHECK_CACHEABLE_POD(mode)
115 #endif
116 };
117 using InternalLinkVector = Vector<InternalLink, 0, SystemAllocPolicy>;
118
119 struct SymbolicLinkArray
120 : mozilla::EnumeratedArray<SymbolicAddress, Uint32Vector,
121 size_t(SymbolicAddress::Limit)> {
122 bool isEmpty() const {
123 for (const Uint32Vector& symbolicLinks : *this) {
124 if (symbolicLinks.length() != 0) {
125 return false;
126 }
127 }
128 return true;
129 }
130 void clear() {
131 for (SymbolicAddress symbolicAddress :
132 mozilla::MakeEnumeratedRange(SymbolicAddress::Limit)) {
133 (*this)[symbolicAddress].clear();
134 }
135 }
136
137 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
138 };
139
140 InternalLinkVector internalLinks;
141 CallFarJumpVector callFarJumps;
142 SymbolicLinkArray symbolicLinks;
143
144 bool isEmpty() const {
145 return internalLinks.length() == 0 && callFarJumps.length() == 0 &&
146 symbolicLinks.isEmpty();
147 }
148 void clear() {
149 internalLinks.clear();
150 callFarJumps.clear();
151 symbolicLinks.clear();
152 }
153
154 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const;
155 };
156
157 WASM_DECLARE_CACHEABLE_POD(LinkData::InternalLink);
158
159 using UniqueLinkData = UniquePtr<LinkData>;
160 using UniqueLinkDataVector = Vector<UniqueLinkData, 0, SystemAllocPolicy>;
161
162 // Executable code must be deallocated specially.
163
164 struct FreeCode {
165 uint32_t codeLength;
166 FreeCode() : codeLength(0) {}
167 explicit FreeCode(uint32_t codeLength) : codeLength(codeLength) {}
168 void operator()(uint8_t* codeBytes);
169 };
170
171 using UniqueCodeBytes = UniquePtr<uint8_t, FreeCode>;
172
173 class Code;
174 class CodeBlock;
175
176 using UniqueCodeBlock = UniquePtr<CodeBlock>;
177 using UniqueConstCodeBlock = UniquePtr<const CodeBlock>;
178 using UniqueConstCodeBlockVector =
179 Vector<UniqueConstCodeBlock, 0, SystemAllocPolicy>;
180 using RawCodeBlockVector = Vector<const CodeBlock*, 0, SystemAllocPolicy>;
181
182 enum class CodeBlockKind {
183 SharedStubs,
184 BaselineTier,
185 OptimizedTier,
186 LazyStubs
187 };
188
189 // A source of machine code for creating an executable code segment.
190 class CodeSource {
191 // The macro assembler to use as the source. If this is set then there is
192 // no `bytes_` pointer.
193 jit::MacroAssembler* masm_ = nullptr;
194 // A raw pointer to the unlinked machine code bytes. If this is set then
195 // there is no `masm_` pointer.
196 const uint8_t* bytes_ = nullptr;
197
198 // The length in bytes for either case. This is always valid and set to
199 // masm.bytesNeeded() if masm_ is present.
200 uint32_t length_ = 0;
201
202 // The link data to use, if any. This is always present if we are linking
203 // from raw bytes. Otherwise it may or may not be present when we are linking
204 // masm. If it is not present for masm we will fall back to basic linking of
205 // code labels and debug symbolic accesses.
206 const LinkData* linkData_;
207
208 // The code object to use, if any, for linking. This is optionally present
209 // in either case. This will not be present if we are doing basic linking
210 // without a link data.
211 const Code* code_;
212
213 public:
214 // Get the machine code from a macro assembler, optional link data, and
215 // optional code object.
216 CodeSource(jit::MacroAssembler& masm, const LinkData* linkData,
217 const Code* code);
218
219 // Get the machine code from a raw bytes range, link data, and optional code
220 // object.
221 CodeSource(const uint8_t* bytes, uint32_t length, const LinkData& linkData,
222 const Code* code);
223
224 // The length of machine code in bytes.
225 uint32_t lengthBytes() const { return length_; }
226
227 // Copy and link the machine code into `codeStart`.
228 bool copyAndLink(jit::AutoMarkJitCodeWritableForThread& writable,
229 uint8_t* codeStart) const;
230 };
231
232 // CodeSegment is a fixed-size chunk of executable memory that we can
233 // bump-allocate smaller allocations from.
234 class CodeSegment : public ShareableBase<CodeSegment> {
235 private:
236 const UniqueCodeBytes bytes_;
237 uint32_t lengthBytes_;
238 const uint32_t capacityBytes_;
239 const Code* code_;
240
241 // Create a new, empty code segment with a given capacity. The capacity must
242 // have granularity of ExecutableCodePageSize (64KB).
243 static RefPtr<CodeSegment> create(
244 mozilla::Maybe<jit::AutoMarkJitCodeWritableForThread>& writable,
245 size_t capacityBytes, bool allowLastDitchGC = true);
246
247 // Returns the alignment that all allocations within a code segment must be.
248 //
249 // If we are write-protecting code, then we must start every new allocation
250 // on a new system page, otherwise we can re-use system pages for new
251 // allocations.
252 static size_t AllocationAlignment();
253 // Align `bytes` to be at least the allocation alignment. See above.
254 static size_t AlignAllocationBytes(uintptr_t bytes);
255 // Returns whether `bytes` is aligned to the allocation alignment.
256 static bool IsAligned(uintptr_t bytes);
257
258 // Checks if this code segment has enough room for an allocation of bytes.
259 // The bytes must be aligned to allocation alignment.
260 bool hasSpace(size_t bytes) const;
261
262 // Claims space in this code segment for an allocation of bytes. The bytes
263 // must be aligned to allocation alignment.
264 void claimSpace(size_t bytes, uint8_t** claimedBase);
265
266 public:
267 CodeSegment(UniqueCodeBytes bytes, uint32_t lengthBytes,
268 uint32_t capacityBytes)
269 : bytes_(std::move(bytes)),
270 lengthBytes_(lengthBytes),
271 capacityBytes_(capacityBytes),
272 code_(nullptr) {}
273
274 // Copies, links, and makes the machine code executable from the given code
275 // source. Returns the code segment the code was allocated into. An optional
276 // pool of code segments may be provided to allocate from.
277 //
278 // There are two important ranges created, an 'allocation' range and a 'code
279 // range'.
280 //
281 // The allocation range is a superset of the code range. The allocation start
282 // offset will be aligned to `AllocationAlignment` which is either the system
283 // page size or just executable code alignment.
284 //
285 // The code range will be within the allocation range and may have some
286 // padding inserted before the start of the allocation. The code start offset
287 // will always be aligned to the executable code alignment.
288 //
289 // Random padding is added before the code range when we are aligning to the
290 // system page size, the start addressess of all the code memories will not
291 // conflict in associative icaches.
292 //
293 // Here's a picture that illustrates the resulting structure of allocations:
294 //
295 // This is an example for a machine with a 4KB page size, for a codeLength
296 // which requires more than one page but less than two, in a segment where
297 // the first page is already allocated.
298 //
299 // Note: if !JitOptions.writeProtectCode, then allocationStart and
300 // allocationLength will be a multiple of jit::CodeAlignment, not the
301 // system page size.
302 //
303 // segment->base() (aligned at 4K = hardware page size)
304 // :
305 // : +4k +8k +12k
306 // : : : :
307 // +-----------------------+ +---------------------------------+ :
308 // | IN USE | | CODE CODE | :
309 // +-----------------------+----------+---------------------------------+---+
310 // . : : :
311 // : : : allocationLength :
312 // : :<------------------------------------------>:
313 // . : : :
314 // : : padding : codeLength :
315 // :<--------------------->:<-------->:<------------------------------->:
316 // : : :
317 // : : :
318 // :<-------------------------------->:
319 // : :
320 // : codeStart
321 // :
322 // allocationStart
323 static RefPtr<CodeSegment> allocate(
324 const CodeSource& codeSource,
325 Vector<RefPtr<CodeSegment>, 0, SystemAllocPolicy>* segmentPool,
326 bool allowLastDitchGC, uint8_t** codeStartOut,
327 uint32_t* allocationLengthOut);
328
329 void setCode(const Code& code) { code_ = &code; }
330
331 uint8_t* base() const { return bytes_.get(); }
332 uint32_t lengthBytes() const {
333 MOZ_ASSERT(lengthBytes_ != UINT32_MAX);
334 return lengthBytes_;
335 }
336 uint32_t capacityBytes() const {
337 MOZ_ASSERT(capacityBytes_ != UINT32_MAX);
338 return capacityBytes_;
339 }
340
341 const Code& code() const { return *code_; }
342
343 void addSizeOfMisc(mozilla::MallocSizeOf mallocSizeOf, size_t* code,
344 size_t* data) const;
345 WASM_DECLARE_FRIEND_SERIALIZE(CodeSegment);
346 };
347
348 using SharedCodeSegment = RefPtr<CodeSegment>;
349 using SharedCodeSegmentVector = Vector<SharedCodeSegment, 0, SystemAllocPolicy>;
350
351 extern UniqueCodeBytes AllocateCodeBytes(
352 mozilla::Maybe<jit::AutoMarkJitCodeWritableForThread>& writable,
353 uint32_t codeLength, bool allowLastDitchGC);
354 extern bool StaticallyLink(jit::AutoMarkJitCodeWritableForThread& writable,
355 uint8_t* base, const LinkData& linkData,
356 const Code* maybeCode);
357 extern void StaticallyUnlink(uint8_t* base, const LinkData& linkData);
358
359 enum class TierUpState : uint32_t {
360 NotRequested,
361 Requested,
362 Finished,
363 };
364
365 struct FuncState {
366 mozilla::Atomic<const CodeBlock*> bestTier;
367 mozilla::Atomic<TierUpState> tierUpState;
368 };
369 using FuncStatesPointer = mozilla::UniquePtr<FuncState[], JS::FreePolicy>;
370
371 // LazyFuncExport helps to efficiently lookup a CodeRange from a given function
372 // index. It is inserted in a vector sorted by function index, to perform
373 // binary search on it later.
374
375 struct LazyFuncExport {
376 size_t funcIndex;
377 size_t lazyStubBlockIndex;
378 size_t funcCodeRangeIndex;
379 // Used to make sure we only upgrade a lazy stub from baseline to ion.
380 mozilla::DebugOnly<CodeBlockKind> funcKind;
381
382 LazyFuncExport(size_t funcIndex, size_t lazyStubBlockIndex,
383 size_t funcCodeRangeIndex, CodeBlockKind funcKind)
384 : funcIndex(funcIndex),
385 lazyStubBlockIndex(lazyStubBlockIndex),
386 funcCodeRangeIndex(funcCodeRangeIndex),
387 funcKind(funcKind) {}
388 };
389
390 using LazyFuncExportVector = Vector<LazyFuncExport, 0, SystemAllocPolicy>;
391
392 // A FuncExport represents a single function definition inside a wasm Module
393 // that has been exported one or more times. A FuncExport represents an
394 // internal entry point that can be called via function definition index by
395 // Instance::callExport(). To allow O(log(n)) lookup of a FuncExport by
396 // function definition index, the FuncExportVector is stored sorted by
397 // function definition index.
398
399 class FuncExport {
400 uint32_t funcIndex_;
401 uint32_t eagerInterpEntryOffset_; // Machine code offset
402
403 WASM_CHECK_CACHEABLE_POD(funcIndex_, eagerInterpEntryOffset_);
404
405 // Sentinel value that this FuncExport will get eager stubs
406 static constexpr uint32_t PENDING_EAGER_STUBS = UINT32_MAX - 1;
407
408 // Sentinel value that this FuncExport will not eager stubs
409 static constexpr uint32_t NO_EAGER_STUBS = UINT32_MAX;
410
411 public:
412 FuncExport() = default;
413 explicit FuncExport(uint32_t funcIndex, bool hasEagerStubs) {
414 funcIndex_ = funcIndex;
415 eagerInterpEntryOffset_ =
416 hasEagerStubs ? PENDING_EAGER_STUBS : NO_EAGER_STUBS;
417 }
418 void initEagerInterpEntryOffset(uint32_t entryOffset) {
419 MOZ_ASSERT(eagerInterpEntryOffset_ == PENDING_EAGER_STUBS);
420 MOZ_ASSERT(entryOffset != PENDING_EAGER_STUBS &&
421 entryOffset != NO_EAGER_STUBS);
422 MOZ_ASSERT(hasEagerStubs());
423 eagerInterpEntryOffset_ = entryOffset;
424 }
425
426 bool hasEagerStubs() const {
427 return eagerInterpEntryOffset_ != NO_EAGER_STUBS;
428 }
429 uint32_t funcIndex() const { return funcIndex_; }
430 uint32_t eagerInterpEntryOffset() const {
431 MOZ_ASSERT(eagerInterpEntryOffset_ != PENDING_EAGER_STUBS);
432 MOZ_ASSERT(hasEagerStubs());
433 return eagerInterpEntryOffset_;
434 }
435 void offsetBy(uint32_t delta) {
436 if (hasEagerStubs()) {
437 eagerInterpEntryOffset_ += delta;
438 }
439 }
440 };
441
442 WASM_DECLARE_CACHEABLE_POD(FuncExport);
443
444 using FuncExportVector = Vector<FuncExport, 0, SystemAllocPolicy>;
445
446 // A FuncImport contains the runtime metadata needed to implement a call to an
447 // imported function. Each function import has two call stubs: an optimized path
448 // into JIT code and a slow path into the generic C++ js::Invoke and these
449 // offsets of these stubs are stored so that function-import callsites can be
450 // dynamically patched at runtime.
451
452 class FuncImport {
453 private:
454 uint32_t interpExitCodeOffset_; // Machine code offset
455 uint32_t jitExitCodeOffset_; // Machine code offset
456
457 WASM_CHECK_CACHEABLE_POD(interpExitCodeOffset_, jitExitCodeOffset_);
458
459 public:
460 FuncImport() : interpExitCodeOffset_(0), jitExitCodeOffset_(0) {}
461
462 void initInterpExitOffset(uint32_t off) {
463 MOZ_ASSERT(!interpExitCodeOffset_);
464 interpExitCodeOffset_ = off;
465 }
466 void initJitExitOffset(uint32_t off) {
467 MOZ_ASSERT(!jitExitCodeOffset_);
468 jitExitCodeOffset_ = off;
469 }
470
471 uint32_t interpExitCodeOffset() const { return interpExitCodeOffset_; }
472 uint32_t jitExitCodeOffset() const { return jitExitCodeOffset_; }
473 };
474
475 WASM_DECLARE_CACHEABLE_POD(FuncImport)
476
477 using FuncImportVector = Vector<FuncImport, 0, SystemAllocPolicy>;
478
479 static const uint32_t BAD_CODE_RANGE = UINT32_MAX;
480
481 class FuncToCodeRangeMap {
482 uint32_t startFuncIndex_ = 0;
483 Uint32Vector funcToCodeRange_;
484
485 bool denseHasFuncIndex(uint32_t funcIndex) const {
486 return funcIndex >= startFuncIndex_ &&
487 funcIndex - startFuncIndex_ < funcToCodeRange_.length();
488 }
489
490 FuncToCodeRangeMap(uint32_t startFuncIndex, Uint32Vector&& funcToCodeRange)
491 : startFuncIndex_(startFuncIndex),
492 funcToCodeRange_(std::move(funcToCodeRange)) {}
493
494 public:
495 [[nodiscard]] static bool createDense(uint32_t startFuncIndex,
496 uint32_t numFuncs,
497 FuncToCodeRangeMap* result) {
498 Uint32Vector funcToCodeRange;
499 if (!funcToCodeRange.appendN(BAD_CODE_RANGE, numFuncs)) {
500 return false;
501 }
502 *result = FuncToCodeRangeMap(startFuncIndex, std::move(funcToCodeRange));
503 return true;
504 }
505
506 FuncToCodeRangeMap() = default;
507 FuncToCodeRangeMap(FuncToCodeRangeMap&& rhs) = default;
508 FuncToCodeRangeMap& operator=(FuncToCodeRangeMap&& rhs) = default;
509 FuncToCodeRangeMap(const FuncToCodeRangeMap& rhs) = delete;
510 FuncToCodeRangeMap& operator=(const FuncToCodeRangeMap& rhs) = delete;
511
512 uint32_t lookup(uint32_t funcIndex) const {
513 if (!denseHasFuncIndex(funcIndex)) {
514 return BAD_CODE_RANGE;
515 }
516 return funcToCodeRange_[funcIndex - startFuncIndex_];
517 }
518
519 uint32_t operator[](uint32_t funcIndex) const { return lookup(funcIndex); }
520
521 [[nodiscard]] bool insert(uint32_t funcIndex, uint32_t codeRangeIndex) {
522 if (!denseHasFuncIndex(funcIndex)) {
523 return false;
524 }
525 funcToCodeRange_[funcIndex - startFuncIndex_] = codeRangeIndex;
526 return true;
527 }
528 void insertInfallible(uint32_t funcIndex, uint32_t codeRangeIndex) {
529 bool result = insert(funcIndex, codeRangeIndex);
530 MOZ_RELEASE_ASSERT(result);
531 }
532
533 void shrinkStorageToFit() { funcToCodeRange_.shrinkStorageToFit(); }
534
535 void assertAllInitialized() {
536 #ifdef DEBUG
537 for (uint32_t codeRangeIndex : funcToCodeRange_) {
538 MOZ_ASSERT(codeRangeIndex != BAD_CODE_RANGE);
539 }
540 #endif
541 }
542
543 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
544 return funcToCodeRange_.sizeOfExcludingThis(mallocSizeOf);
545 }
546
547 size_t numEntries() const { return funcToCodeRange_.length(); }
548
549 WASM_DECLARE_FRIEND_SERIALIZE(FuncToCodeRangeMap);
550 };
551
552 // CodeBlock contains all the data related to a given compilation tier. It is
553 // built during module generation and then immutably stored in a Code.
554 //
555 // Code contains a map from PC to containing code block. The map is thread-safe
556 // to support lookups from multiple threads (see ThreadSafeCodeBlockMap). This
557 // is safe because code blocks are immutable after creation, so there won't
558 // be any concurrent modification during a metadata lookup.
559
560 class CodeBlock {
561 public:
562 // Weak reference to the code that owns us, not serialized.
563 const Code* code;
564 // The index we are held inside our containing Code::data::blocks_ vector.
565 size_t codeBlockIndex;
566
567 // The following information is all serialized
568 // Which kind of code is being stored in this block. Most consumers don't
569 // care about this.
570 const CodeBlockKind kind;
571
572 // The code segment our JIT code is within.
573 SharedCodeSegment segment;
574
575 // Pointer to the beginning of the CodeBlock.
576 uint8_t* codeBase;
577 size_t codeLength;
578
579 // Metadata about the code we have contributed to the segment.
580 //
581 // All offsets are relative to `codeBase` not the segment base.
582 FuncToCodeRangeMap funcToCodeRange;
583 CodeRangeVector codeRanges;
584 InliningContext inliningContext;
585 CallSites callSites;
586 TrapSites trapSites;
587 FuncExportVector funcExports;
588 StackMaps stackMaps;
589 TryNoteVector tryNotes;
590 CodeRangeUnwindInfoVector codeRangeUnwindInfos;
591
592 // Track whether we are registered in the process map of code blocks.
593 bool unregisterOnDestroy_;
594
595 static constexpr CodeBlockKind kindFromTier(Tier tier) {
596 if (tier == Tier::Optimized) {
597 return CodeBlockKind::OptimizedTier;
598 }
599 MOZ_ASSERT(tier == Tier::Baseline);
600 return CodeBlockKind::BaselineTier;
601 }
602
603 explicit CodeBlock(CodeBlockKind kind)
604 : code(nullptr),
605 codeBlockIndex((size_t)-1),
606 kind(kind),
607 codeBase(nullptr),
608 codeLength(0),
609 unregisterOnDestroy_(false) {}
610 ~CodeBlock();
611
612 bool initialized() const {
613 if (code) {
614 // Initialize should have given us an index too.
615 MOZ_ASSERT(codeBlockIndex != (size_t)-1);
616 return true;
617 }
618 return false;
619 }
620
621 bool initialize(const Code& code, size_t codeBlockIndex);
622 void sendToProfiler(const CodeMetadata& codeMeta,
623 const CodeTailMetadata& codeTailMeta,
624 const CodeMetadataForAsmJS* codeMetaForAsmJS,
625 FuncIonPerfSpewerSpan ionSpewers,
626 FuncBaselinePerfSpewerSpan baselineSpewers) const;
627
628 // Gets the tier for this code block. Only valid for non-lazy stub code.
629 Tier tier() const {
630 switch (kind) {
631 case CodeBlockKind::BaselineTier:
632 return Tier::Baseline;
633 case CodeBlockKind::OptimizedTier:
634 return Tier::Optimized;
635 default:
636 MOZ_CRASH();
637 }
638 }
639
640 // Returns whether this code block should be considered for serialization.
641 bool isSerializable() const {
642 return kind == CodeBlockKind::SharedStubs ||
643 kind == CodeBlockKind::OptimizedTier;
644 }
645
646 uint8_t* base() const { return codeBase; }
647 uint32_t length() const { return codeLength; }
648 bool containsCodePC(const void* pc) const {
649 return pc >= base() && pc < (base() + length());
650 }
651
652 const CodeRange& codeRange(uint32_t funcIndex) const {
653 return codeRanges[funcToCodeRange[funcIndex]];
654 }
655 const CodeRange& codeRange(const FuncExport& funcExport) const {
656 return codeRanges[funcToCodeRange[funcExport.funcIndex()]];
657 }
658
659 const CodeRange* lookupRange(const void* pc) const;
660 bool lookupCallSite(void* pc, CallSite* callSite) const;
661 const StackMap* lookupStackMap(uint8_t* pc) const;
662 const TryNote* lookupTryNote(const void* pc) const;
663 bool lookupTrap(void* pc, Trap* kindOut, TrapSite* trapOut) const;
664 const CodeRangeUnwindInfo* lookupUnwindInfo(void* pc) const;
665 FuncExport& lookupFuncExport(uint32_t funcIndex,
666 size_t* funcExportIndex = nullptr);
667 const FuncExport& lookupFuncExport(uint32_t funcIndex,
668 size_t* funcExportIndex = nullptr) const;
669
670 void disassemble(JSContext* cx, int kindSelection,
671 PrintCallback printString) const;
672
673 void addSizeOfMisc(mozilla::MallocSizeOf mallocSizeOf, size_t* code,
674 size_t* data) const;
675
676 WASM_DECLARE_FRIEND_SERIALIZE_ARGS(CodeBlock, const wasm::LinkData& data);
677 };
678
679 // Because of profiling, the thread running wasm might need to know to which
680 // CodeBlock the current PC belongs, during a call to lookup(). A lookup
681 // is a read-only operation, and we don't want to take a lock then
682 // (otherwise, we could have a deadlock situation if an async lookup
683 // happened on a given thread that was holding mutatorsMutex_ while getting
684 // sampled). Since the writer could be modifying the data that is getting
685 // looked up, the writer functions use spin-locks to know if there are any
686 // observers (i.e. calls to lookup()) of the atomic data.
687
688 class ThreadSafeCodeBlockMap {
689 // Since writes (insertions or removals) can happen on any background
690 // thread at the same time, we need a lock here.
691
692 Mutex mutatorsMutex_ MOZ_UNANNOTATED;
693
694 RawCodeBlockVector segments1_;
695 RawCodeBlockVector segments2_;
696
697 // Except during swapAndWait(), there are no lookup() observers of the
698 // vector pointed to by mutableCodeBlocks_
699
700 RawCodeBlockVector* mutableCodeBlocks_;
701 mozilla::Atomic<const RawCodeBlockVector*> readonlyCodeBlocks_;
702 mozilla::Atomic<size_t> numActiveLookups_;
703
704 struct CodeBlockPC {
705 const void* pc;
706 explicit CodeBlockPC(const void* pc) : pc(pc) {}
707 int operator()(const CodeBlock* cb) const {
708 if (cb->containsCodePC(pc)) {
709 return 0;
710 }
711 if (pc < cb->base()) {
712 return -1;
713 }
714 return 1;
715 }
716 };
717
718 void swapAndWait() {
719 // Both vectors are consistent for lookup at this point although their
720 // contents are different: there is no way for the looked up PC to be
721 // in the code segment that is getting registered, because the code
722 // segment is not even fully created yet.
723
724 // If a lookup happens before this instruction, then the
725 // soon-to-become-former read-only pointer is used during the lookup,
726 // which is valid.
727
728 mutableCodeBlocks_ = const_cast<RawCodeBlockVector*>(
729 readonlyCodeBlocks_.exchange(mutableCodeBlocks_));
730
731 // If a lookup happens after this instruction, then the updated vector
732 // is used, which is valid:
733 // - in case of insertion, it means the new vector contains more data,
734 // but it's fine since the code segment is getting registered and thus
735 // isn't even fully created yet, so the code can't be running.
736 // - in case of removal, it means the new vector contains one less
737 // entry, but it's fine since unregistering means the code segment
738 // isn't used by any live instance anymore, thus PC can't be in the
739 // to-be-removed code segment's range.
740
741 // A lookup could have happened on any of the two vectors. Wait for
742 // observers to be done using any vector before mutating.
743
744 while (numActiveLookups_ > 0) {
745 }
746 }
747
748 public:
749 ThreadSafeCodeBlockMap()
750 : mutatorsMutex_(mutexid::WasmCodeBlockMap),
751 mutableCodeBlocks_(&segments1_),
752 readonlyCodeBlocks_(&segments2_),
753 numActiveLookups_(0) {}
754
755 ~ThreadSafeCodeBlockMap() {
756 MOZ_RELEASE_ASSERT(numActiveLookups_ == 0);
757 segments1_.clearAndFree();
758 segments2_.clearAndFree();
759 }
760
761 size_t numActiveLookups() const { return numActiveLookups_; }
762
763 bool insert(const CodeBlock* cs) {
764 LockGuard<Mutex> lock(mutatorsMutex_);
765
766 size_t index;
767 MOZ_ALWAYS_FALSE(BinarySearchIf(*mutableCodeBlocks_, 0,
768 mutableCodeBlocks_->length(),
769 CodeBlockPC(cs->base()), &index));
770
771 if (!mutableCodeBlocks_->insert(mutableCodeBlocks_->begin() + index, cs)) {
772 return false;
773 }
774
775 swapAndWait();
776
777 #ifdef DEBUG
778 size_t otherIndex;
779 MOZ_ALWAYS_FALSE(BinarySearchIf(*mutableCodeBlocks_, 0,
780 mutableCodeBlocks_->length(),
781 CodeBlockPC(cs->base()), &otherIndex));
782 MOZ_ASSERT(index == otherIndex);
783 #endif
784
785 // Although we could simply revert the insertion in the read-only
786 // vector, it is simpler to just crash and given that each CodeBlock
787 // consumes multiple pages, it is unlikely this insert() would OOM in
788 // practice
789 AutoEnterOOMUnsafeRegion oom;
790 if (!mutableCodeBlocks_->insert(mutableCodeBlocks_->begin() + index, cs)) {
791 oom.crash("when inserting a CodeBlock in the process-wide map");
792 }
793
794 return true;
795 }
796
797 size_t remove(const CodeBlock* cs) {
798 LockGuard<Mutex> lock(mutatorsMutex_);
799
800 size_t index;
801 MOZ_ALWAYS_TRUE(BinarySearchIf(*mutableCodeBlocks_, 0,
802 mutableCodeBlocks_->length(),
803 CodeBlockPC(cs->base()), &index));
804
805 mutableCodeBlocks_->erase(mutableCodeBlocks_->begin() + index);
806 size_t newCodeBlockCount = mutableCodeBlocks_->length();
807
808 swapAndWait();
809
810 #ifdef DEBUG
811 size_t otherIndex;
812 MOZ_ALWAYS_TRUE(BinarySearchIf(*mutableCodeBlocks_, 0,
813 mutableCodeBlocks_->length(),
814 CodeBlockPC(cs->base()), &otherIndex));
815 MOZ_ASSERT(index == otherIndex);
816 #endif
817
818 mutableCodeBlocks_->erase(mutableCodeBlocks_->begin() + index);
819 return newCodeBlockCount;
820 }
821
822 const CodeBlock* lookup(const void* pc,
823 const CodeRange** codeRange = nullptr) {
824 auto decObserver = mozilla::MakeScopeExit([&] {
825 MOZ_ASSERT(numActiveLookups_ > 0);
826 numActiveLookups_--;
827 });
828 numActiveLookups_++;
829
830 const RawCodeBlockVector* readonly = readonlyCodeBlocks_;
831
832 size_t index;
833 if (!BinarySearchIf(*readonly, 0, readonly->length(), CodeBlockPC(pc),
834 &index)) {
835 if (codeRange) {
836 *codeRange = nullptr;
837 }
838 return nullptr;
839 }
840
841 // It is fine returning a raw CodeBlock*, because we assume we are
842 // looking up a live PC in code which is on the stack, keeping the
843 // CodeBlock alive.
844
845 const CodeBlock* result = (*readonly)[index];
846 if (codeRange) {
847 *codeRange = result->lookupRange(pc);
848 }
849 return result;
850 }
851 };
852
853 // Jump tables that implement function tiering and fast js-to-wasm calls.
854 //
855 // There is one JumpTable object per Code object, holding two jump tables: the
856 // tiering jump table and the jit-entry jump table. The JumpTable is not
857 // serialized with its Code, but is a run-time entity only. At run-time it is
858 // shared across threads with its owning Code (and the Module that owns the
859 // Code). Values in the JumpTable /must/ /always/ be JSContext-agnostic and
860 // Instance-agnostic, because of this sharing.
861 //
862 // Both jump tables have a number of entries equal to the number of functions in
863 // their Module, including imports. In the tiering table, the elements
864 // corresponding to the Module's imported functions are unused; in the jit-entry
865 // table, the elements corresponding to the Module's non-exported functions are
866 // unused. (Functions can be exported explicitly via the exports section or
867 // implicitly via a mention of their indices outside function bodies.) See
868 // comments at JumpTables::init() and WasmInstanceObject::getExportedFunction().
869 // The entries are void*. Unused entries are null.
870 //
871 // The tiering jump table.
872 //
873 // This table holds code pointers that are used by baseline functions to enter
874 // optimized code. See the large comment block in WasmCompile.cpp for
875 // information about how tiering works.
876 //
877 // The jit-entry jump table.
878 //
879 // The jit-entry jump table entry for a function holds a stub that allows Jitted
880 // JS code to call wasm using the JS JIT ABI. See large comment block at
881 // WasmInstanceObject::getExportedFunction() for more about exported functions
882 // and stubs and the lifecycle of the entries in the jit-entry table - there are
883 // complex invariants.
884
885 class JumpTables {
886 using TablePointer = mozilla::UniquePtr<void*[], JS::FreePolicy>;
887
888 CompileMode mode_;
889 TablePointer tiering_;
890 TablePointer jit_;
891 size_t numFuncs_;
892
893 static_assert(
894 JumpTableJitEntryOffset == 0,
895 "Each jit entry in table must have compatible layout with BaseScript and"
896 "SelfHostedLazyScript");
897
898 public:
899 bool initialize(CompileMode mode, const CodeMetadata& codeMeta,
900 const CodeBlock& sharedStubs, const CodeBlock& tier1);
901
902 void setJitEntry(size_t i, void* target) const {
903 // Make sure that write is atomic; see comment in wasm::Module::finishTier2
904 // to that effect.
905 MOZ_ASSERT(i < numFuncs_);
906 __atomic_store_n(&jit_.get()[i], target, __ATOMIC_RELAXED);
907 }
908 void setJitEntryIfNull(size_t i, void* target) const {
909 // Make sure that compare-and-write is atomic; see comment in
910 // wasm::Module::finishTier2 to that effect.
911 MOZ_ASSERT(i < numFuncs_);
912 void* expected = nullptr;
913 (void)__atomic_compare_exchange_n(&jit_.get()[i], &expected, target,
914 /*weak=*/false,
915 /*success_memorder=*/__ATOMIC_RELAXED,
916 /*failure_memorder=*/__ATOMIC_RELAXED);
917 }
918 void** getAddressOfJitEntry(size_t i) const {
919 MOZ_ASSERT(i < numFuncs_);
920 MOZ_ASSERT(jit_.get()[i]);
921 return &jit_.get()[i];
922 }
923 uint32_t funcIndexFromJitEntry(void** target) const {
924 MOZ_ASSERT(target >= &jit_.get()[0]);
925 MOZ_ASSERT(target <= &(jit_.get()[numFuncs_ - 1]));
926 size_t index = (intptr_t*)target - (intptr_t*)&jit_.get()[0];
927 MOZ_ASSERT(index < wasm::MaxFuncs);
928 return (uint32_t)index;
929 }
930
931 void setTieringEntry(size_t i, void* target) const {
932 MOZ_ASSERT(i < numFuncs_);
933 // See comment in wasm::Module::finishTier2.
934 if (mode_ != CompileMode::Once) {
935 tiering_.get()[i] = target;
936 }
937 }
938 void** tiering() const { return tiering_.get(); }
939
940 size_t sizeOfMiscExcludingThis() const {
941 // 2 words per function for the jit entry table, plus maybe 1 per
942 // function if we're tiering.
943 return sizeof(void*) * (2 + (tiering_ ? 1 : 0)) * numFuncs_;
944 }
945 };
946
947 // Code objects own executable code and the metadata that describe it. A single
948 // Code object is normally shared between a module and all its instances.
949 //
950 // profilingLabels_ is lazily initialized, but behind a lock.
951
952 using SharedCode = RefPtr<const Code>;
953 using MutableCode = RefPtr<Code>;
954 using MetadataAnalysisHashMap =
955 HashMap<const char*, uint32_t, mozilla::CStringHasher, SystemAllocPolicy>;
956
957 class Code : public ShareableBase<Code> {
958 struct ProtectedData {
959 // A vector of all of the code blocks owned by this code. Each code block
960 // is immutable once added to the vector, but this vector may grow.
961 UniqueConstCodeBlockVector blocks;
962 // A vector of link data paired 1:1 with `blocks`. Entries may be null if
963 // the code block is not serializable. This is separate from CodeBlock so
964 // that we may clear it out after serialization has happened.
965 UniqueLinkDataVector blocksLinkData;
966
967 // A vector of code segments that we can allocate lazy segments into
968 SharedCodeSegmentVector lazyStubSegments;
969 // A sorted vector of LazyFuncExport
970 LazyFuncExportVector lazyExports;
971
972 // A vector of code segments that we can lazily allocate functions into
973 SharedCodeSegmentVector lazyFuncSegments;
974
975 // Statistics for tiers of code.
976 CompileAndLinkStats tier1Stats;
977 CompileAndLinkStats tier2Stats;
978 };
979 using ReadGuard = RWExclusiveData<ProtectedData>::ReadGuard;
980 using WriteGuard = RWExclusiveData<ProtectedData>::WriteGuard;
981
982 // The compile mode this code is used with.
983 const CompileMode mode_;
984
985 // Core data that is not thread-safe and must acquire a lock in order to
986 // access.
987 RWExclusiveData<ProtectedData> data_;
988
989 // Thread-safe mutable map from code pointer to code block that contains it.
990 mutable ThreadSafeCodeBlockMap blockMap_;
991
992 // Metadata for this module that is needed for the lifetime of Code. This is
993 // always non-null.
994 SharedCodeMetadata codeMeta_;
995 // Metadata for this module that is needed for the lifetime of Code, and is
996 // only available after the whole module has been decoded. This is always
997 // non-null.
998 SharedCodeTailMetadata codeTailMeta_;
999 // This is null for a wasm module, non-null for asm.js
1000 SharedCodeMetadataForAsmJS codeMetaForAsmJS_;
1001
1002 const CodeBlock* sharedStubs_;
1003 const CodeBlock* completeTier1_;
1004
1005 // [SMDOC] Tier-2 data
1006 //
1007 // hasCompleteTier2_ and completeTier2_ implement a three-state protocol for
1008 // broadcasting tier-2 data; this also amounts to a single-writer/
1009 // multiple-reader setup.
1010 //
1011 // Initially hasCompleteTier2_ is false and completeTier2_ is null.
1012 //
1013 // While hasCompleteTier2_ is false, *no* thread may read completeTier2_, but
1014 // one thread may make completeTier2_ non-null (this will be the tier-2
1015 // compiler thread). That same thread must then later set hasCompleteTier2_
1016 // to true to broadcast the completeTier2_ value and its availability. Note
1017 // that the writing thread may not itself read completeTier2_ before setting
1018 // hasCompleteTier2_, in order to simplify reasoning about global invariants.
1019 //
1020 // Once hasCompleteTier2_ is true, *no* thread may write completeTier2_ and
1021 // *no* thread may read completeTier2_ without having observed
1022 // hasCompleteTier2_ as true first. Once hasCompleteTier2_ is true, it stays
1023 // true.
1024 mutable const CodeBlock* completeTier2_;
1025 mutable mozilla::Atomic<bool> hasCompleteTier2_;
1026
1027 // State for every defined function (not imported) in this module. This is
1028 // only needed if we're doing partial tiering.
1029 mutable FuncStatesPointer funcStates_;
1030
1031 FuncImportVector funcImports_;
1032 ExclusiveData<CacheableCharsVector> profilingLabels_;
1033 JumpTables jumpTables_;
1034
1035 // Where to redirect PC to for handling traps from the signal handler.
1036 uint8_t* trapCode_;
1037
1038 // Offset of the debug stub in the `sharedStubs_` CodeBlock. Not serialized.
1039 uint32_t debugStubOffset_;
1040
1041 // Offset of the request-tier-up stub in the `sharedStubs_` CodeBlock.
1042 uint32_t requestTierUpStubOffset_;
1043
1044 // Offset of the update-call-ref-metrics stub in the `sharedStubs_`
1045 // CodeBlock.
1046 uint32_t updateCallRefMetricsStubOffset_;
1047
1048 // Methods for getting complete tiers, private while we're moving to partial
1049 // tiering.
1050 Tiers completeTiers() const;
1051
1052 [[nodiscard]] bool addCodeBlock(const WriteGuard& guard,
1053 UniqueCodeBlock block,
1054 UniqueLinkData maybeLinkData) const;
1055
1056 [[nodiscard]] const LazyFuncExport* lookupLazyFuncExport(
1057 const WriteGuard& guard, uint32_t funcIndex) const;
1058
1059 // Returns a pointer to the raw interpreter entry of a given function for
1060 // which stubs have been lazily generated.
1061 [[nodiscard]] void* lookupLazyInterpEntry(const WriteGuard& guard,
1062 uint32_t funcIndex) const;
1063
1064 [[nodiscard]] bool createOneLazyEntryStub(const WriteGuard& guard,
1065 uint32_t funcExportIndex,
1066 const CodeBlock& tierCodeBlock,
1067 void** interpEntry) const;
1068 [[nodiscard]] bool createManyLazyEntryStubs(
1069 const WriteGuard& guard, const Uint32Vector& funcExportIndices,
1070 const CodeBlock& tierCodeBlock, size_t* stubBlockIndex) const;
1071 // Create one lazy stub for all the functions in funcExportIndices, putting
1072 // them in a single stub. Jit entries won't be used until
1073 // setJitEntries() is actually called, after the Code owner has committed
1074 // tier2.
1075 [[nodiscard]] bool createTier2LazyEntryStubs(
1076 const WriteGuard& guard, const CodeBlock& tier2Code,
1077 mozilla::Maybe<size_t>* outStubBlockIndex) const;
1078 [[nodiscard]] bool appendProfilingLabels(
1079 const ExclusiveData<CacheableCharsVector>::Guard& labels,
1080 const CodeBlock& codeBlock) const;
1081
1082 void printStats() const;
1083
1084 public:
1085 Code(CompileMode mode, const CodeMetadata& codeMeta,
1086 const CodeTailMetadata& codeTailMeta,
1087 const CodeMetadataForAsmJS* codeMetaForAsmJS);
1088 ~Code();
1089
1090 [[nodiscard]] bool initialize(FuncImportVector&& funcImports,
1091 UniqueCodeBlock sharedStubs,
1092 UniqueLinkData sharedStubsLinkData,
1093 UniqueCodeBlock tier1CodeBlock,
1094 UniqueLinkData tier1LinkData,
1095 const CompileAndLinkStats& tier1Stats);
1096 [[nodiscard]] bool finishTier2(UniqueCodeBlock tier2CodeBlock,
1097 UniqueLinkData tier2LinkData,
1098 const CompileAndLinkStats& tier2Stats) const;
1099
1100 [[nodiscard]] bool getOrCreateInterpEntry(uint32_t funcIndex,
1101 const FuncExport** funcExport,
1102 void** interpEntry) const;
1103
1104 SharedCodeSegment createFuncCodeSegmentFromPool(
1105 jit::MacroAssembler& masm, const LinkData& linkData,
1106 bool allowLastDitchGC, uint8_t** codeStartOut,
1107 uint32_t* codeLengthOut) const;
1108
1109 bool requestTierUp(uint32_t funcIndex) const;
1110
1111 CompileMode mode() const { return mode_; }
1112
1113 void** tieringJumpTable() const { return jumpTables_.tiering(); }
1114
1115 void setJitEntryIfNull(size_t i, void* target) const {
1116 jumpTables_.setJitEntryIfNull(i, target);
1117 }
1118 void** getAddressOfJitEntry(size_t i) const {
1119 return jumpTables_.getAddressOfJitEntry(i);
1120 }
1121 uint32_t funcIndexFromJitEntry(void** jitEntry) const {
1122 return jumpTables_.funcIndexFromJitEntry(jitEntry);
1123 }
1124
1125 uint8_t* trapCode() const { return trapCode_; }
1126
1127 uint32_t debugStubOffset() const { return debugStubOffset_; }
1128 void setDebugStubOffset(uint32_t offs) { debugStubOffset_ = offs; }
1129
1130 uint32_t requestTierUpStubOffset() const { return requestTierUpStubOffset_; }
1131 void setRequestTierUpStubOffset(uint32_t offs) {
1132 requestTierUpStubOffset_ = offs;
1133 }
1134
1135 uint32_t updateCallRefMetricsStubOffset() const {
1136 return updateCallRefMetricsStubOffset_;
1137 }
1138 void setUpdateCallRefMetricsStubOffset(uint32_t offs) {
1139 updateCallRefMetricsStubOffset_ = offs;
1140 }
1141
1142 const FuncImport& funcImport(uint32_t funcIndex) const {
1143 return funcImports_[funcIndex];
1144 }
1145 const FuncImportVector& funcImports() const { return funcImports_; }
1146
1147 bool hasCompleteTier(Tier tier) const;
1148 // The 'stable' complete tier of code. This is stable during a run/
1149 Tier stableCompleteTier() const;
1150 // The 'best' complete tier of code. This may transition from baseline to ion
1151 // at any time.
1152 Tier bestCompleteTier() const;
1153 bool hasSerializableCode() const { return hasCompleteTier(Tier::Serialized); }
1154
1155 const CodeMetadata& codeMeta() const { return *codeMeta_; }
1156 const CodeMetadataForAsmJS* codeMetaForAsmJS() const {
1157 return codeMetaForAsmJS_;
1158 }
1159 const CodeTailMetadata& codeTailMeta() const { return *codeTailMeta_; }
1160 bool debugEnabled() const { return codeTailMeta_->debugEnabled; }
1161
1162 const CodeBlock& sharedStubs() const { return *sharedStubs_; }
1163 const CodeBlock& debugCodeBlock() const {
1164 MOZ_ASSERT(debugEnabled());
1165 MOZ_ASSERT(completeTier1_->tier() == Tier::Debug);
1166 return *completeTier1_;
1167 }
1168 const CodeBlock& completeTierCodeBlock(Tier tier) const;
1169 const CodeBlock& funcCodeBlock(uint32_t funcIndex) const {
1170 if (funcIndex < funcImports_.length()) {
1171 return *sharedStubs_;
1172 }
1173 if (mode_ == CompileMode::LazyTiering) {
1174 return *funcStates_.get()[funcIndex - codeMeta_->numFuncImports].bestTier;
1175 }
1176 return completeTierCodeBlock(bestCompleteTier());
1177 }
1178 bool funcHasTier(uint32_t funcIndex, Tier tier) const {
1179 if (funcIndex < funcImports_.length()) {
1180 return false;
1181 }
1182 return funcCodeBlock(funcIndex).tier() == tier;
1183 }
1184 Tier funcTier(uint32_t funcIndex) const {
1185 MOZ_ASSERT(funcIndex >= funcImports_.length());
1186 return funcCodeBlock(funcIndex).tier();
1187 }
1188 void funcCodeRange(uint32_t funcIndex, const wasm::CodeRange** range,
1189 uint8_t** codeBase) const {
1190 const CodeBlock& codeBlock = funcCodeBlock(funcIndex);
1191 *range = &codeBlock.codeRanges[codeBlock.funcToCodeRange[funcIndex]];
1192 *codeBase = codeBlock.base();
1193 }
1194
1195 const LinkData* codeBlockLinkData(const CodeBlock& block) const;
1196 void clearLinkData() const;
1197
1198 // Code metadata lookup:
1199 bool lookupCallSite(void* pc, CallSite* callSite) const {
1200 const CodeBlock* block = blockMap_.lookup(pc);
1201 if (!block) {
1202 return false;
1203 }
1204 return block->lookupCallSite(pc, callSite);
1205 }
1206 const CodeRange* lookupFuncRange(void* pc) const {
1207 const CodeBlock* block = blockMap_.lookup(pc);
1208 if (!block) {
1209 return nullptr;
1210 }
1211 const CodeRange* result = block->lookupRange(pc);
1212 if (result && result->isFunction()) {
1213 return result;
1214 }
1215 return nullptr;
1216 }
1217 const StackMap* lookupStackMap(uint8_t* pc) const {
1218 const CodeBlock* block = blockMap_.lookup(pc);
1219 if (!block) {
1220 return nullptr;
1221 }
1222 return block->lookupStackMap(pc);
1223 }
1224 const wasm::TryNote* lookupTryNote(void* pc, const CodeBlock** block) const {
1225 *block = blockMap_.lookup(pc);
1226 if (!*block) {
1227 return nullptr;
1228 }
1229 return (*block)->lookupTryNote(pc);
1230 }
1231 bool lookupTrap(void* pc, Trap* kindOut, TrapSite* trapOut) const {
1232 const CodeBlock* block = blockMap_.lookup(pc);
1233 if (!block) {
1234 return false;
1235 }
1236 return block->lookupTrap(pc, kindOut, trapOut);
1237 }
1238 const CodeRangeUnwindInfo* lookupUnwindInfo(void* pc) const {
1239 const CodeBlock* block = blockMap_.lookup(pc);
1240 if (!block) {
1241 return nullptr;
1242 }
1243 return block->lookupUnwindInfo(pc);
1244 }
1245
1246 // To save memory, profilingLabels_ are generated lazily when profiling mode
1247 // is enabled.
1248
1249 void ensureProfilingLabels(bool profilingEnabled) const;
1250 const char* profilingLabel(uint32_t funcIndex) const;
1251
1252 // Wasm disassembly support
1253
1254 void disassemble(JSContext* cx, Tier tier, int kindSelection,
1255 PrintCallback printString) const;
1256
1257 // Wasm metadata size analysis
1258 MetadataAnalysisHashMap metadataAnalysis(JSContext* cx) const;
1259
1260 // about:memory reporting:
1261
1262 void addSizeOfMiscIfNotSeen(
1263 mozilla::MallocSizeOf mallocSizeOf, CodeMetadata::SeenSet* seenCodeMeta,
1264 CodeMetadataForAsmJS::SeenSet* seenCodeMetaForAsmJS,
1265 Code::SeenSet* seenCode, size_t* code, size_t* data) const;
1266
1267 size_t tier1CodeMemoryUsed() const {
1268 return completeTier1_->segment->capacityBytes();
1269 }
1270
1271 WASM_DECLARE_FRIEND_SERIALIZE_ARGS(SharedCode,
1272 const wasm::LinkData& sharedStubsLinkData,
1273 const wasm::LinkData& optimizedLinkData);
1274 };
1275
1276 void PatchDebugSymbolicAccesses(uint8_t* codeBase, jit::MacroAssembler& masm);
1277
1278 } // namespace wasm
1279 } // namespace js
1280
1281 #endif // wasm_code_h