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
,
77 JS::Handle
<jsid
> id
, JS::MutableHandle
<JS::PropertyDescriptor
> desc
);
79 typedef bool (*EnumerateOwnProperties
)(JSContext
* cx
,
80 JS::Handle
<JSObject
*> wrapper
,
81 JS::Handle
<JSObject
*> obj
,
82 JS::MutableHandleVector
<jsid
> props
);
84 typedef bool (*DeleteNamedProperty
)(JSContext
* cx
,
85 JS::Handle
<JSObject
*> wrapper
,
86 JS::Handle
<JSObject
*> obj
,
88 JS::ObjectOpResult
& opresult
);
90 // Returns true if the given global is of a type whose bit is set in
91 // aNonExposedGlobals.
92 bool IsNonExposedGlobal(JSContext
* aCx
, JSObject
* aGlobal
,
93 uint32_t aNonExposedGlobals
);
100 typedef bool (*PropertyEnabled
)(JSContext
* cx
, JSObject
* global
);
102 namespace GlobalNames
{
103 // The names of our possible globals. These are the names of the actual
104 // interfaces, not of the global names used to refer to them in IDL [Exposed]
106 static const uint32_t Window
= 1u << 0;
107 static const uint32_t BackstagePass
= 1u << 1;
108 static const uint32_t DedicatedWorkerGlobalScope
= 1u << 2;
109 static const uint32_t SharedWorkerGlobalScope
= 1u << 3;
110 static const uint32_t ServiceWorkerGlobalScope
= 1u << 4;
111 static const uint32_t WorkerDebuggerGlobalScope
= 1u << 5;
112 static const uint32_t WorkletGlobalScope
= 1u << 6;
113 static const uint32_t AudioWorkletGlobalScope
= 1u << 7;
114 } // namespace GlobalNames
116 struct PrefableDisablers
{
117 inline bool isEnabled(JSContext
* cx
, JS::Handle
<JSObject
*> obj
) const {
118 if (nonExposedGlobals
&&
119 IsNonExposedGlobal(cx
, JS::GetNonCCWObjectGlobal(obj
),
120 nonExposedGlobals
)) {
123 if (prefIndex
!= WebIDLPrefIndex::NoPref
&&
124 !sWebIDLPrefs
[uint16_t(prefIndex
)]()) {
127 if (secureContext
&& !IsSecureContextOrObjectIsFromSecureContext(cx
, obj
)) {
130 if (enabledFunc
&& !enabledFunc(cx
, JS::GetNonCCWObjectGlobal(obj
))) {
136 // Index into the array of StaticPrefs
137 const WebIDLPrefIndex prefIndex
;
139 // A boolean indicating whether a Secure Context is required.
140 const bool secureContext
;
142 // Bitmask of global names that we should not be exposed in.
143 const uint16_t nonExposedGlobals
;
145 // A function pointer to a function that can say the property is disabled
146 // even if "enabled" is set to true. If the pointer is null the value of
147 // "enabled" is used as-is.
148 const PropertyEnabled enabledFunc
;
151 template <typename T
>
153 inline bool isEnabled(JSContext
* cx
, JS::Handle
<JSObject
*> obj
) const {
154 MOZ_ASSERT(!js::IsWrapper(obj
));
155 if (MOZ_LIKELY(!disablers
)) {
158 return disablers
->isEnabled(cx
, obj
);
161 // Things that can disable this set of specs. |nullptr| means "cannot be
163 const PrefableDisablers
* const disablers
;
165 // Array of specs, terminated in whatever way is customary for T.
166 // Null to indicate a end-of-array for Prefable, when such an
167 // indicator is needed.
168 const T
* const specs
;
177 eUnforgeableAttribute
,
182 #define NUM_BITS_PROPERTY_INFO_TYPE 3
183 #define NUM_BITS_PROPERTY_INFO_PREF_INDEX 13
184 #define NUM_BITS_PROPERTY_INFO_SPEC_INDEX 16
186 struct PropertyInfo
{
188 // MSVC generates static initializers if we store a jsid here, even if
189 // PropertyInfo has a constexpr constructor. See bug 1460341 and bug 1464036.
193 // One of PropertyType, will be used for accessing the corresponding Duo in
194 // NativePropertiesN.duos[].
195 uint32_t type
: NUM_BITS_PROPERTY_INFO_TYPE
;
196 // The index to the corresponding Preable in Duo.mPrefables[].
197 uint32_t prefIndex
: NUM_BITS_PROPERTY_INFO_PREF_INDEX
;
198 // The index to the corresponding spec in Duo.mPrefables[prefIndex].specs[].
199 uint32_t specIndex
: NUM_BITS_PROPERTY_INFO_SPEC_INDEX
;
201 void SetId(jsid aId
) {
202 static_assert(sizeof(jsid
) == sizeof(mIdBits
),
203 "jsid should fit in mIdBits");
204 mIdBits
= JSID_BITS(aId
);
206 MOZ_ALWAYS_INLINE jsid
Id() const { return jsid::fromRawBits(mIdBits
); }
210 ePropertyTypeCount
<= 1ull << NUM_BITS_PROPERTY_INFO_TYPE
,
211 "We have property type count that is > (1 << NUM_BITS_PROPERTY_INFO_TYPE)");
213 // Conceptually, NativeProperties has seven (Prefable<T>*, PropertyInfo*) duos
214 // (where T is one of JSFunctionSpec, JSPropertySpec, or ConstantSpec), one for
215 // each of: static methods and attributes, methods and attributes, unforgeable
216 // methods and attributes, and constants.
218 // That's 14 pointers, but in most instances most of the duos are all null, and
219 // there are many instances. To save space we use a variable-length type,
220 // NativePropertiesN<N>, to hold the data and getters to access it. It has N
221 // actual duos (stored in duos[]), plus four bits for each of the 7 possible
222 // duos: 1 bit that states if that duo is present, and 3 that state that duo's
223 // offset (if present) in duos[].
225 // All duo accesses should be done via the getters, which contain assertions
226 // that check we don't overrun the end of the struct. (The duo data members are
227 // public only so they can be statically initialized.) These assertions should
228 // never fail so long as (a) accesses to the variable-length part are guarded by
229 // appropriate Has*() calls, and (b) all instances are well-formed, i.e. the
230 // value of N matches the number of mHas* members that are true.
232 // We store all the property ids a NativePropertiesN owns in a single array of
233 // PropertyInfo structs. Each struct contains an id and the information needed
234 // to find the corresponding Prefable for the enabled check, as well as the
235 // information needed to find the correct property descriptor in the
236 // Prefable. We also store an array of indices into the PropertyInfo array,
237 // sorted by bits of the corresponding jsid. Given a jsid, this allows us to
238 // binary search for the index of the corresponding PropertyInfo, if any.
240 // Finally, we define a typedef of NativePropertiesN<7>, NativeProperties, which
241 // we use as a "base" type used to refer to all instances of NativePropertiesN.
242 // (7 is used because that's the maximum valid parameter, though any other
243 // value 1..6 could also be used.) This is reasonable because of the
244 // aforementioned assertions in the getters. Upcast() is used to convert
245 // specific instances to this "base" type.
249 // NativeProperties points to various things, and it can be hard to keep track.
250 // The following example shows the layout.
252 // Imagine an example interface, with:
254 // - 6 methods, 3 with no disablers struct, 2 sharing the same disablers
255 // struct, 1 using a different disablers struct
256 // - 4 attributes, all with no disablers
257 // - The property order is such that those using the same disablers structs are
258 // together. (This is not guaranteed, but it makes the example simpler.)
260 // Each PropertyInfo also contain indices into sMethods/sMethods_specs (for
261 // method infos) and sAttributes/sAttributes_specs (for attributes), which let
262 // them find their spec, but these are not shown.
264 // sNativeProperties sNativeProperties_ sNativeProperties_
265 // ---- sortedPropertyIndices[10] propertyInfos[10]
266 // - <several scalar fields> ---- ----
267 // - sortedPropertyIndices ----> <10 indices> +--> 0 info (method)
268 // - duos[2] ---- | 1 info (method)
269 // ----(methods) | 2 info (method)
270 // 0 - mPrefables -------> points to sMethods below | 3 info (method)
271 // - mPropertyInfos ------------------------------+ 4 info (method)
272 // 1 - mPrefables -------> points to sAttributes below 5 info (method)
273 // - mPropertyInfos ---------------------------------> 6 info (attr)
274 // ---- 7 info (attr)
275 // ---- 8 info (attr)
279 // sMethods has three entries (excluding the terminator) because there are
280 // three disablers structs. The {nullptr,nullptr} serves as the terminator.
281 // There are also END terminators within sMethod_specs; the need for these
282 // terminators (as opposed to a length) is deeply embedded in SpiderMonkey.
283 // Disablers structs are suffixed with the index of the first spec they cover.
285 // sMethods sMethods_specs
287 // 0 - nullptr +----> 0 spec
288 // - specs ----------------------+ 1 spec
289 // 1 - disablers ---> disablers4 2 spec
290 // - specs ------------------------+ 3 END
291 // 2 - disablers ---> disablers7 +--> 4 spec
292 // - specs ----------------------+ 5 spec
293 // 3 - nullptr | 6 END
294 // - nullptr +----> 7 spec
297 // sAttributes has a single entry (excluding the terminator) because all of the
298 // specs lack disablers.
300 // sAttributes sAttributes_specs
302 // 0 - nullptr +----> 0 spec
303 // - specs ----------------------+ 1 spec
304 // 1 - nullptr 2 spec
309 struct NativePropertiesN
{
310 // Duo structs are stored in the duos[] array, and each element in the array
311 // could require a different T. Therefore, we can't use the correct type for
312 // mPrefables. Instead we use void* and cast to the correct type in the
315 const /*Prefable<const T>*/ void* const mPrefables
;
316 PropertyInfo
* const mPropertyInfos
;
319 constexpr const NativePropertiesN
<7>* Upcast() const {
320 return reinterpret_cast<const NativePropertiesN
<7>*>(this);
323 const PropertyInfo
* PropertyInfos() const { return duos
[0].mPropertyInfos
; }
325 #define DO(SpecT, FieldName) \
327 /* The bitfields indicating the duo's presence and (if present) offset. */ \
328 const uint32_t mHas##FieldName##s : 1; \
329 const uint32_t m##FieldName##sOffset : 3; \
332 const Duo* FieldName##sDuo() const { \
333 MOZ_ASSERT(Has##FieldName##s()); \
334 return &duos[m##FieldName##sOffset]; \
338 bool Has##FieldName##s() const { return mHas##FieldName##s; } \
339 const Prefable<const SpecT>* FieldName##s() const { \
340 return static_cast<const Prefable<const SpecT>*>( \
341 FieldName##sDuo()->mPrefables); \
343 PropertyInfo* FieldName##PropertyInfos() const { \
344 return FieldName##sDuo()->mPropertyInfos; \
347 DO(JSFunctionSpec
, StaticMethod
)
348 DO(JSPropertySpec
, StaticAttribute
)
349 DO(JSFunctionSpec
, Method
)
350 DO(JSPropertySpec
, Attribute
)
351 DO(JSFunctionSpec
, UnforgeableMethod
)
352 DO(JSPropertySpec
, UnforgeableAttribute
)
353 DO(ConstantSpec
, Constant
)
357 // The index to the iterator method in MethodPropertyInfos() array.
358 const int16_t iteratorAliasMethodIndex
;
359 // The number of PropertyInfo structs that the duos manage. This is the total
360 // count across all duos.
361 const uint16_t propertyInfoCount
;
362 // The sorted indices array from sorting property ids, which will be used when
363 // we binary search for a property.
364 uint16_t* sortedPropertyIndices
;
369 // Ensure the struct has the expected size. The 8 is for the bitfields plus
370 // iteratorAliasMethodIndex and idsLength; the rest is for the idsSortedIndex,
372 static_assert(sizeof(NativePropertiesN
<1>) == 8 + 3 * sizeof(void*), "1 size");
373 static_assert(sizeof(NativePropertiesN
<2>) == 8 + 5 * sizeof(void*), "2 size");
374 static_assert(sizeof(NativePropertiesN
<3>) == 8 + 7 * sizeof(void*), "3 size");
375 static_assert(sizeof(NativePropertiesN
<4>) == 8 + 9 * sizeof(void*), "4 size");
376 static_assert(sizeof(NativePropertiesN
<5>) == 8 + 11 * sizeof(void*), "5 size");
377 static_assert(sizeof(NativePropertiesN
<6>) == 8 + 13 * sizeof(void*), "6 size");
378 static_assert(sizeof(NativePropertiesN
<7>) == 8 + 15 * sizeof(void*), "7 size");
381 typedef NativePropertiesN
<7> NativeProperties
;
383 struct NativePropertiesHolder
{
384 const NativeProperties
* regular
;
385 const NativeProperties
* chromeOnly
;
388 // Helper structure for Xrays for DOM binding objects. The same instance is used
389 // for instances, interface objects and interface prototype objects of a
390 // specific interface.
391 struct NativePropertyHooks
{
392 // The hook to call for resolving indexed or named properties. May be null if
393 // there can't be any.
394 ResolveOwnProperty mResolveOwnProperty
;
395 // The hook to call for enumerating indexed or named properties. May be null
396 // if there can't be any.
397 EnumerateOwnProperties mEnumerateOwnProperties
;
398 // The hook to call to delete a named property. May be null if there are no
399 // named properties or no named property deleter. On success (true return)
400 // the "found" argument will be set to true if there was in fact such a named
401 // property and false otherwise. If it's set to false, the caller is expected
402 // to proceed with whatever deletion behavior it would have if there were no
403 // named properties involved at all (i.e. if the hook were null). If it's set
404 // to true, it will indicate via opresult whether the delete actually
406 DeleteNamedProperty mDeleteNamedProperty
;
408 // The property arrays for this interface.
409 NativePropertiesHolder mNativeProperties
;
411 // This will be set to the ID of the interface prototype object for the
412 // interface, if it has one. If it doesn't have one it will be set to
413 // prototypes::id::_ID_Count.
414 prototypes::ID mPrototypeID
;
416 // This will be set to the ID of the interface object for the interface, if it
417 // has one. If it doesn't have one it will be set to
418 // constructors::id::_ID_Count.
419 constructors::ID mConstructorID
;
421 // The NativePropertyHooks instance for the parent interface (for
422 // ShimInterfaceInfo).
423 const NativePropertyHooks
* mProtoHooks
;
425 // The JSClass to use for expandos on our Xrays. Can be null, in which case
426 // Xrays will use a default class of their choice.
427 const JSClass
* mXrayExpandoClass
;
430 enum DOMObjectType
: uint8_t {
435 eGlobalInterfacePrototype
,
436 eNamedPropertiesObject
439 inline bool IsInstance(DOMObjectType type
) {
440 return type
== eInstance
|| type
== eGlobalInstance
;
443 inline bool IsInterfacePrototype(DOMObjectType type
) {
444 return type
== eInterfacePrototype
|| type
== eGlobalInterfacePrototype
;
447 typedef JSObject
* (*AssociatedGlobalGetter
)(JSContext
* aCx
,
448 JS::Handle
<JSObject
*> aObj
);
450 typedef JSObject
* (*ProtoGetter
)(JSContext
* aCx
);
453 * Returns a handle to the relevant WebIDL prototype object for the current
454 * compartment global (which may be a handle to null on out of memory). Once
455 * allocated, the prototype object is guaranteed to exist as long as the global
456 * does, since the global traces its array of WebIDL prototypes and
459 typedef JS::Handle
<JSObject
*> (*ProtoHandleGetter
)(JSContext
* aCx
);
462 * Serializes a WebIDL object for structured cloning. aObj may not be in the
463 * compartment of aCx in cases when we were working with a cross-compartment
464 * wrapper. aObj is expected to be an object of the DOMJSClass that we got the
467 typedef bool (*WebIDLSerializer
)(JSContext
* aCx
,
468 JSStructuredCloneWriter
* aWriter
,
469 JS::Handle
<JSObject
*> aObj
);
472 * Deserializes a WebIDL object from a structured clone serialization.
474 typedef JSObject
* (*WebIDLDeserializer
)(JSContext
* aCx
,
475 nsIGlobalObject
* aGlobal
,
476 JSStructuredCloneReader
* aReader
);
478 typedef nsWrapperCache
* (*WrapperCacheGetter
)(JS::Handle
<JSObject
*> aObj
);
480 // Special JSClass for reflected DOM objects.
482 // It would be nice to just inherit from JSClass, but that precludes pure
483 // compile-time initialization of the form |DOMJSClass = {...};|, since C++
484 // only allows brace initialization for aggregate/POD types.
487 // A list of interfaces that this object implements, in order of decreasing
489 const prototypes::ID mInterfaceChain
[MAX_PROTOTYPE_CHAIN_LENGTH
];
491 // We store the DOM object in reserved slot with index DOM_OBJECT_SLOT or in
492 // the proxy private if we use a proxy object.
493 // Sometimes it's an nsISupports and sometimes it's not; this class tells
495 const bool mDOMObjectIsISupports
;
497 const NativePropertyHooks
* mNativeHooks
;
499 // A callback to find the associated global for our C++ object. Note that
500 // this is used in cases when that global is _changing_, so it will not match
501 // the global of the JSObject* passed in to this function!
502 AssociatedGlobalGetter mGetAssociatedGlobal
;
503 ProtoHandleGetter mGetProto
;
505 // This stores the CC participant for the native, null if this class does not
506 // implement cycle collection or if it inherits from nsISupports (we can get
507 // the CC participant by QI'ing in that case).
508 nsCycleCollectionParticipant
* mParticipant
;
510 // The serializer for this class if the relevant object is [Serializable].
512 WebIDLSerializer mSerializer
;
514 // A callback to get the wrapper cache for C++ objects that don't inherit from
515 // nsISupports, or null.
516 WrapperCacheGetter mWrapperCacheGetter
;
518 static const DOMJSClass
* FromJSClass(const JSClass
* base
) {
519 MOZ_ASSERT(base
->flags
& JSCLASS_IS_DOMJSCLASS
);
520 return reinterpret_cast<const DOMJSClass
*>(base
);
523 const JSClass
* ToJSClass() const { return &mBase
; }
526 // Special JSClass for DOM interface and interface prototype objects.
527 struct DOMIfaceAndProtoJSClass
{
528 // It would be nice to just inherit from JSClass, but that precludes pure
529 // compile-time initialization of the form
530 // |DOMJSInterfaceAndPrototypeClass = {...};|, since C++ only allows brace
531 // initialization for aggregate/POD types.
534 // Either eInterface, eInterfacePrototype, eGlobalInterfacePrototype or
535 // eNamedPropertiesObject.
536 DOMObjectType mType
; // uint8_t
538 // Boolean indicating whether this object wants a @@hasInstance property
539 // pointing to InterfaceHasInstance defined on it. Only ever true for the
541 bool wantsInterfaceHasInstance
;
543 const prototypes::ID mPrototypeID
; // uint16_t
544 const uint32_t mDepth
;
546 const NativePropertyHooks
* mNativeHooks
;
548 // The value to return for Function.prototype.toString on this interface
550 const char* mFunToString
;
552 ProtoGetter mGetParentProto
;
554 static const DOMIfaceAndProtoJSClass
* FromJSClass(const JSClass
* base
) {
555 MOZ_ASSERT(base
->flags
& JSCLASS_IS_DOMIFACEANDPROTOJSCLASS
);
556 return reinterpret_cast<const DOMIfaceAndProtoJSClass
*>(base
);
559 const JSClass
* ToJSClass() const { return &mBase
; }
562 class ProtoAndIfaceCache
;
564 inline bool DOMGlobalHasProtoAndIFaceCache(JSObject
* global
) {
565 MOZ_ASSERT(JS::GetClass(global
)->flags
& JSCLASS_DOM_GLOBAL
);
566 // This can be undefined if we GC while creating the global
567 return !JS::GetReservedSlot(global
, DOM_PROTOTYPE_SLOT
).isUndefined();
570 inline bool HasProtoAndIfaceCache(JSObject
* global
) {
571 if (!(JS::GetClass(global
)->flags
& JSCLASS_DOM_GLOBAL
)) {
574 return DOMGlobalHasProtoAndIFaceCache(global
);
577 inline ProtoAndIfaceCache
* GetProtoAndIfaceCache(JSObject
* global
) {
578 MOZ_ASSERT(JS::GetClass(global
)->flags
& JSCLASS_DOM_GLOBAL
);
579 return static_cast<ProtoAndIfaceCache
*>(
580 JS::GetReservedSlot(global
, DOM_PROTOTYPE_SLOT
).toPrivate());
584 } // namespace mozilla
586 #endif /* mozilla_dom_DOMJSClass_h */