Debian Codegraph @

js/src/vm/JSObject.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 * 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 #ifndef vm_JSObject_h
8 #define vm_JSObject_h
9
10 #include "mozilla/MemoryReporting.h"
11
12 #include "jsfriendapi.h"
13
14 #include "js/friend/ErrorMessages.h" // JSErrNum
15 #include "js/GCVector.h"
16 #include "js/shadow/Zone.h" // JS::shadow::Zone
17 #include "js/Wrapper.h"
18 #include "vm/Shape.h"
19
20 namespace JS {
21 struct ClassInfo;
22 } // namespace JS
23
24 namespace js {
25
26 using PropertyDescriptorVector = JS::GCVector<JS::PropertyDescriptor>;
27 class GCMarker;
28 class JS_PUBLIC_API GenericPrinter;
29 class JSONPrinter;
30 class Nursery;
31 struct AutoEnterOOMUnsafeRegion;
32
33 namespace gc {
34 class RelocationOverlay;
35 } // namespace gc
36
37 /****************************************************************************/
38
39 class GlobalObject;
40 class NativeObject;
41 class WithEnvironmentObject;
42
43 enum class IntegrityLevel { Sealed, Frozen };
44
45 /*
46 * The NewObjectKind allows an allocation site to specify the lifetime
47 * requirements that must be fixed at allocation time.
48 */
49 enum NewObjectKind {
50 /* This is the default. Most objects are generic. */
51 GenericObject,
52
53 /*
54 * Objects which will not benefit from being allocated in the nursery
55 * (e.g. because they are known to have a long lifetime) may be allocated
56 * with this kind to place them immediately into the tenured generation.
57 */
58 TenuredObject
59 };
60
61 // Forward declarations, required for later friend declarations.
62 bool PreventExtensions(JSContext* cx, JS::HandleObject obj,
63 JS::ObjectOpResult& result);
64 bool SetImmutablePrototype(JSContext* cx, JS::HandleObject obj,
65 bool* succeeded);
66
67 } /* namespace js */
68
69 /*
70 * [SMDOC] JSObject layout
71 *
72 * A JavaScript object.
73 *
74 * This is the base class for all objects exposed to JS script (as well as some
75 * objects that are only accessed indirectly). Subclasses add additional fields
76 * and execution semantics. The runtime class of an arbitrary JSObject is
77 * identified by JSObject::getClass().
78 *
79 * All objects have a non-null Shape, stored in the cell header, which describes
80 * the current layout and set of property keys of the object.
81 *
82 * Each Shape has a pointer to a BaseShape. The BaseShape contains the object's
83 * prototype object, its class, and its realm.
84 *
85 * NOTE: Some operations can change the contents of an object (including class)
86 * in-place so avoid assuming an object with same pointer has same class
87 * as before.
88 * - JSObject::swap()
89 */
90 class JSObject
91 : public js::gc::CellWithTenuredGCPointer<js::gc::Cell, js::Shape> {
92 public:
93 // The Shape is stored in the cell header.
94 js::Shape* shape() const { return headerPtr(); }
95
96 // Like shape(), but uses getAtomic to read the header word.
97 js::Shape* shapeMaybeForwarded() const { return headerPtrAtomic(); }
98
99 #ifndef JS_64BIT
100 // Ensure fixed slots have 8-byte alignment on 32-bit platforms.
101 uint32_t padding_;
102 #endif
103
104 private:
105 friend class js::GCMarker;
106 friend class js::GlobalObject;
107 friend class js::Nursery;
108 friend class js::gc::RelocationOverlay;
109 friend bool js::PreventExtensions(JSContext* cx, JS::HandleObject obj,
110 JS::ObjectOpResult& result);
111 friend bool js::SetImmutablePrototype(JSContext* cx, JS::HandleObject obj,
112 bool* succeeded);
113
114 public:
115 const JSClass* getClass() const { return shape()->getObjectClass(); }
116 bool hasClass(const JSClass* c) const { return getClass() == c; }
117
118 js::LookupPropertyOp getOpsLookupProperty() const {
119 return getClass()->getOpsLookupProperty();
120 }
121 js::DefinePropertyOp getOpsDefineProperty() const {
122 return getClass()->getOpsDefineProperty();
123 }
124 js::HasPropertyOp getOpsHasProperty() const {
125 return getClass()->getOpsHasProperty();
126 }
127 js::GetPropertyOp getOpsGetProperty() const {
128 return getClass()->getOpsGetProperty();
129 }
130 js::SetPropertyOp getOpsSetProperty() const {
131 return getClass()->getOpsSetProperty();
132 }
133 js::GetOwnPropertyOp getOpsGetOwnPropertyDescriptor() const {
134 return getClass()->getOpsGetOwnPropertyDescriptor();
135 }
136 js::DeletePropertyOp getOpsDeleteProperty() const {
137 return getClass()->getOpsDeleteProperty();
138 }
139 js::GetElementsOp getOpsGetElements() const {
140 return getClass()->getOpsGetElements();
141 }
142 JSFunToStringOp getOpsFunToString() const {
143 return getClass()->getOpsFunToString();
144 }
145
146 JS::Compartment* compartment() const { return shape()->compartment(); }
147 JS::Compartment* maybeCompartment() const { return compartment(); }
148
149 void initShape(js::Shape* shape) {
150 // Note: use Cell::Zone() instead of zone() because zone() relies on the
151 // shape we still have to initialize.
152 MOZ_ASSERT(Cell::zone() == shape->zone());
153 initHeaderPtr(shape);
154 }
155 void setShape(js::Shape* shape) {
156 MOZ_ASSERT(maybeCCWRealm() == shape->realm());
157 setHeaderPtr(shape);
158 }
159
160 static bool setFlag(JSContext* cx, JS::HandleObject obj, js::ObjectFlag flag);
161
162 bool hasFlag(js::ObjectFlag flag) const {
163 return shape()->hasObjectFlag(flag);
164 }
165
166 bool hasAnyFlag(js::ObjectFlags flags) const {
167 return shape()->objectFlags().hasAnyFlag(flags);
168 }
169
170 // Change this object's shape for a prototype mutation.
171 //
172 // Note: the caller must ensure the object has a mutable proto, is extensible,
173 // etc.
174 static bool setProtoUnchecked(JSContext* cx, JS::HandleObject obj,
175 js::Handle<js::TaggedProto> proto);
176
177 // An object is marked IsUsedAsPrototype if it is (or was) another object's
178 // prototype. Optimization heuristics will make use of this flag.
179 //
180 // This flag is only relevant for static prototypes. Proxy traps can return
181 // objects without this flag set.
182 //
183 // NOTE: it's important to call setIsUsedAsPrototype *after* initializing the
184 // object's properties, because that avoids unnecessary shadowing checks and
185 // reshaping.
186 //
187 // See: ReshapeForProtoMutation, ReshapeForShadowedProp
188 bool isUsedAsPrototype() const {
189 return hasFlag(js::ObjectFlag::IsUsedAsPrototype);
190 }
191 static bool setIsUsedAsPrototype(JSContext* cx, JS::HandleObject obj) {
192 return setFlag(cx, obj, js::ObjectFlag::IsUsedAsPrototype);
193 }
194
195 bool useWatchtowerTestingLog() const {
196 return hasFlag(js::ObjectFlag::UseWatchtowerTestingLog);
197 }
198 static bool setUseWatchtowerTestingLog(JSContext* cx, JS::HandleObject obj) {
199 return setFlag(cx, obj, js::ObjectFlag::UseWatchtowerTestingLog);
200 }
201
202 bool isGenerationCountedGlobal() const {
203 return hasFlag(js::ObjectFlag::GenerationCountedGlobal);
204 }
205
206 bool hasFuseProperty() const {
207 return hasFlag(js::ObjectFlag::HasFuseProperty);
208 }
209 static bool setHasFuseProperty(JSContext* cx, JS::HandleObject obj) {
210 return setFlag(cx, obj, js::ObjectFlag::HasFuseProperty);
211 }
212
213 // A "qualified" varobj is the object on which "qualified" variable
214 // declarations (i.e., those defined with "var") are kept.
215 //
216 // Conceptually, when a var binding is defined, it is defined on the
217 // innermost qualified varobj on the environment chain.
218 //
219 // Function scopes (CallObjects) are qualified varobjs, and there can be
220 // no other qualified varobj that is more inner for var bindings in that
221 // function. As such, all references to local var bindings in a function
222 // may be statically bound to the function scope. This is subject to
223 // further optimization. Unaliased bindings inside functions reside
224 // entirely on the frame, not in CallObjects.
225 //
226 // Global scopes are also qualified varobjs. It is possible to statically
227 // know, for a given script, that are no more inner qualified varobjs, so
228 // free variable references can be statically bound to the global.
229 //
230 // Finally, there are non-syntactic qualified varobjs used by embedders
231 // (e.g., Gecko and XPConnect), as they often wish to run scripts under a
232 // scope that captures var bindings.
233 inline bool isQualifiedVarObj() const;
234
235 // Non-syntactic with-environment objects can be made qualified varobjs after
236 // construction. All other qualified varobjs are directly marked as such when
237 // allocating the object.
238 static inline bool setQualifiedVarObj(
239 JSContext* cx, JS::Handle<js::WithEnvironmentObject*> obj);
240
241 // An "unqualified" varobj is the object on which "unqualified"
242 // assignments (i.e., bareword assignments for which the LHS does not
243 // exist on the environment chain) are kept.
244 inline bool isUnqualifiedVarObj() const;
245
246 // Once the "invalidated teleporting" flag is set for an object, it is never
247 // cleared and it may cause the JITs to insert additional guards when
248 // accessing properties on this object. While the flag remains clear, the
249 // shape teleporting optimization can be used to avoid those extra checks.
250 //
251 // The flag is set on the object if either:
252 //
253 // * Its own proto was mutated or it was on the proto chain of an object that
254 // had its proto mutated.
255 //
256 // * It was on the proto chain of an object that started shadowing a property
257 // on this object.
258 //
259 // See:
260 // - ReshapeForProtoMutation
261 // - ReshapeForShadowedProp
262 // - ProtoChainSupportsTeleporting
263 inline bool hasInvalidatedTeleporting() const;
264 static bool setInvalidatedTeleporting(JSContext* cx, JS::HandleObject obj) {
265 MOZ_ASSERT(obj->isUsedAsPrototype());
266 MOZ_ASSERT(obj->hasStaticPrototype(),
267 "teleporting as a concept is only applicable to static "
268 "(not dynamically-computed) prototypes");
269 return setFlag(cx, obj, js::ObjectFlag::InvalidatedTeleporting);
270 }
271
272 [[nodiscard]] static bool reshapeForTeleporting(JSContext* cx,
273 JS::HandleObject obj);
274
275 /*
276 * Whether there may be "interesting symbol" properties on this object. An
277 * interesting symbol is a symbol for which symbol->isInterestingSymbol()
278 * returns true.
279 */
280 MOZ_ALWAYS_INLINE bool maybeHasInterestingSymbolProperty() const;
281
282 inline bool needsProxyGetSetResultValidation() const;
283
284 /* GC support. */
285
286 void traceChildren(JSTracer* trc);
287
288 void fixupAfterMovingGC() {}
289
290 static const JS::TraceKind TraceKind = JS::TraceKind::Object;
291
292 static constexpr size_t thingSize(js::gc::AllocKind kind);
293
294 MOZ_ALWAYS_INLINE JS::Zone* zone() const {
295 MOZ_ASSERT_IF(!isTenured(), nurseryZone() == shape()->zone());
296 return shape()->zone();
297 }
298 MOZ_ALWAYS_INLINE JS::shadow::Zone* shadowZone() const {
299 return JS::shadow::Zone::from(zone());
300 }
301 MOZ_ALWAYS_INLINE JS::Zone* zoneFromAnyThread() const {
302 MOZ_ASSERT_IF(!isTenured(),
303 nurseryZoneFromAnyThread() == shape()->zoneFromAnyThread());
304 return shape()->zoneFromAnyThread();
305 }
306 MOZ_ALWAYS_INLINE JS::shadow::Zone* shadowZoneFromAnyThread() const {
307 return JS::shadow::Zone::from(zoneFromAnyThread());
308 }
309 static MOZ_ALWAYS_INLINE void postWriteBarrier(void* cellp, JSObject* prev,
310 JSObject* next) {
311 js::gc::PostWriteBarrierImpl<JSObject>(cellp, prev, next);
312 }
313
314 js::gc::AllocKind allocKind() const;
315
316 /* Return the allocKind we would use if we were to tenure this object. */
317 js::gc::AllocKind allocKindForTenure(const js::Nursery& nursery) const;
318
319 bool canHaveFixedElements() const;
320
321 size_t tenuredSizeOfThis() const {
322 MOZ_ASSERT(isTenured());
323 return js::gc::Arena::thingSize(asTenured().getAllocKind());
324 }
325
326 void addSizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf,
327 JS::ClassInfo* info,
328 JS::RuntimeSizes* runtimeSizes);
329
330 // We can only use addSizeOfExcludingThis on tenured objects: it assumes it
331 // can apply mallocSizeOf to bits and pieces of the object, whereas objects
332 // in the nursery may have those bits and pieces allocated in the nursery
333 // along with them, and are not each their own malloc blocks.
334 size_t sizeOfIncludingThisInNursery() const;
335
336 #ifdef DEBUG
337 static void debugCheckNewObject(js::Shape* shape, js::gc::AllocKind allocKind,
338 js::gc::Heap heap);
339 #else
340 static void debugCheckNewObject(js::Shape* shape, js::gc::AllocKind allocKind,
341 js::gc::Heap heap) {}
342 #endif
343
344 /*
345 * We permit proxies to dynamically compute their prototype if desired.
346 * (Not all proxies will so desire: in particular, most DOM proxies can
347 * track their prototype with a single, nullable JSObject*.) If a proxy
348 * so desires, we store (JSObject*)0x1 in the proto field of the object's
349 * group.
350 *
351 * We offer three ways to get an object's prototype:
352 *
353 * 1. obj->staticPrototype() returns the prototype, but it asserts if obj
354 * is a proxy, and the proxy has opted to dynamically compute its
355 * prototype using a getPrototype() handler.
356 * 2. obj->taggedProto() returns a TaggedProto, which can be tested to
357 * check if the proto is an object, nullptr, or lazily computed.
358 * 3. js::GetPrototype(cx, obj, &proto) computes the proto of an object.
359 * If obj is a proxy with dynamically-computed prototype, this code may
360 * perform arbitrary behavior (allocation, GC, run JS) while computing
361 * the proto.
362 */
363
364 js::TaggedProto taggedProto() const { return shape()->proto(); }
365
366 bool uninlinedIsProxyObject() const;
367
368 JSObject* staticPrototype() const {
369 MOZ_ASSERT(hasStaticPrototype());
370 return taggedProto().toObjectOrNull();
371 }
372
373 // Normal objects and a subset of proxies have an uninteresting, static
374 // (albeit perhaps mutable) [[Prototype]]. For such objects the
375 // [[Prototype]] is just a value returned when needed for accesses, or
376 // modified in response to requests. These objects store the
377 // [[Prototype]] directly within |obj->group()|.
378 bool hasStaticPrototype() const { return !hasDynamicPrototype(); }
379
380 // The remaining proxies have a [[Prototype]] requiring dynamic computation
381 // for every access, going through the proxy handler {get,set}Prototype and
382 // setImmutablePrototype methods. (Wrappers particularly use this to keep
383 // the wrapper/wrappee [[Prototype]]s consistent.)
384 bool hasDynamicPrototype() const {
385 bool dynamic = taggedProto().isDynamic();
386 MOZ_ASSERT_IF(dynamic, uninlinedIsProxyObject());
387 return dynamic;
388 }
389
390 // True iff this object's [[Prototype]] is immutable. Must be called only
391 // on objects with a static [[Prototype]]!
392 inline bool staticPrototypeIsImmutable() const;
393
394 /*
395 * Environment chains.
396 *
397 * The environment chain of an object is the link in the search path when
398 * a script does a name lookup on an environment object. For JS internal
399 * environment objects --- Call, LexicalEnvironment, and WithEnvironment
400 * --- the chain is stored in the first fixed slot of the object. For
401 * other environment objects, the chain goes directly to the global.
402 *
403 * In code which is not marked hasNonSyntacticScope, environment chains
404 * can contain only syntactic environment objects (see
405 * IsSyntacticEnvironment) with a global object at the root as the
406 * environment of the outermost non-function script. In
407 * hasNonSyntacticScope code, the environment of the outermost
408 * non-function script might not be a global object, and can have a mix of
409 * other objects above it before the global object is reached.
410 */
411
412 /*
413 * Get the enclosing environment of an object. When called on a
414 * non-EnvironmentObject, this will just be the global (the name
415 * "enclosing environment" still applies in this situation because
416 * non-EnvironmentObjects can be on the environment chain).
417 */
418 inline JSObject* enclosingEnvironment() const;
419
420 // Cross-compartment wrappers are not associated with a single realm/global,
421 // so these methods assert the object is not a CCW.
422 inline js::GlobalObject& nonCCWGlobal() const;
423
424 JS::Realm* nonCCWRealm() const {
425 MOZ_ASSERT(!js::UninlinedIsCrossCompartmentWrapper(this));
426 return shape()->realm();
427 }
428 bool hasSameRealmAs(JSContext* cx) const;
429
430 // Returns the object's realm even if the object is a CCW (be careful, in
431 // this case the realm is not very meaningful because wrappers are shared by
432 // all realms in the compartment).
433 JS::Realm* maybeCCWRealm() const { return shape()->realm(); }
434
435 /*
436 * ES5 meta-object properties and operations.
437 */
438
439 public:
440 // Indicates whether a non-proxy is extensible. Don't call on proxies!
441 // This method really shouldn't exist -- but there are a few internal
442 // places that want it (JITs and the like), and it'd be a pain to mark them
443 // all as friends.
444 inline bool nonProxyIsExtensible() const;
445 bool uninlinedNonProxyIsExtensible() const;
446
447 public:
448 /*
449 * Back to generic stuff.
450 */
451 MOZ_ALWAYS_INLINE bool isCallable() const;
452 MOZ_ALWAYS_INLINE bool isConstructor() const;
453 MOZ_ALWAYS_INLINE JSNative callHook() const;
454 MOZ_ALWAYS_INLINE JSNative constructHook() const;
455
456 bool isBackgroundFinalized() const;
457
458 MOZ_ALWAYS_INLINE void finalize(JS::GCContext* gcx);
459
460 public:
461 static bool nonNativeSetProperty(JSContext* cx, js::HandleObject obj,
462 js::HandleId id, js::HandleValue v,
463 js::HandleValue receiver,
464 JS::ObjectOpResult& result);
465 static bool nonNativeSetElement(JSContext* cx, js::HandleObject obj,
466 uint32_t index, js::HandleValue v,
467 js::HandleValue receiver,
468 JS::ObjectOpResult& result);
469
470 static void swap(JSContext* cx, JS::HandleObject a, JS::HandleObject b,
471 js::AutoEnterOOMUnsafeRegion& oomUnsafe);
472
473 /*
474 * In addition to the generic object interface provided by JSObject,
475 * specific types of objects may provide additional operations. To access,
476 * these addition operations, callers should use the pattern:
477 *
478 * if (obj.is<XObject>()) {
479 * XObject& x = obj.as<XObject>();
480 * x.foo();
481 * }
482 *
483 * These XObject classes form a hierarchy. For example, for a cloned block
484 * object, the following predicates are true: is<ClonedBlockObject>,
485 * is<NestedScopeObject> and is<ScopeObject>. Each of these has a
486 * respective class that derives and adds operations.
487 *
488 * A class XObject is defined in a vm/XObject{.h, .cpp, -inl.h} file
489 * triplet (along with any class YObject that derives XObject).
490 *
491 * Note that X represents a low-level representation and does not query the
492 * [[Class]] property of object defined by the spec: use |JS::GetBuiltinClass|
493 * for this.
494 */
495
496 template <class T>
497 inline bool is() const {
498 return getClass() == &T::class_;
499 }
500
501 template <class T>
502 T& as() {
503 MOZ_ASSERT(this->is<T>());
504 return *static_cast<T*>(this);
505 }
506
507 template <class T>
508 const T& as() const {
509 MOZ_ASSERT(this->is<T>());
510 return *static_cast<const T*>(this);
511 }
512
513 /*
514 * True if either this or CheckedUnwrap(this) is an object of class T.
515 * (Only two objects are checked, regardless of how many wrappers there
516 * are.)
517 *
518 * /!\ Note: This can be true at one point, but false later for the same
519 * object, thanks to js::NukeCrossCompartmentWrapper and friends.
520 */
521 template <class T>
522 bool canUnwrapAs();
523
524 /*
525 * Unwrap and downcast to class T.
526 *
527 * Precondition: `this->canUnwrapAs<T>()`. Note that it's not enough to
528 * have checked this at some point in the past; if there's any doubt as to
529 * whether js::Nuke* could have been called in the meantime, check again.
530 */
531 template <class T>
532 T& unwrapAs();
533
534 /*
535 * Tries to unwrap and downcast to class T. Returns nullptr if (and only if) a
536 * wrapper with a security policy is involved. Crashes in all builds if the
537 * (possibly unwrapped) object is not of class T (for example, because it's a
538 * dead wrapper).
539 */
540 template <class T>
541 inline T* maybeUnwrapAs();
542
543 /*
544 * Tries to unwrap and downcast to an object with class |clasp|. Returns
545 * nullptr if (and only if) a wrapper with a security policy is involved.
546 * Crashes in all builds if the (possibly unwrapped) object doesn't have class
547 * |clasp| (for example, because it's a dead wrapper).
548 */
549 inline JSObject* maybeUnwrapAs(const JSClass* clasp);
550
551 /*
552 * Tries to unwrap and downcast to class T. Returns nullptr if a wrapper with
553 * a security policy is involved or if the object does not have class T.
554 */
555 template <class T>
556 T* maybeUnwrapIf();
557
558 #if defined(DEBUG) || defined(JS_JITSPEW)
559 void dump() const;
560 void dump(js::GenericPrinter& out) const;
561 void dump(js::JSONPrinter& json) const;
562
563 void dumpFields(js::JSONPrinter& json) const;
564 void dumpStringContent(js::GenericPrinter& out) const;
565 #endif
566
567 // Maximum size in bytes of a JSObject.
568 #ifdef JS_64BIT
569 static constexpr size_t MAX_BYTE_SIZE =
570 3 * sizeof(void*) + 16 * sizeof(JS::Value);
571 #else
572 static constexpr size_t MAX_BYTE_SIZE =
573 4 * sizeof(void*) + 16 * sizeof(JS::Value);
574 #endif
575
576 protected:
577 // JIT Accessors.
578 //
579 // To help avoid writing Spectre-unsafe code, we only allow MacroAssembler
580 // to call the method below.
581 friend class js::jit::MacroAssembler;
582
583 static constexpr size_t offsetOfShape() { return offsetOfHeaderPtr(); }
584
585 private:
586 JSObject(const JSObject& other) = delete;
587 void operator=(const JSObject& other) = delete;
588
589 protected:
590 // For the allocator only, to be used with placement new.
591 friend class js::gc::GCRuntime;
592 JSObject() = default;
593 };
594
595 template <>
596 inline bool JSObject::is<JSObject>() const {
597 return true;
598 }
599
600 template <typename Wrapper>
601 template <typename U>
602 MOZ_ALWAYS_INLINE JS::Handle<U*> js::RootedOperations<JSObject*, Wrapper>::as()
603 const {
604 const Wrapper& self = *static_cast<const Wrapper*>(this);
605 MOZ_ASSERT(self->template is<U>());
606 return Handle<U*>::fromMarkedLocation(
607 reinterpret_cast<U* const*>(self.address()));
608 }
609
610 template <typename Wrapper>
611 template <class U>
612 MOZ_ALWAYS_INLINE JS::Handle<U*> js::HandleOperations<JSObject*, Wrapper>::as()
613 const {
614 const JS::Handle<JSObject*>& self =
615 *static_cast<const JS::Handle<JSObject*>*>(this);
616 MOZ_ASSERT(self->template is<U>());
617 return Handle<U*>::fromMarkedLocation(
618 reinterpret_cast<U* const*>(self.address()));
619 }
620
621 template <class T>
622 bool JSObject::canUnwrapAs() {
623 static_assert(!std::is_convertible_v<T*, js::Wrapper*>,
624 "T can't be a Wrapper type; this function discards wrappers");
625
626 if (is<T>()) {
627 return true;
628 }
629 JSObject* obj = js::CheckedUnwrapStatic(this);
630 return obj && obj->is<T>();
631 }
632
633 template <class T>
634 T& JSObject::unwrapAs() {
635 static_assert(!std::is_convertible_v<T*, js::Wrapper*>,
636 "T can't be a Wrapper type; this function discards wrappers");
637
638 if (is<T>()) {
639 return as<T>();
640 }
641
642 // Since the caller just called canUnwrapAs<T>(), which does a
643 // CheckedUnwrap, this does not need to repeat the security check.
644 JSObject* unwrapped = js::UncheckedUnwrap(this);
645 MOZ_ASSERT(js::CheckedUnwrapStatic(this) == unwrapped,
646 "check that the security check we skipped really is redundant");
647 return unwrapped->as<T>();
648 }
649
650 template <class T>
651 inline T* JSObject::maybeUnwrapAs() {
652 static_assert(!std::is_convertible_v<T*, js::Wrapper*>,
653 "T can't be a Wrapper type; this function discards wrappers");
654
655 if (is<T>()) {
656 return &as<T>();
657 }
658
659 JSObject* unwrapped = js::CheckedUnwrapStatic(this);
660 if (!unwrapped) {
661 return nullptr;
662 }
663
664 if (MOZ_LIKELY(unwrapped->is<T>())) {
665 return &unwrapped->as<T>();
666 }
667
668 MOZ_CRASH("Invalid object. Dead wrapper?");
669 }
670
671 inline JSObject* JSObject::maybeUnwrapAs(const JSClass* clasp) {
672 if (hasClass(clasp)) {
673 return this;
674 }
675
676 JSObject* unwrapped = js::CheckedUnwrapStatic(this);
677 if (!unwrapped) {
678 return nullptr;
679 }
680
681 if (MOZ_LIKELY(unwrapped->hasClass(clasp))) {
682 return unwrapped;
683 }
684
685 MOZ_CRASH("Invalid object. Dead wrapper?");
686 }
687
688 template <class T>
689 T* JSObject::maybeUnwrapIf() {
690 static_assert(!std::is_convertible_v<T*, js::Wrapper*>,
691 "T can't be a Wrapper type; this function discards wrappers");
692
693 if (is<T>()) {
694 return &as<T>();
695 }
696
697 JSObject* unwrapped = js::CheckedUnwrapStatic(this);
698 return (unwrapped && unwrapped->is<T>()) ? &unwrapped->as<T>() : nullptr;
699 }
700
701 /*
702 * The only sensible way to compare JSObject with == is by identity. We use
703 * const& instead of * as a syntactic way to assert non-null. This leads to an
704 * abundance of address-of operators to identity. Hence this overload.
705 */
706 static MOZ_ALWAYS_INLINE bool operator==(const JSObject& lhs,
707 const JSObject& rhs) {
708 return &lhs == &rhs;
709 }
710
711 static MOZ_ALWAYS_INLINE bool operator!=(const JSObject& lhs,
712 const JSObject& rhs) {
713 return &lhs != &rhs;
714 }
715
716 // Size of the various GC thing allocation sizes used for objects.
717 struct JSObject_Slots0 : JSObject {
718 void* data[2];
719 };
720 struct JSObject_Slots2 : JSObject {
721 void* data[2];
722 js::Value fslots[2];
723 };
724 struct JSObject_Slots4 : JSObject {
725 void* data[2];
726 js::Value fslots[4];
727 };
728 struct JSObject_Slots7 : JSObject {
729 // Only used for extended functions which are required to have exactly seven
730 // fixed slots due to JIT assumptions.
731 void* data[2];
732 js::Value fslots[7];
733 };
734 struct JSObject_Slots8 : JSObject {
735 void* data[2];
736 js::Value fslots[8];
737 };
738 struct JSObject_Slots12 : JSObject {
739 void* data[2];
740 js::Value fslots[12];
741 };
742 struct JSObject_Slots16 : JSObject {
743 void* data[2];
744 js::Value fslots[16];
745 };
746
747 /* static */
748 constexpr size_t JSObject::thingSize(js::gc::AllocKind kind) {
749 MOZ_ASSERT(IsObjectAllocKind(kind));
750 constexpr uint8_t objectSizes[] = {
751 #define EXPAND_OJBECT_SIZE(_1, _2, _3, sizedType, _4, _5, _6) sizeof(sizedType),
752 FOR_EACH_OBJECT_ALLOCKIND(EXPAND_OJBECT_SIZE)};
753 return objectSizes[size_t(kind)];
754 }
755
756 namespace js {
757
758 // Returns true if object may possibly use JSObject::swap. The JITs may better
759 // optimize objects that can never swap (and thus change their type).
760 //
761 // If ObjectMayBeSwapped is false, it is safe to guard on pointer identity to
762 // test immutable features of the object. For example, the target of a
763 // JSFunction will not change. Note: the object can still be moved by GC.
764 extern bool ObjectMayBeSwapped(const JSObject* obj);
765
766 extern bool DefineFunctions(JSContext* cx, HandleObject obj,
767 const JSFunctionSpec* fs);
768
769 /* ES6 draft rev 36 (2015 March 17) 7.1.1 ToPrimitive(vp[, preferredType]) */
770 extern bool ToPrimitiveSlow(JSContext* cx, JSType hint, MutableHandleValue vp);
771
772 inline bool ToPrimitive(JSContext* cx, MutableHandleValue vp) {
773 if (vp.isPrimitive()) {
774 return true;
775 }
776 return ToPrimitiveSlow(cx, JSTYPE_UNDEFINED, vp);
777 }
778
779 inline bool ToPrimitive(JSContext* cx, JSType preferredType,
780 MutableHandleValue vp) {
781 if (vp.isPrimitive()) {
782 return true;
783 }
784 return ToPrimitiveSlow(cx, preferredType, vp);
785 }
786
787 /*
788 * toString support. (This isn't called GetClassName because there's a macro in
789 * <windows.h> with that name.)
790 */
791 MOZ_ALWAYS_INLINE const char* GetObjectClassName(JSContext* cx,
792 HandleObject obj);
793
794 } /* namespace js */
795
796 namespace js {
797
798 // ES6 9.1.15 GetPrototypeFromConstructor.
799 extern bool GetPrototypeFromConstructor(JSContext* cx,
800 js::HandleObject newTarget,
801 JSProtoKey intrinsicDefaultProto,
802 js::MutableHandleObject proto);
803
804 // https://tc39.github.io/ecma262/#sec-getprototypefromconstructor
805 //
806 // Determine which [[Prototype]] to use when creating a new object using a
807 // builtin constructor.
808 //
809 // This sets `proto` to `nullptr` to mean "the builtin prototype object for
810 // this type in the current realm", the common case.
811 //
812 // We could set it to `cx->global()->getOrCreatePrototype(protoKey)`, but
813 // nullptr gets a fast path in e.g. js::NewObjectWithClassProtoCommon.
814 //
815 // intrinsicDefaultProto can be JSProto_Null if there's no appropriate
816 // JSProtoKey enum; but we then select the wrong prototype object in a
817 // multi-realm corner case (see bug 1515167).
818 MOZ_ALWAYS_INLINE bool GetPrototypeFromBuiltinConstructor(
819 JSContext* cx, const CallArgs& args, JSProtoKey intrinsicDefaultProto,
820 js::MutableHandleObject proto) {
821 // We can skip the "prototype" lookup in the two common cases:
822 // 1. Builtin constructor called without `new`, as in `obj = Object();`.
823 // 2. Builtin constructor called with `new`, as in `obj = new Object();`.
824 //
825 // Cases that can't take the fast path include `new MySubclassOfObject()`,
826 // `new otherGlobal.Object()`, and `Reflect.construct(Object, [], Date)`.
827 if (!args.isConstructing() ||
828 &args.newTarget().toObject() == &args.callee()) {
829 MOZ_ASSERT(args.callee().hasSameRealmAs(cx));
830 proto.set(nullptr);
831 return true;
832 }
833
834 // We're calling this constructor from a derived class, retrieve the
835 // actual prototype from newTarget.
836 RootedObject newTarget(cx, &args.newTarget().toObject());
837 return GetPrototypeFromConstructor(cx, newTarget, intrinsicDefaultProto,
838 proto);
839 }
840
841 /* ES6 draft rev 32 (2015 Feb 2) 6.2.4.5 ToPropertyDescriptor(Obj) */
842 bool ToPropertyDescriptor(JSContext* cx, HandleValue descval,
843 bool checkAccessors,
844 MutableHandle<JS::PropertyDescriptor> desc);
845
846 /*
847 * Throw a TypeError if desc.getter() or setter() is not
848 * callable. This performs exactly the checks omitted by ToPropertyDescriptor
849 * when checkAccessors is false.
850 */
851 Result<> CheckPropertyDescriptorAccessors(JSContext* cx,
852 Handle<JS::PropertyDescriptor> desc);
853
854 void CompletePropertyDescriptor(MutableHandle<JS::PropertyDescriptor> desc);
855
856 /*
857 * Read property descriptors from props, as for Object.defineProperties. See
858 * ES5 15.2.3.7 steps 3-5.
859 */
860 extern bool ReadPropertyDescriptors(
861 JSContext* cx, HandleObject props, bool checkAccessors,
862 MutableHandleIdVector ids, MutableHandle<PropertyDescriptorVector> descs);
863
864 /* Read the name using a dynamic lookup on the envChain. */
865 extern bool LookupName(JSContext* cx, Handle<PropertyName*> name,
866 HandleObject envChain, MutableHandleObject objp,
867 MutableHandleObject pobjp, PropertyResult* propp);
868
869 extern bool LookupNameNoGC(JSContext* cx, PropertyName* name,
870 JSObject* envChain, NativeObject** pobjp,
871 PropertyResult* propp);
872
873 /*
874 * Like LookupName except returns the global object if 'name' is not found in
875 * any preceding scope.
876 *
877 * Additionally, pobjp and propp are not needed by callers so they are not
878 * returned.
879 */
880 extern JSObject* LookupNameWithGlobalDefault(JSContext* cx,
881 Handle<PropertyName*> name,
882 HandleObject envChain);
883
884 /*
885 * Like LookupName except returns the unqualified var object if 'name' is not
886 * found in any preceding scope. Normally the unqualified var object is the
887 * global. If the value for the name in the looked-up scope is an uninitialized
888 * lexical, a RuntimeLexicalErrorObject is returned.
889 *
890 * Additionally, pobjp is not needed by callers so it is not returned.
891 */
892 extern JSObject* LookupNameUnqualified(JSContext* cx,
893 Handle<PropertyName*> name,
894 HandleObject envChain);
895
896 } // namespace js
897
898 namespace js {
899
900 /*
901 * Family of Pure property lookup functions. The bool return does NOT have the
902 * standard SpiderMonkey semantics. The return value means "can this operation
903 * be performed and produce a valid result without any side effects?". If any of
904 * these return true, then the outparam can be inspected to determine the
905 * result.
906 */
907
908 bool LookupPropertyPure(JSContext* cx, JSObject* obj, jsid id,
909 NativeObject** objp, PropertyResult* propp);
910
911 bool LookupOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id,
912 PropertyResult* propp);
913
914 bool GetPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp);
915
916 bool GetOwnPropertyPure(JSContext* cx, JSObject* obj, jsid id, Value* vp,
917 bool* found);
918
919 bool GetGetterPure(JSContext* cx, JSObject* obj, jsid id, JSFunction** fp);
920
921 /*
922 * Like JS::FromPropertyDescriptor, but ignore desc.object() and always set vp
923 * to an object on success.
924 *
925 * Use JS::FromPropertyDescriptor for getOwnPropertyDescriptor, since
926 * desc.object() is used to indicate whether a result was found or not. Use
927 * this instead for defineProperty: it would be senseless to define a "missing"
928 * property.
929 */
930 extern bool FromPropertyDescriptorToObject(JSContext* cx,
931 Handle<JS::PropertyDescriptor> desc,
932 MutableHandleValue vp);
933
934 // obj is a JSObject*, but we root it immediately up front. We do it
935 // that way because we need a Rooted temporary in this method anyway.
936 extern bool IsPrototypeOf(JSContext* cx, HandleObject protoObj, JSObject* obj,
937 bool* result);
938
939 /* Wrap boolean, number or string as Boolean, Number or String object. */
940 extern JSObject* PrimitiveToObject(JSContext* cx, const Value& v);
941 extern JSProtoKey PrimitiveToProtoKey(JSContext* cx, const Value& v);
942
943 } /* namespace js */
944
945 namespace js {
946
947 JSObject* ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
948 int valIndex, HandleId key);
949 JSObject* ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
950 int valIndex,
951 Handle<PropertyName*> key);
952 JSObject* ToObjectSlowForPropertyAccess(JSContext* cx, JS::HandleValue val,
953 int valIndex, HandleValue keyValue);
954
955 MOZ_ALWAYS_INLINE JSObject* ToObjectFromStackForPropertyAccess(JSContext* cx,
956 HandleValue vp,
957 int vpIndex,
958 HandleId key) {
959 if (vp.isObject()) {
960 return &vp.toObject();
961 }
962 return js::ToObjectSlowForPropertyAccess(cx, vp, vpIndex, key);
963 }
964 MOZ_ALWAYS_INLINE JSObject* ToObjectFromStackForPropertyAccess(
965 JSContext* cx, HandleValue vp, int vpIndex, Handle<PropertyName*> key) {
966 if (vp.isObject()) {
967 return &vp.toObject();
968 }
969 return js::ToObjectSlowForPropertyAccess(cx, vp, vpIndex, key);
970 }
971 MOZ_ALWAYS_INLINE JSObject* ToObjectFromStackForPropertyAccess(
972 JSContext* cx, HandleValue vp, int vpIndex, HandleValue key) {
973 if (vp.isObject()) {
974 return &vp.toObject();
975 }
976 return js::ToObjectSlowForPropertyAccess(cx, vp, vpIndex, key);
977 }
978
979 /*
980 * Report a TypeError: "so-and-so is not an object".
981 * Using NotNullObject is usually less code.
982 */
983 extern void ReportNotObject(JSContext* cx, const Value& v);
984
985 inline JSObject* RequireObject(JSContext* cx, HandleValue v) {
986 if (v.isObject()) {
987 return &v.toObject();
988 }
989 ReportNotObject(cx, v);
990 return nullptr;
991 }
992
993 /*
994 * Report a TypeError: "SOMETHING must be an object, got VALUE".
995 * Using NotNullObject is usually less code.
996 *
997 * By default this function will attempt to report the expression which computed
998 * the value which given as argument. This can be disabled by using
999 * JSDVG_IGNORE_STACK.
1000 */
1001 extern void ReportNotObject(JSContext* cx, JSErrNum err, int spindex,
1002 HandleValue v);
1003
1004 inline JSObject* RequireObject(JSContext* cx, JSErrNum err, int spindex,
1005 HandleValue v) {
1006 if (v.isObject()) {
1007 return &v.toObject();
1008 }
1009 ReportNotObject(cx, err, spindex, v);
1010 return nullptr;
1011 }
1012
1013 extern void ReportNotObject(JSContext* cx, JSErrNum err, HandleValue v);
1014
1015 inline JSObject* RequireObject(JSContext* cx, JSErrNum err, HandleValue v) {
1016 if (v.isObject()) {
1017 return &v.toObject();
1018 }
1019 ReportNotObject(cx, err, v);
1020 return nullptr;
1021 }
1022
1023 /*
1024 * Report a TypeError: "N-th argument of FUN must be an object, got VALUE".
1025 * Using NotNullObjectArg is usually less code.
1026 */
1027 extern void ReportNotObjectArg(JSContext* cx, const char* nth, const char* fun,
1028 HandleValue v);
1029
1030 inline JSObject* RequireObjectArg(JSContext* cx, const char* nth,
1031 const char* fun, HandleValue v) {
1032 if (v.isObject()) {
1033 return &v.toObject();
1034 }
1035 ReportNotObjectArg(cx, nth, fun, v);
1036 return nullptr;
1037 }
1038
1039 extern bool GetFirstArgumentAsObject(JSContext* cx, const CallArgs& args,
1040 const char* method,
1041 MutableHandleObject objp);
1042
1043 /* Helper for throwing, always returns false. */
1044 extern bool Throw(JSContext* cx, HandleId id, unsigned errorNumber,
1045 const char* details = nullptr);
1046
1047 /*
1048 * ES6 rev 29 (6 Dec 2014) 7.3.13. Mark obj as non-extensible, and adjust each
1049 * of obj's own properties' attributes appropriately: each property becomes
1050 * non-configurable, and if level == Frozen, data properties become
1051 * non-writable as well.
1052 */
1053 extern bool SetIntegrityLevel(JSContext* cx, HandleObject obj,
1054 IntegrityLevel level);
1055
1056 inline bool FreezeObject(JSContext* cx, HandleObject obj) {
1057 return SetIntegrityLevel(cx, obj, IntegrityLevel::Frozen);
1058 }
1059
1060 /*
1061 * ES6 rev 29 (6 Dec 2014) 7.3.14. Code shared by Object.isSealed and
1062 * Object.isFrozen.
1063 */
1064 extern bool TestIntegrityLevel(JSContext* cx, HandleObject obj,
1065 IntegrityLevel level, bool* resultp);
1066
1067 [[nodiscard]] extern JSObject* SpeciesConstructor(
1068 JSContext* cx, HandleObject obj, HandleObject defaultCtor,
1069 bool (*isDefaultSpecies)(JSContext*, JSFunction*));
1070
1071 [[nodiscard]] extern JSObject* SpeciesConstructor(
1072 JSContext* cx, HandleObject obj, JSProtoKey ctorKey,
1073 bool (*isDefaultSpecies)(JSContext*, JSFunction*));
1074
1075 extern bool GetObjectFromHostDefinedData(JSContext* cx,
1076 MutableHandleObject obj);
1077
1078 #ifdef DEBUG
1079 inline bool IsObjectValueInCompartment(const Value& v, JS::Compartment* comp) {
1080 if (!v.isObject()) {
1081 return true;
1082 }
1083 return v.toObject().compartment() == comp;
1084 }
1085 #endif
1086
1087 /*
1088 * A generic trace hook that calls the object's 'trace' method.
1089 *
1090 * If you are introducing a new JSObject subclass, MyObject, that needs a custom
1091 * JSClassOps::trace function, it's often helpful to write `trace` as a
1092 * non-static member function, since `this` will the correct type. In this case,
1093 * you can use `CallTraceMethod<MyObject>` as your JSClassOps::trace value.
1094 */
1095 template <typename ObjectSubclass>
1096 void CallTraceMethod(JSTracer* trc, JSObject* obj) {
1097 obj->as<ObjectSubclass>().trace(trc);
1098 }
1099
1100 #ifdef JS_HAS_CTYPES
1101
1102 namespace ctypes {
1103
1104 extern size_t SizeOfDataIfCDataObject(mozilla::MallocSizeOf mallocSizeOf,
1105 JSObject* obj);
1106
1107 } // namespace ctypes
1108
1109 #endif
1110
1111 #ifdef DEBUG
1112 void AssertJSClassInvariants(const JSClass* clasp);
1113 #endif
1114
1115 } /* namespace js */
1116
1117 #endif /* vm_JSObject_h */