Debian Codegraph @

js/src/wasm/WasmGC.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 2019 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_gc_h
20 #define wasm_gc_h
21
22 #include "mozilla/BinarySearch.h"
23
24 #include "jit/ABIArgGenerator.h" // For ABIArgIter
25 #include "js/AllocPolicy.h"
26 #include "js/Vector.h"
27 #include "util/Memory.h"
28 #include "wasm/WasmBuiltins.h"
29 #include "wasm/WasmFrame.h"
30 #include "wasm/WasmSerialize.h"
31
32 namespace js {
33
34 namespace jit {
35 class Label;
36 class MacroAssembler;
37 } // namespace jit
38
39 namespace wasm {
40
41 class ArgTypeVector;
42 class BytecodeOffset;
43
44 // Definitions for stackmaps.
45
46 using ExitStubMapVector = Vector<bool, 32, SystemAllocPolicy>;
47
48 struct StackMapHeader {
49 explicit StackMapHeader(uint32_t numMappedWords = 0)
50 : numMappedWords(numMappedWords),
51 numExitStubWords(0),
52 frameOffsetFromTop(0),
53 hasDebugFrameWithLiveRefs(0) {}
54
55 // The total number of stack words covered by the map ..
56 static constexpr size_t MappedWordsBits = 30;
57 uint32_t numMappedWords : MappedWordsBits;
58
59 // .. of which this many are "exit stub" extras
60 static constexpr size_t ExitStubWordsBits = 6;
61 uint32_t numExitStubWords : ExitStubWordsBits;
62
63 // Where is Frame* relative to the top? This is an offset in words. On every
64 // platform, FrameOffsetBits needs to be at least
65 // ceil(log2(MaxParams*sizeof-biggest-param-type-in-words)). The most
66 // constraining platforms are 32-bit with SIMD support, currently x86-32.
67 static constexpr size_t FrameOffsetBits = 12;
68 uint32_t frameOffsetFromTop : FrameOffsetBits;
69
70 // Notes the presence of a DebugFrame with possibly-live references. A
71 // DebugFrame may or may not contain GC-managed data; in situations when it is
72 // possible that any pointers in the DebugFrame are non-null, the DebugFrame
73 // gets a stackmap.
74 uint32_t hasDebugFrameWithLiveRefs : 1;
75
76 WASM_CHECK_CACHEABLE_POD(numMappedWords, numExitStubWords, frameOffsetFromTop,
77 hasDebugFrameWithLiveRefs);
78
79 static constexpr uint32_t maxMappedWords = (1 << MappedWordsBits) - 1;
80 static constexpr uint32_t maxExitStubWords = (1 << ExitStubWordsBits) - 1;
81 static constexpr uint32_t maxFrameOffsetFromTop = (1 << FrameOffsetBits) - 1;
82
83 static constexpr size_t MaxParamSize =
84 std::max(sizeof(jit::FloatRegisters::RegisterContent),
85 sizeof(jit::Registers::RegisterContent));
86
87 // Add 16 words to account for the size of FrameWithInstances including any
88 // shadow stack (at worst 8 words total), and then a little headroom in case
89 // the argument area had to be aligned.
90 static_assert(sizeof(FrameWithInstances) / sizeof(void*) <= 8);
91 static_assert(maxFrameOffsetFromTop >=
92 (MaxParams * MaxParamSize / sizeof(void*)) + 16,
93 "limited size of the offset field");
94 };
95
96 WASM_DECLARE_CACHEABLE_POD(StackMapHeader);
97
98 // This is the expected size for the header
99 static_assert(sizeof(StackMapHeader) == 8,
100 "wasm::StackMapHeader has unexpected size");
101
102 // A StackMap is a bit-array containing numMappedWords*2 bits, two bits per
103 // word of stack. Index zero is for the lowest addressed word in the range.
104 //
105 // This is a variable-length structure whose size must be known at creation
106 // time.
107 //
108 // Users of the map will know the address of the wasm::Frame that is covered
109 // by this map. In order that they can calculate the exact address range
110 // covered by the map, the map also stores the offset, from the highest
111 // addressed word of the map, of the embedded wasm::Frame. This is an offset
112 // down from the highest address, rather than up from the lowest, so as to
113 // limit its range to FrameOffsetBits bits.
114 //
115 // The stackmap may also cover a DebugFrame (all DebugFrames which may
116 // potentially contain live pointers into the JS heap get a map). If so, that
117 // can be noted, since users of the map need to trace pointers in a
118 // DebugFrame.
119 //
120 // Finally, for sanity checking only, for stackmaps associated with a wasm
121 // trap exit stub, the number of words used by the trap exit stub save area
122 // is also noted. This is used in Instance::traceFrame to check that the
123 // TrapExitDummyValue is in the expected place in the frame.
124 struct StackMap final {
125 // The header contains the constant-sized fields before the variable-sized
126 // bitmap that follows.
127 StackMapHeader header;
128
129 enum Kind : uint32_t {
130 POD = 0,
131 AnyRef = 1,
132
133 // The data pointer for a WasmArrayObject, which may be an interior pointer
134 // to the object itself. See WasmArrayObject::inlineStorage.
135 ArrayDataPointer = 2,
136
137 Limit,
138 };
139
140 private:
141 // The variable-sized bitmap.
142 uint32_t bitmap[1];
143
144 explicit StackMap(uint32_t numMappedWords) : header(numMappedWords) {
145 const uint32_t nBitmap = calcBitmapNumElems(header.numMappedWords);
146 memset(bitmap, 0, nBitmap * sizeof(bitmap[0]));
147 }
148 explicit StackMap(const StackMapHeader& header) : header(header) {
149 const uint32_t nBitmap = calcBitmapNumElems(header.numMappedWords);
150 memset(bitmap, 0, nBitmap * sizeof(bitmap[0]));
151 }
152
153 public:
154 static StackMap* create(uint32_t numMappedWords) {
155 size_t size = allocationSizeInBytes(numMappedWords);
156 char* buf = (char*)js_malloc(size);
157 if (!buf) {
158 return nullptr;
159 }
160 return ::new (buf) StackMap(numMappedWords);
161 }
162 static StackMap* create(const StackMapHeader& header) {
163 size_t size = allocationSizeInBytes(header.numMappedWords);
164 char* buf = (char*)js_malloc(size);
165 if (!buf) {
166 return nullptr;
167 }
168 return ::new (buf) StackMap(header);
169 }
170
171 void destroy() { js_free((char*)this); }
172
173 // Returns the size of a `StackMap` allocated with `numMappedWords`.
174 static size_t allocationSizeInBytes(uint32_t numMappedWords) {
175 uint32_t nBitmap = calcBitmapNumElems(numMappedWords);
176 return sizeof(StackMap) + (nBitmap - 1) * sizeof(bitmap[0]);
177 }
178
179 // Returns the allocated size of this `StackMap`.
180 size_t allocationSizeInBytes() const {
181 return allocationSizeInBytes(header.numMappedWords);
182 }
183
184 // Record the number of words in the map used as a wasm trap exit stub
185 // save area. See comment above.
186 void setExitStubWords(uint32_t nWords) {
187 MOZ_ASSERT(header.numExitStubWords == 0);
188 MOZ_RELEASE_ASSERT(nWords <= header.maxExitStubWords);
189 MOZ_ASSERT(nWords <= header.numMappedWords);
190 header.numExitStubWords = nWords;
191 }
192
193 // Record the offset from the highest-addressed word of the map, that the
194 // wasm::Frame lives at. See comment above.
195 void setFrameOffsetFromTop(uint32_t nWords) {
196 MOZ_ASSERT(header.frameOffsetFromTop == 0);
197 MOZ_RELEASE_ASSERT(nWords <= StackMapHeader::maxFrameOffsetFromTop);
198 MOZ_ASSERT(header.frameOffsetFromTop < header.numMappedWords);
199 header.frameOffsetFromTop = nWords;
200 }
201
202 // If the frame described by this StackMap includes a DebugFrame, call here to
203 // record that fact.
204 void setHasDebugFrameWithLiveRefs() {
205 MOZ_ASSERT(header.hasDebugFrameWithLiveRefs == 0);
206 header.hasDebugFrameWithLiveRefs = 1;
207 }
208
209 inline void set(uint32_t index, Kind kind) {
210 MOZ_ASSERT(index < header.numMappedWords);
211 MOZ_ASSERT(kind < Kind::Limit);
212 uint32_t wordIndex = index / mappedWordsPerBitmapElem;
213 uint32_t wordOffset = index % mappedWordsPerBitmapElem * bitsPerMappedWord;
214 bitmap[wordIndex] |= (kind << wordOffset);
215 }
216
217 inline Kind get(uint32_t index) const {
218 MOZ_ASSERT(index < header.numMappedWords);
219 uint32_t wordIndex = index / mappedWordsPerBitmapElem;
220 uint32_t wordOffset = index % mappedWordsPerBitmapElem * bitsPerMappedWord;
221 Kind result = Kind((bitmap[wordIndex] >> wordOffset) & valueMask);
222 return result;
223 }
224
225 inline uint8_t* rawBitmap() { return (uint8_t*)&bitmap; }
226 inline const uint8_t* rawBitmap() const { return (const uint8_t*)&bitmap; }
227 inline size_t rawBitmapLengthInBytes() const {
228 return calcBitmapNumElems(header.numMappedWords) * sizeof(bitmap[0]);
229 }
230
231 private:
232 static constexpr uint32_t bitsPerMappedWord = 2;
233 static constexpr uint32_t mappedWordsPerBitmapElem =
234 sizeof(bitmap[0]) * CHAR_BIT / bitsPerMappedWord;
235 static constexpr uint32_t valueMask = js::BitMask(bitsPerMappedWord);
236 static_assert(8 % bitsPerMappedWord == 0);
237 static_assert(Kind::Limit - 1 <= valueMask);
238
239 static uint32_t calcBitmapNumElems(uint32_t numMappedWords) {
240 MOZ_RELEASE_ASSERT(numMappedWords <= StackMapHeader::maxMappedWords);
241 uint32_t nBitmap = js::HowMany(numMappedWords, mappedWordsPerBitmapElem);
242 return nBitmap == 0 ? 1 : nBitmap;
243 }
244 };
245
246 // This is the expected size for a map that covers 32 or fewer words.
247 static_assert(sizeof(StackMap) == 12, "wasm::StackMap has unexpected size");
248
249 // A map from an offset relative to the beginning of a code block to a StackMap
250 using StackMapHashMap =
251 HashMap<uint32_t, StackMap*, DefaultHasher<uint32_t>, SystemAllocPolicy>;
252
253 class StackMaps {
254 private:
255 // Map for finding a stack map at a specific code offset.
256 StackMapHashMap mapping_;
257
258 public:
259 StackMaps() {}
260 ~StackMaps() {
261 for (auto iter = mapping_.modIter(); !iter.done(); iter.next()) {
262 StackMap* stackmap = iter.getMutable().value();
263 stackmap->destroy();
264 }
265 mapping_.clear();
266 }
267
268 [[nodiscard]] bool add(uint32_t codeOffset, StackMap* map) {
269 return mapping_.put(codeOffset, map);
270 }
271 void clear() { mapping_.clear(); }
272 bool empty() const { return mapping_.empty(); }
273 // Return the number of stack maps contained in this.
274 size_t length() const { return mapping_.count(); }
275
276 // Add all the stack maps from the other collection to this collection.
277 // Apply an optional offset while adding the stack maps.
278 [[nodiscard]] bool appendAll(StackMaps& other, uint32_t offsetInModule) {
279 // Reserve space for the new mappings so that we don't have to handle
280 // failure in the loop below.
281 if (!mapping_.reserve(mapping_.count() + other.mapping_.count())) {
282 return false;
283 }
284
285 for (auto iter = other.mapping_.modIter(); !iter.done(); iter.next()) {
286 uint32_t newOffset = iter.get().key() + offsetInModule;
287 StackMap* stackMap = iter.get().value();
288 mapping_.putNewInfallible(newOffset, stackMap);
289 }
290
291 other.mapping_.clear();
292 return true;
293 }
294
295 const StackMap* lookup(uint32_t codeOffset) const {
296 auto ptr = mapping_.readonlyThreadsafeLookup(codeOffset);
297 if (!ptr) {
298 return nullptr;
299 }
300
301 return ptr->value();
302 }
303
304 size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
305 return mapping_.shallowSizeOfExcludingThis(mallocSizeOf);
306 }
307
308 void checkInvariants(const uint8_t* base) const;
309
310 WASM_DECLARE_FRIEND_SERIALIZE(StackMaps);
311 };
312
313 // Supporting code for creation of stackmaps.
314
315 // StackArgAreaSizeUnaligned returns the size, in bytes, of the stack arg area
316 // size needed to pass |argTypes|, excluding any alignment padding beyond the
317 // size of the area as a whole. The size is as determined by the platforms
318 // native ABI.
319 //
320 // StackArgAreaSizeAligned returns the same, but rounded up to the nearest 16
321 // byte boundary.
322 //
323 // Note, StackArgAreaSize{Unaligned,Aligned}() must process all the arguments
324 // in order to take into account all necessary alignment constraints. The
325 // signature must include any receiver argument -- in other words, it must be
326 // the complete native-ABI-level call signature.
327 template <class T>
328 static inline size_t StackArgAreaSizeUnaligned(const T& argTypes) {
329 jit::WasmABIArgIter<const T> i(argTypes);
330 while (!i.done()) {
331 i++;
332 }
333 return i.stackBytesConsumedSoFar();
334 }
335
336 static inline size_t StackArgAreaSizeUnaligned(
337 const SymbolicAddressSignature& saSig) {
338 // WasmABIArgIter::ABIArgIter wants the items to be iterated over to be
339 // presented in some type that has methods length() and operator[]. So we
340 // have to wrap up |saSig|'s array of types in this API-matching class.
341 class MOZ_STACK_CLASS ItemsAndLength {
342 const jit::MIRType* items_;
343 size_t length_;
344
345 public:
346 ItemsAndLength(const jit::MIRType* items, size_t length)
347 : items_(items), length_(length) {}
348 size_t length() const { return length_; }
349 jit::MIRType operator[](size_t i) const { return items_[i]; }
350 };
351
352 // Assert, at least crudely, that we're not accidentally going to run off
353 // the end of the array of types, nor into undefined parts of it, while
354 // iterating.
355 MOZ_ASSERT(saSig.numArgs <
356 sizeof(saSig.argTypes) / sizeof(saSig.argTypes[0]));
357 MOZ_ASSERT(saSig.argTypes[saSig.numArgs] ==
358 jit::MIRType::None /*the end marker*/);
359
360 ItemsAndLength itemsAndLength(saSig.argTypes, saSig.numArgs);
361 return StackArgAreaSizeUnaligned(itemsAndLength);
362 }
363
364 static inline size_t AlignStackArgAreaSize(size_t unalignedSize) {
365 return AlignBytes(unalignedSize, jit::WasmStackAlignment);
366 }
367
368 // Generate a stackmap for a function's stack-overflow-at-entry trap, with
369 // the structure:
370 //
371 // <reg dump area>
372 // | ++ <space reserved before trap, if any>
373 // | ++ <space for Frame>
374 // | ++ <inbound arg area>
375 // | |
376 // Lowest Addr Highest Addr
377 //
378 // The caller owns the resulting stackmap. This assumes a grow-down stack.
379 //
380 // For non-debug builds, if the stackmap would contain no pointers, no
381 // stackmap is created, and nullptr is returned. For a debug build, a
382 // stackmap is always created and returned.
383 //
384 // The "space reserved before trap" is the space reserved by
385 // MacroAssembler::wasmReserveStackChecked, in the case where the frame is
386 // "small", as determined by that function.
387 [[nodiscard]] bool CreateStackMapForFunctionEntryTrap(
388 const ArgTypeVector& argTypes, const jit::RegisterOffsets& trapExitLayout,
389 size_t trapExitLayoutWords, size_t nBytesReservedBeforeTrap,
390 size_t nInboundStackArgBytes, wasm::StackMap** result);
391
392 // At a resumable wasm trap, the machine's registers are saved on the stack by
393 // (code generated by) GenerateTrapExit(). This function writes into |args| a
394 // vector of booleans describing the ref-ness of the saved integer registers.
395 // |args[0]| corresponds to the low addressed end of the described section of
396 // the save area.
397 [[nodiscard]] bool GenerateStackmapEntriesForTrapExit(
398 const ArgTypeVector& args, const jit::RegisterOffsets& trapExitLayout,
399 const size_t trapExitLayoutNumWords, ExitStubMapVector* extras);
400
401 // Shared write barrier code.
402 //
403 // A barriered store looks like this:
404 //
405 // Label skipPreBarrier;
406 // EmitWasmPreBarrierGuard(..., &skipPreBarrier);
407 // <COMPILER-SPECIFIC ACTIONS HERE>
408 // EmitWasmPreBarrierCall(...);
409 // bind(&skipPreBarrier);
410 //
411 // <STORE THE VALUE IN MEMORY HERE>
412 //
413 // Label skipPostBarrier;
414 // <COMPILER-SPECIFIC ACTIONS HERE>
415 // EmitWasmPostBarrierGuard(..., &skipPostBarrier);
416 // <CALL POST-BARRIER HERE IN A COMPILER-SPECIFIC WAY>
417 // bind(&skipPostBarrier);
418 //
419 // The actions are divided up to allow other actions to be placed between them,
420 // such as saving and restoring live registers. The postbarrier call invokes
421 // C++ and will kill all live registers.
422
423 // Before storing a GC pointer value in memory, skip to `skipBarrier` if the
424 // prebarrier is not needed. Will clobber `scratch`.
425 //
426 // It is OK for `instance` and `scratch` to be the same register.
427 //
428 // If `trapSiteDesc` is something, then metadata to catch a null access and emit
429 // a null pointer exception will be emitted. This will only catch a null access
430 // due to an incremental GC being in progress, the write that follows this
431 // pre-barrier guard must also be guarded against null.
432 template <class Addr>
433 void EmitWasmPreBarrierGuard(jit::MacroAssembler& masm, jit::Register instance,
434 jit::Register scratch, Addr addr,
435 jit::Label* skipBarrier,
436 MaybeTrapSiteDesc trapSiteDesc);
437
438 // Before storing a GC pointer value in memory, call out-of-line prebarrier
439 // code. This assumes `PreBarrierReg` contains the address that will be updated.
440 // On ARM64 it also assums that x28 (the PseudoStackPointer) has the same value
441 // as SP. `PreBarrierReg` is preserved by the barrier function. Will clobber
442 // `scratch`.
443 //
444 // It is OK for `instance` and `scratch` to be the same register.
445 void EmitWasmPreBarrierCallImmediate(jit::MacroAssembler& masm,
446 jit::Register instance,
447 jit::Register scratch,
448 jit::Register valueAddr,
449 size_t valueOffset);
450 // The equivalent of EmitWasmPreBarrierCallImmediate, but for a jit::BaseIndex.
451 // Will clobber `scratch1` and `scratch2`.
452 //
453 // It is OK for `instance` and `scratch1` to be the same register.
454 void EmitWasmPreBarrierCallIndex(jit::MacroAssembler& masm,
455 jit::Register instance, jit::Register scratch1,
456 jit::Register scratch2, jit::BaseIndex addr);
457
458 // After storing a GC pointer value in memory, skip to `skipBarrier` if a
459 // postbarrier is not needed. If the location being set is in an heap-allocated
460 // object then `object` must reference that object; otherwise it should be None.
461 // The value that was stored is `setValue`. Will clobber `otherScratch` and
462 // will use other available scratch registers.
463 //
464 // `otherScratch` cannot be a designated scratch register.
465 void EmitWasmPostBarrierGuard(jit::MacroAssembler& masm,
466 const mozilla::Maybe<jit::Register>& object,
467 jit::Register otherScratch,
468 jit::Register setValue, jit::Label* skipBarrier);
469
470 // Before calling Instance::postBarrierWholeCell, we can check the object
471 // against the store buffer's last element cache, skipping the post barrier if
472 // that object had already been barriered.
473 //
474 // `instance` and `temp` can be the same register; if so, instance will be
475 // clobbered, otherwise instance will be preserved.
476 void CheckWholeCellLastElementCache(jit::MacroAssembler& masm,
477 jit::Register instance,
478 jit::Register object, jit::Register temp,
479 jit::Label* skipBarrier);
480
481 #ifdef DEBUG
482 // Check (approximately) whether `nextPC` is a valid code address for a
483 // stackmap created by this compiler. This is done by examining the
484 // instruction at `nextPC`. The matching is inexact, so it may err on the
485 // side of returning `true` if it doesn't know. Doing so reduces the
486 // effectiveness of the MOZ_ASSERTs that use this function, so at least for
487 // the four primary platforms we should keep it as exact as possible.
488
489 bool IsPlausibleStackMapKey(const uint8_t* nextPC);
490 #endif
491
492 } // namespace wasm
493 } // namespace js
494
495 #endif // wasm_gc_h