Debian Codegraph @

js/src/wasm/WasmGcObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "wasm/WasmGcObject-inl.h"
8
9 #include <algorithm>
10
11 #include "gc/Marking.h"
12 #include "js/CharacterEncoding.h"
13 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
14 #include "js/PropertySpec.h"
15 #include "js/ScalarType.h" // js::Scalar::Type
16 #include "js/Vector.h"
17 #include "util/StringBuilder.h"
18 #include "vm/GlobalObject.h"
19 #include "vm/JSFunction.h"
20 #include "vm/JSObject.h"
21 #include "vm/PlainObject.h" // js::PlainObject
22 #include "vm/PropertyResult.h"
23 #include "vm/Realm.h"
24 #include "vm/SelfHosting.h"
25 #include "vm/StringType.h"
26 #include "vm/TypedArrayObject.h"
27 #include "vm/Uint8Clamped.h"
28
29 #include "gc/GCContext-inl.h" // GCContext::removeCellMemory
30 #include "gc/ObjectKind-inl.h"
31 #include "vm/JSContext-inl.h"
32
33 using namespace js;
34 using namespace wasm;
35
36 // [SMDOC] Management of OOL storage areas for Wasm{Array,Struct}Object.
37 //
38 // WasmArrayObject always has its payload data stored in a block the C++-heap,
39 // which is pointed to from the WasmArrayObject. The same is true for
40 // WasmStructObject in the case where the fields cannot fit in the object
41 // itself. These C++ blocks are in some places referred to as "trailer blocks".
42 //
43 // The presence of trailer blocks complicates the use of generational GC (that
44 // is, Nursery allocation) of Wasm{Array,Struct}Object. In particular:
45 //
46 // (1) For objects which do not get tenured at minor collection, there must be
47 // a way to free the associated trailer, but there is no way to visit
48 // non-tenured blocks during minor collection.
49 //
50 // (2) Even if (1) were solved, calling js_malloc/js_free for every object
51 // creation-death cycle is expensive, possibly around 400 machine
52 // instructions, and we expressly want to avoid that in a generational GC
53 // scenario.
54 //
55 // The following scheme is therefore employed.
56 //
57 // (a) gc::Nursery maintains a pool of available C++-heap-allocated blocks --
58 // a js::MallocedBlockCache -- and the intention is that trailers are
59 // allocated from this pool and freed back into it whenever possible.
60 //
61 // (b) WasmArrayObject::createArrayNonEmpty and
62 // WasmStructObject::createStructOOL always request trailer allocation
63 // from the nursery's cache (a). If the cache cannot honour the request
64 // directly it will allocate directly from js_malloc; we hope this happens
65 // only infrequently.
66 //
67 // (c) The allocated block is returned as a js::PointerAndUint7, a pair that
68 // holds the trailer block pointer and an auxiliary tag that the
69 // js::MallocedBlockCache needs to see when the block is freed.
70 //
71 // The raw trailer block pointer (a `void*`) is stored in the
72 // Wasm{Array,Struct}Object OOL data field. These objects are not aware
73 // of and do not interact with js::PointerAndUint7, and nor does any
74 // JIT-generated code.
75 //
76 // (d) Still in WasmArrayObject::createArrayNonEmpty and
77 // WasmStructObject::createStructOOL, if the object was allocated in the
78 // nursery, then the resulting js::PointerAndUint7 is "registered" with
79 // the nursery by handing it to Nursery::registerTrailer.
80 //
81 // (e) When a minor collection happens (Nursery::doCollection), we are
82 // notified of objects that are moved by calls to the ::obj_moved methods
83 // in this file. For those objects that have been tenured, the raw
84 // trailer pointer is "unregistered" with the nursery by handing it to
85 // Nursery::unregisterTrailer.
86 //
87 // (f) Still during minor collection: The nursery now knows both the set of
88 // trailer blocks added, and those removed because the corresponding
89 // object has been tenured. The difference between these two sets (that
90 // is, `added - removed`) is the set of trailer blocks corresponding to
91 // blocks that didn't get tenured. That set is computed and freed (back
92 // to the nursery's js::MallocedBlockCache) by Nursery::freeTrailerBlocks.
93 //
94 // (g) At the end of minor collection, the added and removed sets are made
95 // empty, and the cycle begins again.
96 //
97 // (h) Also at the end of minor collection, a call to
98 // `mallocedBlockCache_.preen` hands a few blocks in the cache back to
99 // js_free. This mechanism exists so as to ensure that unused blocks do
100 // not remain in the cache indefinitely.
101 //
102 // (i) In order that the tenured heap is collected "often enough" in the case
103 // where the trailer blocks are large (relative to their owning objects),
104 // we have to tell the tenured heap about the sizes of trailers entering
105 // and leaving it. This is done via calls to AddCellMemory and
106 // GCContext::removeCellMemory.
107 //
108 // (j) For objects that got tenured, we are eventually notified of their death
109 // by a call to the ::obj_finalize methods below. At that point we hand
110 // their block pointers to js_free.
111 //
112 // (k) When the nursery is eventually destroyed, all blocks in its block cache
113 // are handed to js_free. Hence, at process exit, provided all nurseries
114 // are first collected and then their destructors run, no C++ heap blocks
115 // are leaked.
116 //
117 // As a result of this scheme, trailer blocks associated with what we hope is
118 // the frequent case -- objects that are allocated but never make it out of
119 // the nursery -- are cycled through the nursery's block cache.
120 //
121 // Trailers associated with tenured blocks cannot participate though; they are
122 // always returned to js_free. Making them participate is difficult: it would
123 // require changing their owning object's OOL data pointer to be a
124 // js::PointerAndUint7 rather than a raw `void*`, so that then the blocks
125 // could be released to the cache in the ::obj_finalize methods. This would
126 // however require changes in the generated code for array element and OOL
127 // struct element accesses.
128 //
129 // It would also lead to threading difficulties, because the ::obj_finalize
130 // methods run on a background thread, whilst allocation from the cache
131 // happens on the main thread, but the MallocedBlockCache is not thread safe.
132 // Making it thread safe would entail adding a locking mechanism, but that's
133 // potentially slow and so negates the point of having a cache at all.
134 //
135 // Here's a short summary of the trailer block life cycle:
136 //
137 // * allocated:
138 //
139 // - in WasmArrayObject::createArrayNonEmpty
140 // and WasmStructObject::createStructOOL
141 //
142 // - by calling the nursery's MallocBlockCache alloc method
143 //
144 // * deallocated:
145 //
146 // - for non-tenured objects, in the collector itself,
147 // in Nursery::doCollection calling Nursery::freeTrailerBlocks,
148 // releasing to the nursery's block cache
149 //
150 // - for tenured objects, in the ::obj_finalize methods, releasing directly
151 // to js_free
152 //
153 // If this seems confusing ("why is it ok to allocate from the cache but
154 // release to js_free?"), remember that the cache holds blocks previously
155 // obtained from js_malloc but which are *not* currently in use. Hence it is
156 // fine to give them back to js_free; that just makes the cache a bit emptier
157 // but has no effect on correctness.
158
159 //=========================================================================
160 // WasmGcObject
161
162 const ObjectOps WasmGcObject::objectOps_ = {
163 WasmGcObject::obj_lookupProperty, // lookupProperty
164 WasmGcObject::obj_defineProperty, // defineProperty
165 WasmGcObject::obj_hasProperty, // hasProperty
166 WasmGcObject::obj_getProperty, // getProperty
167 WasmGcObject::obj_setProperty, // setProperty
168 WasmGcObject::obj_getOwnPropertyDescriptor, // getOwnPropertyDescriptor
169 WasmGcObject::obj_deleteProperty, // deleteProperty
170 nullptr, // getElements
171 nullptr, // funToString
172 };
173
174 /* static */
175 bool WasmGcObject::obj_lookupProperty(JSContext* cx, HandleObject obj,
176 HandleId id, MutableHandleObject objp,
177 PropertyResult* propp) {
178 objp.set(nullptr);
179 propp->setNotFound();
180 return true;
181 }
182
183 bool WasmGcObject::obj_defineProperty(JSContext* cx, HandleObject obj,
184 HandleId id,
185 Handle<PropertyDescriptor> desc,
186 ObjectOpResult& result) {
187 result.failReadOnly();
188 return true;
189 }
190
191 bool WasmGcObject::obj_hasProperty(JSContext* cx, HandleObject obj, HandleId id,
192 bool* foundp) {
193 *foundp = false;
194 return true;
195 }
196
197 bool WasmGcObject::obj_getProperty(JSContext* cx, HandleObject obj,
198 HandleValue receiver, HandleId id,
199 MutableHandleValue vp) {
200 vp.setUndefined();
201 return true;
202 }
203
204 bool WasmGcObject::obj_setProperty(JSContext* cx, HandleObject obj, HandleId id,
205 HandleValue v, HandleValue receiver,
206 ObjectOpResult& result) {
207 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
208 JSMSG_WASM_MODIFIED_GC_OBJECT);
209 return false;
210 }
211
212 bool WasmGcObject::obj_getOwnPropertyDescriptor(
213 JSContext* cx, HandleObject obj, HandleId id,
214 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) {
215 desc.reset();
216 return true;
217 }
218
219 bool WasmGcObject::obj_deleteProperty(JSContext* cx, HandleObject obj,
220 HandleId id, ObjectOpResult& result) {
221 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
222 JSMSG_WASM_MODIFIED_GC_OBJECT);
223 return false;
224 }
225
226 bool WasmGcObject::lookUpProperty(JSContext* cx, Handle<WasmGcObject*> obj,
227 jsid id, WasmGcObject::PropOffset* offset,
228 StorageType* type) {
229 switch (obj->kind()) {
230 case wasm::TypeDefKind::Struct: {
231 const auto& structType = obj->typeDef().structType();
232 uint32_t index;
233 if (!IdIsIndex(id, &index)) {
234 return false;
235 }
236 if (index >= structType.fields_.length()) {
237 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
238 JSMSG_WASM_OUT_OF_BOUNDS);
239 return false;
240 }
241 offset->set(structType.fieldOffset(index));
242 *type = structType.fields_[index].type;
243 return true;
244 }
245 case wasm::TypeDefKind::Array: {
246 const auto& arrayType = obj->typeDef().arrayType();
247
248 uint32_t index;
249 if (!IdIsIndex(id, &index)) {
250 return false;
251 }
252 uint32_t numElements = obj->as<WasmArrayObject>().numElements_;
253 if (index >= numElements) {
254 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
255 JSMSG_WASM_OUT_OF_BOUNDS);
256 return false;
257 }
258 uint64_t scaledIndex =
259 uint64_t(index) * uint64_t(arrayType.elementType().size());
260 if (scaledIndex >= uint64_t(UINT32_MAX)) {
261 // It's unrepresentable as an WasmGcObject::PropOffset. Give up.
262 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
263 JSMSG_WASM_OUT_OF_BOUNDS);
264 return false;
265 }
266 offset->set(uint32_t(scaledIndex));
267 *type = arrayType.elementType();
268 return true;
269 }
270 default:
271 MOZ_ASSERT_UNREACHABLE();
272 return false;
273 }
274 }
275
276 bool WasmGcObject::loadValue(JSContext* cx, Handle<WasmGcObject*> obj, jsid id,
277 MutableHandleValue vp) {
278 WasmGcObject::PropOffset offset;
279 StorageType type;
280 if (!lookUpProperty(cx, obj, id, &offset, &type)) {
281 return false;
282 }
283
284 // Temporary hack, (ref T) is not exposable to JS yet but some tests would
285 // like to access it so we erase (ref T) with eqref when loading. This is
286 // safe as (ref T) <: eqref and we're not in the writing case where we
287 // would need to perform a type check.
288 if (type.isTypeRef()) {
289 type = RefType::fromTypeCode(TypeCode::EqRef, true);
290 }
291
292 if (!type.isExposable()) {
293 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
294 JSMSG_WASM_BAD_VAL_TYPE);
295 return false;
296 }
297
298 if (obj->is<WasmStructObject>()) {
299 // `offset` is the field offset, without regard to the in/out-line split.
300 // That is handled by the call to `fieldOffsetToAddress`.
301 WasmStructObject& structObj = obj->as<WasmStructObject>();
302 // Ensure no out-of-range access possible
303 MOZ_RELEASE_ASSERT(structObj.kind() == TypeDefKind::Struct);
304 MOZ_RELEASE_ASSERT(offset.get() + type.size() <=
305 structObj.typeDef().structType().size_);
306 return ToJSValue(cx, structObj.fieldOffsetToAddress(type, offset.get()),
307 type, vp);
308 }
309
310 MOZ_ASSERT(obj->is<WasmArrayObject>());
311 const WasmArrayObject& arrayObj = obj->as<WasmArrayObject>();
312 return ToJSValue(cx, arrayObj.data_ + offset.get(), type, vp);
313 }
314
315 bool WasmGcObject::isRuntimeSubtypeOf(
316 const wasm::TypeDef* parentTypeDef) const {
317 return TypeDef::isSubTypeOf(&typeDef(), parentTypeDef);
318 }
319
320 bool WasmGcObject::obj_newEnumerate(JSContext* cx, HandleObject obj,
321 MutableHandleIdVector properties,
322 bool enumerableOnly) {
323 return true;
324 }
325
326 static void WriteValTo(const Val& val, StorageType ty, void* dest) {
327 switch (ty.kind()) {
328 case StorageType::I8:
329 *((uint8_t*)dest) = val.i32();
330 break;
331 case StorageType::I16:
332 *((uint16_t*)dest) = val.i32();
333 break;
334 case StorageType::I32:
335 *((uint32_t*)dest) = val.i32();
336 break;
337 case StorageType::I64:
338 *((uint64_t*)dest) = val.i64();
339 break;
340 case StorageType::F32:
341 *((float*)dest) = val.f32();
342 break;
343 case StorageType::F64:
344 *((double*)dest) = val.f64();
345 break;
346 case StorageType::V128:
347 *((V128*)dest) = val.v128();
348 break;
349 case StorageType::Ref:
350 *((GCPtr<AnyRef>*)dest) = val.ref();
351 break;
352 }
353 }
354
355 //=========================================================================
356 // WasmArrayObject
357
358 /* static */
359 void WasmArrayObject::obj_trace(JSTracer* trc, JSObject* object) {
360 WasmArrayObject& arrayObj = object->as<WasmArrayObject>();
361 uint8_t* data = arrayObj.data_;
362
363 const auto& typeDef = arrayObj.typeDef();
364 const auto& arrayType = typeDef.arrayType();
365 if (!arrayType.elementType().isRefRepr()) {
366 return;
367 }
368
369 uint32_t numElements = arrayObj.numElements_;
370 uint32_t elemSize = arrayType.elementType().size();
371 for (uint32_t i = 0; i < numElements; i++) {
372 AnyRef* elementPtr = reinterpret_cast<AnyRef*>(data + i * elemSize);
373 TraceManuallyBarrieredEdge(trc, elementPtr, "wasm-array-element");
374 }
375 }
376
377 /* static */
378 void WasmArrayObject::obj_finalize(JS::GCContext* gcx, JSObject* object) {
379 // This method, and also ::obj_moved and the WasmStructObject equivalents,
380 // assumes that the object's TypeDef (as reachable via its SuperTypeVector*)
381 // stays alive at least as long as the object.
382 WasmArrayObject& arrayObj = object->as<WasmArrayObject>();
383 if (!arrayObj.isDataInline()) {
384 // Free the trailer block. Unfortunately we can't give it back to the
385 // malloc'd block cache because we might not be running on the main
386 // thread, and the cache isn't thread-safe.
387 js_free(arrayObj.dataHeader());
388 // And tell the tenured-heap accounting machinery that the trailer has
389 // been freed.
390 const TypeDef& typeDef = arrayObj.typeDef();
391 MOZ_ASSERT(typeDef.isArrayType());
392 // arrayObj.numElements_ was validated to not overflow when constructing the
393 // array
394 size_t trailerSize = calcStorageBytesUnchecked(
395 typeDef.arrayType().elementType().size(), arrayObj.numElements_);
396 // Ensured by WasmArrayObject::createArrayNonEmpty.
397 MOZ_RELEASE_ASSERT(trailerSize <= size_t(MaxArrayPayloadBytes));
398 gcx->removeCellMemory(&arrayObj, trailerSize + TrailerBlockOverhead,
399 MemoryUse::WasmTrailerBlock);
400 // For safety
401 arrayObj.data_ = nullptr;
402 }
403 }
404
405 /* static */
406 size_t WasmArrayObject::obj_moved(JSObject* obj, JSObject* old) {
407 // Moving inline arrays requires us to update the data pointer.
408 WasmArrayObject& arrayObj = obj->as<WasmArrayObject>();
409 WasmArrayObject& oldArrayObj = old->as<WasmArrayObject>();
410 if (oldArrayObj.isDataInline()) {
411 // The old array had inline storage, which has been copied.
412 // Fix up the data pointer on the new array to point to it.
413 arrayObj.data_ = WasmArrayObject::addressOfInlineData(&arrayObj);
414 }
415 MOZ_ASSERT(arrayObj.isDataInline() == oldArrayObj.isDataInline());
416
417 if (IsInsideNursery(old)) {
418 Nursery& nursery = obj->runtimeFromMainThread()->gc.nursery();
419 // It's been tenured.
420 if (!arrayObj.isDataInline()) {
421 const TypeDef& typeDef = arrayObj.typeDef();
422 MOZ_ASSERT(typeDef.isArrayType());
423 // arrayObj.numElements_ was validated not to overflow when constructing
424 // the array
425 size_t trailerSize = calcStorageBytesUnchecked(
426 typeDef.arrayType().elementType().size(), arrayObj.numElements_);
427 // Ensured by WasmArrayObject::createArrayOOL.
428 MOZ_RELEASE_ASSERT(trailerSize <= size_t(MaxArrayPayloadBytes));
429 nursery.trackTrailerOnPromotion(arrayObj.dataHeader(), obj, trailerSize,
430 TrailerBlockOverhead,
431 MemoryUse::WasmTrailerBlock);
432 }
433 }
434
435 return 0;
436 }
437
438 void WasmArrayObject::storeVal(const Val& val, uint32_t itemIndex) {
439 const ArrayType& arrayType = typeDef().arrayType();
440 size_t elementSize = arrayType.elementType().size();
441 MOZ_ASSERT(itemIndex < numElements_);
442 uint8_t* data = data_ + elementSize * itemIndex;
443 WriteValTo(val, arrayType.elementType(), data);
444 }
445
446 void WasmArrayObject::fillVal(const Val& val, uint32_t itemIndex,
447 uint32_t len) {
448 const ArrayType& arrayType = typeDef().arrayType();
449 size_t elementSize = arrayType.elementType().size();
450 uint8_t* data = data_ + elementSize * itemIndex;
451 MOZ_ASSERT(itemIndex <= numElements_ && len <= numElements_ - itemIndex);
452 for (uint32_t i = 0; i < len; i++) {
453 WriteValTo(val, arrayType.elementType(), data);
454 data += elementSize;
455 }
456 }
457
458 static const JSClassOps WasmArrayObjectClassOps = {
459 nullptr, /* addProperty */
460 nullptr, /* delProperty */
461 nullptr, /* enumerate */
462 WasmGcObject::obj_newEnumerate,
463 nullptr, /* resolve */
464 nullptr, /* mayResolve */
465 WasmArrayObject::obj_finalize, /* finalize */
466 nullptr, /* call */
467 nullptr, /* construct */
468 WasmArrayObject::obj_trace,
469 };
470 static const ClassExtension WasmArrayObjectClassExt = {
471 WasmArrayObject::obj_moved, /* objectMovedOp */
472 };
473 const JSClass WasmArrayObject::class_ = {
474 "WasmArrayObject",
475 JSClass::NON_NATIVE | JSCLASS_DELAY_METADATA_BUILDER |
476 JSCLASS_BACKGROUND_FINALIZE | JSCLASS_SKIP_NURSERY_FINALIZE,
477 &WasmArrayObjectClassOps,
478 JS_NULL_CLASS_SPEC,
479 &WasmArrayObjectClassExt,
480 &WasmGcObject::objectOps_,
481 };
482
483 //=========================================================================
484 // WasmStructObject
485
486 /* static */
487 const JSClass* js::WasmStructObject::classForTypeDef(
488 const wasm::TypeDef* typeDef) {
489 MOZ_ASSERT(typeDef->kind() == wasm::TypeDefKind::Struct);
490 size_t nbytes = typeDef->structType().size_;
491 return nbytes > WasmStructObject_MaxInlineBytes
492 ? &WasmStructObject::classOutline_
493 : &WasmStructObject::classInline_;
494 }
495
496 /* static */
497 js::gc::AllocKind js::WasmStructObject::allocKindForTypeDef(
498 const wasm::TypeDef* typeDef) {
499 MOZ_ASSERT(typeDef->kind() == wasm::TypeDefKind::Struct);
500 size_t nbytes = typeDef->structType().size_;
501
502 // `nbytes` is the total required size for all struct fields, including
503 // padding. What we need is the size of resulting WasmStructObject,
504 // ignoring any space used for out-of-line data. First, restrict `nbytes`
505 // to cover just the inline data.
506 if (nbytes > WasmStructObject_MaxInlineBytes) {
507 nbytes = WasmStructObject_MaxInlineBytes;
508 }
509
510 // Now convert it to size of the WasmStructObject as a whole.
511 nbytes = sizeOfIncludingInlineData(nbytes);
512
513 return gc::GetGCObjectKindForBytes(nbytes);
514 }
515
516 bool WasmStructObject::getField(JSContext* cx, uint32_t index,
517 MutableHandle<Value> val) {
518 const StructType& resultType = typeDef().structType();
519 MOZ_ASSERT(index <= resultType.fields_.length());
520 const FieldType& field = resultType.fields_[index];
521 uint32_t fieldOffset = resultType.fieldOffset(index);
522 StorageType ty = field.type.storageType();
523 return ToJSValue(cx, fieldOffsetToAddress(ty, fieldOffset), ty, val);
524 }
525
526 /* static */
527 void WasmStructObject::obj_trace(JSTracer* trc, JSObject* object) {
528 WasmStructObject& structObj = object->as<WasmStructObject>();
529
530 const auto& structType = structObj.typeDef().structType();
531 for (uint32_t offset : structType.inlineTraceOffsets_) {
532 AnyRef* fieldPtr =
533 reinterpret_cast<AnyRef*>(structObj.inlineData() + offset);
534 TraceManuallyBarrieredEdge(trc, fieldPtr, "wasm-struct-field");
535 }
536 for (uint32_t offset : structType.outlineTraceOffsets_) {
537 AnyRef* fieldPtr =
538 reinterpret_cast<AnyRef*>(structObj.outlineData_ + offset);
539 TraceManuallyBarrieredEdge(trc, fieldPtr, "wasm-struct-field");
540 }
541 }
542
543 /* static */
544 void WasmStructObject::obj_finalize(JS::GCContext* gcx, JSObject* object) {
545 // See corresponding comments in WasmArrayObject::obj_finalize.
546 WasmStructObject& structObj = object->as<WasmStructObject>();
547 if (structObj.outlineData_) {
548 js_free(structObj.outlineData_);
549 const TypeDef& typeDef = structObj.typeDef();
550 MOZ_ASSERT(typeDef.isStructType());
551 uint32_t totalBytes = typeDef.structType().size_;
552 uint32_t inlineBytes, outlineBytes;
553 WasmStructObject::getDataByteSizes(totalBytes, &inlineBytes, &outlineBytes);
554 MOZ_ASSERT(inlineBytes == WasmStructObject_MaxInlineBytes);
555 MOZ_ASSERT(outlineBytes > 0);
556 gcx->removeCellMemory(&structObj, outlineBytes + TrailerBlockOverhead,
557 MemoryUse::WasmTrailerBlock);
558 structObj.outlineData_ = nullptr;
559 }
560 }
561
562 /* static */
563 size_t WasmStructObject::obj_moved(JSObject* obj, JSObject* old) {
564 // See also, corresponding comments in WasmArrayObject::obj_moved.
565 if (IsInsideNursery(old)) {
566 Nursery& nursery = obj->runtimeFromMainThread()->gc.nursery();
567 WasmStructObject& structObj = obj->as<WasmStructObject>();
568 const TypeDef& typeDef = structObj.typeDef();
569 MOZ_ASSERT(typeDef.isStructType());
570 uint32_t totalBytes = typeDef.structType().size_;
571 uint32_t inlineBytes, outlineBytes;
572 WasmStructObject::getDataByteSizes(totalBytes, &inlineBytes, &outlineBytes);
573 MOZ_ASSERT(inlineBytes == WasmStructObject_MaxInlineBytes);
574 MOZ_ASSERT(outlineBytes > 0);
575 nursery.trackTrailerOnPromotion(structObj.outlineData_, obj, outlineBytes,
576 TrailerBlockOverhead,
577 MemoryUse::WasmTrailerBlock);
578 }
579
580 return 0;
581 }
582
583 void WasmStructObject::storeVal(const Val& val, uint32_t fieldIndex) {
584 const StructType& structType = typeDef().structType();
585 StorageType fieldType = structType.fields_[fieldIndex].type;
586 uint32_t fieldOffset = structType.fieldOffset(fieldIndex);
587
588 MOZ_ASSERT(fieldIndex < structType.fields_.length());
589 bool areaIsOutline;
590 uint32_t areaOffset;
591 fieldOffsetToAreaAndOffset(fieldType, fieldOffset, &areaIsOutline,
592 &areaOffset);
593
594 uint8_t* data;
595 if (areaIsOutline) {
596 data = outlineData_ + areaOffset;
597 } else {
598 data = inlineData() + areaOffset;
599 }
600
601 WriteValTo(val, fieldType, data);
602 }
603
604 static const JSClassOps WasmStructObjectOutlineClassOps = {
605 nullptr, /* addProperty */
606 nullptr, /* delProperty */
607 nullptr, /* enumerate */
608 WasmGcObject::obj_newEnumerate,
609 nullptr, /* resolve */
610 nullptr, /* mayResolve */
611 WasmStructObject::obj_finalize, /* finalize */
612 nullptr, /* call */
613 nullptr, /* construct */
614 WasmStructObject::obj_trace,
615 };
616 static const ClassExtension WasmStructObjectOutlineClassExt = {
617 WasmStructObject::obj_moved, /* objectMovedOp */
618 };
619 const JSClass WasmStructObject::classOutline_ = {
620 "WasmStructObject",
621 JSClass::NON_NATIVE | JSCLASS_DELAY_METADATA_BUILDER |
622 JSCLASS_BACKGROUND_FINALIZE | JSCLASS_SKIP_NURSERY_FINALIZE,
623 &WasmStructObjectOutlineClassOps,
624 JS_NULL_CLASS_SPEC,
625 &WasmStructObjectOutlineClassExt,
626 &WasmGcObject::objectOps_,
627 };
628
629 // Structs that only have inline data get a different class without a
630 // finalizer. This class should otherwise be identical to the class for
631 // structs with outline data.
632 static const JSClassOps WasmStructObjectInlineClassOps = {
633 nullptr, /* addProperty */
634 nullptr, /* delProperty */
635 nullptr, /* enumerate */
636 WasmGcObject::obj_newEnumerate,
637 nullptr, /* resolve */
638 nullptr, /* mayResolve */
639 nullptr, /* finalize */
640 nullptr, /* call */
641 nullptr, /* construct */
642 WasmStructObject::obj_trace,
643 };
644 static const ClassExtension WasmStructObjectInlineClassExt = {
645 nullptr, /* objectMovedOp */
646 };
647 const JSClass WasmStructObject::classInline_ = {
648 "WasmStructObject",
649 JSClass::NON_NATIVE | JSCLASS_DELAY_METADATA_BUILDER,
650 &WasmStructObjectInlineClassOps,
651 JS_NULL_CLASS_SPEC,
652 &WasmStructObjectInlineClassExt,
653 &WasmGcObject::objectOps_,
654 };