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 file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_dom_DOMJSClass_h
8 #define mozilla_dom_DOMJSClass_h
11 #include "jsfriendapi.h"
12 #include "js/Object.h" // JS::GetClass, JS::GetReservedSlot
13 #include "js/Wrapper.h"
14 #include "mozilla/Assertions.h"
15 #include "mozilla/Attributes.h"
16 #include "mozilla/Likely.h"
18 #include "mozilla/dom/PrototypeList.h" // auto-generated
19 #include "mozilla/dom/WebIDLPrefs.h" // auto-generated
21 class nsCycleCollectionParticipant
;
23 struct JSFunctionSpec
;
24 struct JSPropertySpec
;
25 struct JSStructuredCloneReader
;
26 struct JSStructuredCloneWriter
;
27 class nsIGlobalObject
;
29 // All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
30 #define DOM_PROTOTYPE_SLOT JSCLASS_GLOBAL_SLOT_COUNT
32 // Keep this count up to date with any extra global slots added above.
33 #define DOM_GLOBAL_SLOTS 1
35 // We use these flag bits for the new bindings.
36 #define JSCLASS_DOM_GLOBAL JSCLASS_USERBIT1
37 #define JSCLASS_IS_DOMIFACEANDPROTOJSCLASS JSCLASS_USERBIT2
43 * Returns true if code running in the given JSContext is allowed to access
44 * [SecureContext] API on the given JSObject.
46 * [SecureContext] API exposure is restricted to use by code in a Secure
49 * https://w3c.github.io/webappsec-secure-contexts/
51 * Since we want [SecureContext] exposure to depend on the privileges of the
52 * running code (rather than the privileges of an object's creator), this
53 * function checks to see whether the given JSContext's Realm is flagged
54 * as a Secure Context. That allows us to make sure that system principal code
55 * (which is marked as a Secure Context) can access Secure Context API on an
56 * object in a different realm, regardless of whether the other realm is a
57 * Secure Context or not.
59 * Checking the JSContext's Realm doesn't work for expanded principal
60 * globals accessing a Secure Context web page though (e.g. those used by frame
61 * scripts). To handle that we fall back to checking whether the JSObject came
62 * from a Secure Context.
64 * Note: We'd prefer this function to live in BindingUtils.h, but we need to
65 * call it in this header, and BindingUtils.h includes us (i.e. we'd have a
66 * circular dependency between headers if it lived there).
68 inline bool IsSecureContextOrObjectIsFromSecureContext(JSContext
* aCx
,
70 MOZ_ASSERT(!js::IsWrapper(aObj
));
71 return JS::GetIsSecureContext(js::GetContextRealm(aCx
)) ||
72 JS::GetIsSecureContext(js::GetNonCCWObjectRealm(aObj
));
75 typedef bool (*ResolveOwnProperty
)(
76 JSContext
* cx
, JS::Handle
<JSObject
*> wrapper
, JS::Handle
<JSObject
*> obj
,
78 JS::MutableHandle
<mozilla::Maybe
<JS::PropertyDescriptor
>> desc
);
80 typedef bool (*EnumerateOwnProperties
)(JSContext
* cx
,
81 JS::Handle
<JSObject
*> wrapper
,
82 JS::Handle
<JSObject
*> obj
,
83 JS::MutableHandleVector
<jsid
> props
);
85 typedef bool (*DeleteNamedProperty
)(JSContext
* cx
,
86 JS::Handle
<JSObject
*> wrapper
,
87 JS::Handle
<JSObject
*> obj
,
89 JS::ObjectOpResult
& opresult
);
91 // Returns true if the given global is of a type whose bit is set in
92 // aNonExposedGlobals.
93 bool IsNonExposedGlobal(JSContext
* aCx
, JSObject
* aGlobal
,
94 uint32_t aNonExposedGlobals
);
101 typedef bool (*PropertyEnabled
)(JSContext
* cx
, JSObject
* global
);
103 namespace GlobalNames
{
104 // The names of our possible globals. These are the names of the actual
105 // interfaces, not of the global names used to refer to them in IDL [Exposed]
107 static const uint32_t Window
= 1u << 0;
108 static const uint32_t BackstagePass
= 1u << 1;
109 static const uint32_t DedicatedWorkerGlobalScope
= 1u << 2;
110 static const uint32_t SharedWorkerGlobalScope
= 1u << 3;
111 static const uint32_t ServiceWorkerGlobalScope
= 1u << 4;
112 static const uint32_t WorkerDebuggerGlobalScope
= 1u << 5;
113 static const uint32_t WorkletGlobalScope
= 1u << 6;
114 static const uint32_t AudioWorkletGlobalScope
= 1u << 7;
115 } // namespace GlobalNames
117 struct PrefableDisablers
{
118 inline bool isEnabled(JSContext
* cx
, JS::Handle
<JSObject
*> obj
) const {
119 if (nonExposedGlobals
&&
120 IsNonExposedGlobal(cx
, JS::GetNonCCWObjectGlobal(obj
),
121 nonExposedGlobals
)) {
124 if (prefIndex
!= WebIDLPrefIndex::NoPref
&&
125 !sWebIDLPrefs
[uint16_t(prefIndex
)]()) {
128 if (secureContext
&& !IsSecureContextOrObjectIsFromSecureContext(cx
, obj
)) {
131 if (enabledFunc
&& !enabledFunc(cx
, JS::GetNonCCWObjectGlobal(obj
))) {
137 // Index into the array of StaticPrefs
138 const WebIDLPrefIndex prefIndex
;
140 // A boolean indicating whether a Secure Context is required.
141 const bool secureContext
;
143 // Bitmask of global names that we should not be exposed in.
144 const uint16_t nonExposedGlobals
;
146 // A function pointer to a function that can say the property is disabled
147 // even if "enabled" is set to true. If the pointer is null the value of
148 // "enabled" is used as-is.
149 const PropertyEnabled enabledFunc
;
152 template <typename T
>
154 inline bool isEnabled(JSContext
* cx
, JS::Handle
<JSObject
*> obj
) const {
155 MOZ_ASSERT(!js::IsWrapper(obj
));
156 if (MOZ_LIKELY(!disablers
)) {
159 return disablers
->isEnabled(cx
, obj
);
162 // Things that can disable this set of specs. |nullptr| means "cannot be
164 const PrefableDisablers
* const disablers
;
166 // Array of specs, terminated in whatever way is customary for T.
167 // Null to indicate a end-of-array for Prefable, when such an
168 // indicator is needed.
169 const T
* const specs
;
178 eUnforgeableAttribute
,
183 #define NUM_BITS_PROPERTY_INFO_TYPE 3
184 #define NUM_BITS_PROPERTY_INFO_PREF_INDEX 13
185 #define NUM_BITS_PROPERTY_INFO_SPEC_INDEX 16
187 struct PropertyInfo
{
189 // MSVC generates static initializers if we store a jsid here, even if
190 // PropertyInfo has a constexpr constructor. See bug 1460341 and bug 1464036.
194 // One of PropertyType, will be used for accessing the corresponding Duo in
195 // NativePropertiesN.duos[].
196 uint32_t type
: NUM_BITS_PROPERTY_INFO_TYPE
;
197 // The index to the corresponding Preable in Duo.mPrefables[].
198 uint32_t prefIndex
: NUM_BITS_PROPERTY_INFO_PREF_INDEX
;
199 // The index to the corresponding spec in Duo.mPrefables[prefIndex].specs[].
200 uint32_t specIndex
: NUM_BITS_PROPERTY_INFO_SPEC_INDEX
;
202 void SetId(jsid aId
) {
203 static_assert(sizeof(jsid
) == sizeof(mIdBits
),
204 "jsid should fit in mIdBits");
205 mIdBits
= JSID_BITS(aId
);
207 MOZ_ALWAYS_INLINE jsid
Id() const { return jsid::fromRawBits(mIdBits
); }
211 ePropertyTypeCount
<= 1ull << NUM_BITS_PROPERTY_INFO_TYPE
,
212 "We have property type count that is > (1 << NUM_BITS_PROPERTY_INFO_TYPE)");
214 // Conceptually, NativeProperties has seven (Prefable<T>*, PropertyInfo*) duos
215 // (where T is one of JSFunctionSpec, JSPropertySpec, or ConstantSpec), one for
216 // each of: static methods and attributes, methods and attributes, unforgeable
217 // methods and attributes, and constants.
219 // That's 14 pointers, but in most instances most of the duos are all null, and
220 // there are many instances. To save space we use a variable-length type,
221 // NativePropertiesN<N>, to hold the data and getters to access it. It has N
222 // actual duos (stored in duos[]), plus four bits for each of the 7 possible
223 // duos: 1 bit that states if that duo is present, and 3 that state that duo's
224 // offset (if present) in duos[].
226 // All duo accesses should be done via the getters, which contain assertions
227 // that check we don't overrun the end of the struct. (The duo data members are
228 // public only so they can be statically initialized.) These assertions should
229 // never fail so long as (a) accesses to the variable-length part are guarded by
230 // appropriate Has*() calls, and (b) all instances are well-formed, i.e. the
231 // value of N matches the number of mHas* members that are true.
233 // We store all the property ids a NativePropertiesN owns in a single array of
234 // PropertyInfo structs. Each struct contains an id and the information needed
235 // to find the corresponding Prefable for the enabled check, as well as the
236 // information needed to find the correct property descriptor in the
237 // Prefable. We also store an array of indices into the PropertyInfo array,
238 // sorted by bits of the corresponding jsid. Given a jsid, this allows us to
239 // binary search for the index of the corresponding PropertyInfo, if any.
241 // Finally, we define a typedef of NativePropertiesN<7>, NativeProperties, which
242 // we use as a "base" type used to refer to all instances of NativePropertiesN.
243 // (7 is used because that's the maximum valid parameter, though any other
244 // value 1..6 could also be used.) This is reasonable because of the
245 // aforementioned assertions in the getters. Upcast() is used to convert
246 // specific instances to this "base" type.
250 // NativeProperties points to various things, and it can be hard to keep track.
251 // The following example shows the layout.
253 // Imagine an example interface, with:
255 // - 6 methods, 3 with no disablers struct, 2 sharing the same disablers
256 // struct, 1 using a different disablers struct
257 // - 4 attributes, all with no disablers
258 // - The property order is such that those using the same disablers structs are
259 // together. (This is not guaranteed, but it makes the example simpler.)
261 // Each PropertyInfo also contain indices into sMethods/sMethods_specs (for
262 // method infos) and sAttributes/sAttributes_specs (for attributes), which let
263 // them find their spec, but these are not shown.
265 // sNativeProperties sNativeProperties_ sNativeProperties_
266 // ---- sortedPropertyIndices[10] propertyInfos[10]
267 // - <several scalar fields> ---- ----
268 // - sortedPropertyIndices ----> <10 indices> +--> 0 info (method)
269 // - duos[2] ---- | 1 info (method)
270 // ----(methods) | 2 info (method)
271 // 0 - mPrefables -------> points to sMethods below | 3 info (method)
272 // - mPropertyInfos ------------------------------+ 4 info (method)
273 // 1 - mPrefables -------> points to sAttributes below 5 info (method)
274 // - mPropertyInfos ---------------------------------> 6 info (attr)
275 // ---- 7 info (attr)
276 // ---- 8 info (attr)
280 // sMethods has three entries (excluding the terminator) because there are
281 // three disablers structs. The {nullptr,nullptr} serves as the terminator.
282 // There are also END terminators within sMethod_specs; the need for these
283 // terminators (as opposed to a length) is deeply embedded in SpiderMonkey.
284 // Disablers structs are suffixed with the index of the first spec they cover.
286 // sMethods sMethods_specs
288 // 0 - nullptr +----> 0 spec
289 // - specs ----------------------+ 1 spec
290 // 1 - disablers ---> disablers4 2 spec
291 // - specs ------------------------+ 3 END
292 // 2 - disablers ---> disablers7 +--> 4 spec
293 // - specs ----------------------+ 5 spec
294 // 3 - nullptr | 6 END
295 // - nullptr +----> 7 spec
298 // sAttributes has a single entry (excluding the terminator) because all of the
299 // specs lack disablers.
301 // sAttributes sAttributes_specs
303 // 0 - nullptr +----> 0 spec
304 // - specs ----------------------+ 1 spec
305 // 1 - nullptr 2 spec
310 struct NativePropertiesN
{
311 // Duo structs are stored in the duos[] array, and each element in the array
312 // could require a different T. Therefore, we can't use the correct type for
313 // mPrefables. Instead we use void* and cast to the correct type in the
316 const /*Prefable<const T>*/ void* const mPrefables
;
317 PropertyInfo
* const mPropertyInfos
;
320 constexpr const NativePropertiesN
<7>* Upcast() const {
321 return reinterpret_cast<const NativePropertiesN
<7>*>(this);
324 const PropertyInfo
* PropertyInfos() const { return duos
[0].mPropertyInfos
; }
326 #define DO(SpecT, FieldName) \
328 /* The bitfields indicating the duo's presence and (if present) offset. */ \
329 const uint32_t mHas##FieldName##s : 1; \
330 const uint32_t m##FieldName##sOffset : 3; \
333 const Duo* FieldName##sDuo() const { \
334 MOZ_ASSERT(Has##FieldName##s()); \
335 return &duos[m##FieldName##sOffset]; \
339 bool Has##FieldName##s() const { return mHas##FieldName##s; } \
340 const Prefable<const SpecT>* FieldName##s() const { \
341 return static_cast<const Prefable<const SpecT>*>( \
342 FieldName##sDuo()->mPrefables); \
344 PropertyInfo* FieldName##PropertyInfos() const { \
345 return FieldName##sDuo()->mPropertyInfos; \
348 DO(JSFunctionSpec
, StaticMethod
)
349 DO(JSPropertySpec
, StaticAttribute
)
350 DO(JSFunctionSpec
, Method
)
351 DO(JSPropertySpec
, Attribute
)
352 DO(JSFunctionSpec
, UnforgeableMethod
)
353 DO(JSPropertySpec
, UnforgeableAttribute
)
354 DO(ConstantSpec
, Constant
)
358 // The index to the iterator method in MethodPropertyInfos() array.
359 const int16_t iteratorAliasMethodIndex
;
360 // The number of PropertyInfo structs that the duos manage. This is the total
361 // count across all duos.
362 const uint16_t propertyInfoCount
;
363 // The sorted indices array from sorting property ids, which will be used when
364 // we binary search for a property.
365 uint16_t* sortedPropertyIndices
;
370 // Ensure the struct has the expected size. The 8 is for the bitfields plus
371 // iteratorAliasMethodIndex and idsLength; the rest is for the idsSortedIndex,
373 static_assert(sizeof(NativePropertiesN
<1>) == 8 + 3 * sizeof(void*), "1 size");
374 static_assert(sizeof(NativePropertiesN
<2>) == 8 + 5 * sizeof(void*), "2 size");
375 static_assert(sizeof(NativePropertiesN
<3>) == 8 + 7 * sizeof(void*), "3 size");
376 static_assert(sizeof(NativePropertiesN
<4>) == 8 + 9 * sizeof(void*), "4 size");
377 static_assert(sizeof(NativePropertiesN
<5>) == 8 + 11 * sizeof(void*), "5 size");
378 static_assert(sizeof(NativePropertiesN
<6>) == 8 + 13 * sizeof(void*), "6 size");
379 static_assert(sizeof(NativePropertiesN
<7>) == 8 + 15 * sizeof(void*), "7 size");
382 typedef NativePropertiesN
<7> NativeProperties
;
384 struct NativePropertiesHolder
{
385 const NativeProperties
* regular
;
386 const NativeProperties
* chromeOnly
;
387 // Points to a static bool that's set to true once the regular and chromeOnly
388 // NativeProperties have been inited. This is a pointer to a bool instead of
389 // a bool value because NativePropertiesHolder is stored by value in
390 // a static const NativePropertyHooks.
394 // Helper structure for Xrays for DOM binding objects. The same instance is used
395 // for instances, interface objects and interface prototype objects of a
396 // specific interface.
397 struct NativePropertyHooks
{
398 // The hook to call for resolving indexed or named properties. May be null if
399 // there can't be any.
400 ResolveOwnProperty mResolveOwnProperty
;
401 // The hook to call for enumerating indexed or named properties. May be null
402 // if there can't be any.
403 EnumerateOwnProperties mEnumerateOwnProperties
;
404 // The hook to call to delete a named property. May be null if there are no
405 // named properties or no named property deleter. On success (true return)
406 // the "found" argument will be set to true if there was in fact such a named
407 // property and false otherwise. If it's set to false, the caller is expected
408 // to proceed with whatever deletion behavior it would have if there were no
409 // named properties involved at all (i.e. if the hook were null). If it's set
410 // to true, it will indicate via opresult whether the delete actually
412 DeleteNamedProperty mDeleteNamedProperty
;
414 // The property arrays for this interface.
415 NativePropertiesHolder mNativeProperties
;
417 // This will be set to the ID of the interface prototype object for the
418 // interface, if it has one. If it doesn't have one it will be set to
419 // prototypes::id::_ID_Count.
420 prototypes::ID mPrototypeID
;
422 // This will be set to the ID of the interface object for the interface, if it
423 // has one. If it doesn't have one it will be set to
424 // constructors::id::_ID_Count.
425 constructors::ID mConstructorID
;
427 // The NativePropertyHooks instance for the parent interface (for
428 // ShimInterfaceInfo).
429 const NativePropertyHooks
* mProtoHooks
;
431 // The JSClass to use for expandos on our Xrays. Can be null, in which case
432 // Xrays will use a default class of their choice.
433 const JSClass
* mXrayExpandoClass
;
436 enum DOMObjectType
: uint8_t {
441 eGlobalInterfacePrototype
,
442 eNamedPropertiesObject
445 inline bool IsInstance(DOMObjectType type
) {
446 return type
== eInstance
|| type
== eGlobalInstance
;
449 inline bool IsInterfacePrototype(DOMObjectType type
) {
450 return type
== eInterfacePrototype
|| type
== eGlobalInterfacePrototype
;
453 typedef JSObject
* (*AssociatedGlobalGetter
)(JSContext
* aCx
,
454 JS::Handle
<JSObject
*> aObj
);
456 typedef JSObject
* (*ProtoGetter
)(JSContext
* aCx
);
459 * Returns a handle to the relevant WebIDL prototype object for the current
460 * compartment global (which may be a handle to null on out of memory). Once
461 * allocated, the prototype object is guaranteed to exist as long as the global
462 * does, since the global traces its array of WebIDL prototypes and
465 typedef JS::Handle
<JSObject
*> (*ProtoHandleGetter
)(JSContext
* aCx
);
468 * Serializes a WebIDL object for structured cloning. aObj may not be in the
469 * compartment of aCx in cases when we were working with a cross-compartment
470 * wrapper. aObj is expected to be an object of the DOMJSClass that we got the
473 typedef bool (*WebIDLSerializer
)(JSContext
* aCx
,
474 JSStructuredCloneWriter
* aWriter
,
475 JS::Handle
<JSObject
*> aObj
);
478 * Deserializes a WebIDL object from a structured clone serialization.
480 typedef JSObject
* (*WebIDLDeserializer
)(JSContext
* aCx
,
481 nsIGlobalObject
* aGlobal
,
482 JSStructuredCloneReader
* aReader
);
484 typedef nsWrapperCache
* (*WrapperCacheGetter
)(JS::Handle
<JSObject
*> aObj
);
486 // Special JSClass for reflected DOM objects.
488 // It would be nice to just inherit from JSClass, but that precludes pure
489 // compile-time initialization of the form |DOMJSClass = {...};|, since C++
490 // only allows brace initialization for aggregate/POD types.
493 // A list of interfaces that this object implements, in order of decreasing
495 const prototypes::ID mInterfaceChain
[MAX_PROTOTYPE_CHAIN_LENGTH
];
497 // We store the DOM object in reserved slot with index DOM_OBJECT_SLOT or in
498 // the proxy private if we use a proxy object.
499 // Sometimes it's an nsISupports and sometimes it's not; this class tells
501 const bool mDOMObjectIsISupports
;
503 const NativePropertyHooks
* mNativeHooks
;
505 // A callback to find the associated global for our C++ object. Note that
506 // this is used in cases when that global is _changing_, so it will not match
507 // the global of the JSObject* passed in to this function!
508 AssociatedGlobalGetter mGetAssociatedGlobal
;
509 ProtoHandleGetter mGetProto
;
511 // This stores the CC participant for the native, null if this class does not
512 // implement cycle collection or if it inherits from nsISupports (we can get
513 // the CC participant by QI'ing in that case).
514 nsCycleCollectionParticipant
* mParticipant
;
516 // The serializer for this class if the relevant object is [Serializable].
518 WebIDLSerializer mSerializer
;
520 // A callback to get the wrapper cache for C++ objects that don't inherit from
521 // nsISupports, or null.
522 WrapperCacheGetter mWrapperCacheGetter
;
524 static const DOMJSClass
* FromJSClass(const JSClass
* base
) {
525 MOZ_ASSERT(base
->flags
& JSCLASS_IS_DOMJSCLASS
);
526 return reinterpret_cast<const DOMJSClass
*>(base
);
529 const JSClass
* ToJSClass() const { return &mBase
; }
532 // Special JSClass for DOM interface and interface prototype objects.
533 struct DOMIfaceAndProtoJSClass
{
534 // It would be nice to just inherit from JSClass, but that precludes pure
535 // compile-time initialization of the form
536 // |DOMJSInterfaceAndPrototypeClass = {...};|, since C++ only allows brace
537 // initialization for aggregate/POD types.
540 // Either eInterface, eInterfacePrototype, eGlobalInterfacePrototype or
541 // eNamedPropertiesObject.
542 DOMObjectType mType
; // uint8_t
544 // Boolean indicating whether this object wants a @@hasInstance property
545 // pointing to InterfaceHasInstance defined on it. Only ever true for the
547 bool wantsInterfaceHasInstance
;
549 const prototypes::ID mPrototypeID
; // uint16_t
550 const uint32_t mDepth
;
552 const NativePropertyHooks
* mNativeHooks
;
554 // The value to return for Function.prototype.toString on this interface
556 const char* mFunToString
;
558 ProtoGetter mGetParentProto
;
560 static const DOMIfaceAndProtoJSClass
* FromJSClass(const JSClass
* base
) {
561 MOZ_ASSERT(base
->flags
& JSCLASS_IS_DOMIFACEANDPROTOJSCLASS
);
562 return reinterpret_cast<const DOMIfaceAndProtoJSClass
*>(base
);
565 const JSClass
* ToJSClass() const { return &mBase
; }
568 class ProtoAndIfaceCache
;
570 inline bool DOMGlobalHasProtoAndIFaceCache(JSObject
* global
) {
571 MOZ_ASSERT(JS::GetClass(global
)->flags
& JSCLASS_DOM_GLOBAL
);
572 // This can be undefined if we GC while creating the global
573 return !JS::GetReservedSlot(global
, DOM_PROTOTYPE_SLOT
).isUndefined();
576 inline bool HasProtoAndIfaceCache(JSObject
* global
) {
577 if (!(JS::GetClass(global
)->flags
& JSCLASS_DOM_GLOBAL
)) {
580 return DOMGlobalHasProtoAndIFaceCache(global
);
583 inline ProtoAndIfaceCache
* GetProtoAndIfaceCache(JSObject
* global
) {
584 MOZ_ASSERT(JS::GetClass(global
)->flags
& JSCLASS_DOM_GLOBAL
);
585 return static_cast<ProtoAndIfaceCache
*>(
586 JS::GetReservedSlot(global
, DOM_PROTOTYPE_SLOT
).toPrivate());
590 } // namespace mozilla
592 #endif /* mozilla_dom_DOMJSClass_h */