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/. */
10 #include "mozilla/Maybe.h"
12 #include "jstypes.h" // for JS_PUBLIC_API, JS_PUBLIC_DATA
14 #include "js/Array.h" // JS::IsArrayAnswer
15 #include "js/CallNonGenericMethod.h"
17 #include "js/HeapAPI.h" // for ObjectIsMarkedBlack
18 #include "js/Id.h" // for jsid
19 #include "js/Object.h" // JS::GetClass
20 #include "js/RootingAPI.h" // for Handle, MutableHandle (ptr only)
21 #include "js/shadow/Object.h" // JS::shadow::Object
22 #include "js/TypeDecls.h" // for HandleObject, HandleId, HandleValue, MutableHandleIdVector, MutableHandleValue, MutableHand...
23 #include "js/Value.h" // for Value, AssertValueIsNotGray, UndefinedValue, ObjectOrNullValue
29 class JS_PUBLIC_API Wrapper
;
32 * [SMDOC] Proxy Objects
34 * A proxy is a JSObject with highly customizable behavior. ES6 specifies a
35 * single kind of proxy, but the customization mechanisms we use to implement
36 * ES6 Proxy objects are also useful wherever an object with weird behavior is
37 * wanted. Proxies are used to implement:
39 * - the scope objects used by the Debugger's frame.eval() method
40 * (see js::GetDebugEnvironment)
42 * - the khuey hack, whereby a whole compartment can be blown away
43 * even if other compartments hold references to objects in it
44 * (see js::NukeCrossCompartmentWrappers)
46 * - XPConnect security wrappers, which protect chrome from malicious content
47 * (js/xpconnect/wrappers)
49 * - DOM objects with special property behavior, like named getters
50 * (dom/bindings/Codegen.py generates these proxies from WebIDL)
52 * ### Proxies and internal methods
54 * ES2019 specifies 13 internal methods. The runtime semantics of just about
55 * everything a script can do to an object is specified in terms of these
56 * internal methods. For example:
58 * JS code ES6 internal method that gets called
59 * --------------------------- --------------------------------
60 * obj.prop obj.[[Get]](obj, "prop")
61 * "prop" in obj obj.[[HasProperty]]("prop")
62 * new obj() obj.[[Construct]](<empty argument List>)
64 * With regard to the implementation of these internal methods, there are three
65 * very different kinds of object in SpiderMonkey.
67 * 1. Native objects cover most objects and contain both internal slots and
68 * properties. JSClassOps and ObjectOps may be used to override certain
71 * 2. Proxy objects are composed of internal slots and a ProxyHandler. The
72 * handler contains C++ methods that can implement these standard (and
73 * non-standard) internal methods. JSClassOps and ObjectOps for the base
74 * ProxyObject invoke the handler methods as appropriate.
76 * 3. Objects with custom layouts like TypedObjects. These rely on JSClassOps
77 * and ObjectOps to implement internal methods.
79 * Native objects with custom JSClassOps / ObjectOps are used when the object
80 * behaves very similar to a normal object such as the ArrayObject and it's
81 * length property. Most usages wrapping a C++ or other type should prefer
82 * using a Proxy. Using the proxy approach makes it much easier to create an
83 * ECMAScript and JIT compatible object, particularly if using an appropriate
86 * Just about anything you do to a proxy will end up going through a C++
87 * virtual method call. Possibly several. There's no reason the JITs and ICs
88 * can't specialize for particular proxies, based on the handler; but currently
89 * we don't do much of this, so the virtual method overhead typically is
92 * ### The proxy handler hierarchy
94 * A major use case for proxies is to forward each internal method call to
95 * another object, known as its target. The target can be an arbitrary JS
96 * object. Not every proxy has the notion of a target, however.
98 * To minimize code duplication, a set of abstract proxy handler classes is
99 * provided, from which other handlers may inherit. These abstract classes are
100 * organized in the following hierarchy:
104 * ForwardingProxyHandler // has a target and forwards internal methods
106 * Wrapper // can be unwrapped to reveal target
107 * | // (see js::CheckedUnwrap)
109 * CrossCompartmentWrapper // target is in another compartment;
110 * // implements membrane between compartments
112 * Example: Some DOM objects (including all the arraylike DOM objects) are
113 * implemented as proxies. Since these objects don't need to forward operations
114 * to any underlying JS object, BaseDOMProxyHandler directly subclasses
117 * Gecko's security wrappers are examples of cross-compartment wrappers.
119 * ### Proxy prototype chains
121 * While most ECMAScript internal methods are handled by simply calling the
122 * handler method, the [[GetPrototypeOf]] / [[SetPrototypeOf]] behaviors may
123 * follow one of two models:
125 * 1. A concrete prototype object (or null) is passed to object construction
126 * and ordinary prototype read and write applies. The prototype-related
127 * handler hooks are never called in this case. The [[Prototype]] slot is
128 * used to store the current prototype value.
130 * 2. TaggedProto::LazyProto is passed to NewProxyObject (or the
131 * ProxyOptions::lazyProto flag is set). Each read or write of the
132 * prototype will invoke the handler. This dynamic prototype behavior may
133 * be useful for wrapper-like objects. If this mode is used the
134 * getPrototype handler at a minimum must be implemented.
136 * NOTE: In this mode the [[Prototype]] internal slot is unavailable and
137 * must be simulated if needed. This is non-standard, but an
138 * appropriate handler can hide this implementation detail.
140 * One subtlety here is that ECMAScript has a notion of "ordinary" prototypes.
141 * An object that doesn't override [[GetPrototypeOf]] is considered to have an
142 * ordinary prototype. The getPrototypeIfOrdinary handler must be implemented
143 * by you or your base class. Typically model 1 will be considered "ordinary"
144 * and model 2 will not.
148 * BaseProxyHandler is the most generic kind of proxy handler. It does not make
149 * any assumptions about the target. Consequently, it does not provide any
150 * default implementation for most methods. As a convenience, a few high-level
151 * methods, like get() and set(), are given default implementations that work by
152 * calling the low-level methods, like getOwnPropertyDescriptor().
154 * Important: If you add a method here, you should probably also add a
155 * Proxy::foo entry point with an AutoEnterPolicy. If you don't, you need an
156 * explicit override for the method in SecurityWrapper. See bug 945826 comment
159 class JS_PUBLIC_API BaseProxyHandler
{
161 * Sometimes it's desirable to designate groups of proxy handlers as
162 * "similar". For this, we use the notion of a "family": A consumer-provided
163 * opaque pointer that designates the larger group to which this proxy
166 * If it will never be important to differentiate this proxy from others as
167 * part of a distinct group, nullptr may be used instead.
172 * Proxy handlers can use mHasPrototype to request the following special
173 * treatment from the JS engine:
175 * - When mHasPrototype is true, the engine never calls these methods:
176 * has, set, enumerate, iterate. Instead, for these operations,
177 * it calls the "own" methods like getOwnPropertyDescriptor, hasOwn,
178 * defineProperty, getOwnEnumerablePropertyKeys, etc.,
179 * and consults the prototype chain if needed.
181 * - When mHasPrototype is true, the engine calls handler->get() only if
182 * handler->hasOwn() says an own property exists on the proxy. If not,
183 * it consults the prototype chain.
185 * This is useful because it frees the ProxyHandler from having to implement
186 * any behavior having to do with the prototype chain.
191 * All proxies indicate whether they have any sort of interesting security
192 * policy that might prevent the caller from doing something it wants to
193 * the object. In the case of wrappers, this distinction is used to
194 * determine whether the caller may strip off the wrapper if it so desires.
196 bool mHasSecurityPolicy
;
199 explicit constexpr BaseProxyHandler(const void* aFamily
,
200 bool aHasPrototype
= false,
201 bool aHasSecurityPolicy
= false)
203 mHasPrototype(aHasPrototype
),
204 mHasSecurityPolicy(aHasSecurityPolicy
) {}
206 bool hasPrototype() const { return mHasPrototype
; }
208 bool hasSecurityPolicy() const { return mHasSecurityPolicy
; }
210 inline const void* family() const { return mFamily
; }
211 static size_t offsetOfFamily() { return offsetof(BaseProxyHandler
, mFamily
); }
213 virtual bool finalizeInBackground(const JS::Value
& priv
) const {
215 * Called on creation of a proxy to determine whether its finalize
216 * method can be finalized on the background thread.
221 virtual bool canNurseryAllocate() const {
223 * Nursery allocation is allowed if and only if it is safe to not
224 * run |finalize| when the ProxyObject dies.
229 /* Policy enforcement methods.
231 * enter() allows the policy to specify whether the caller may perform |act|
232 * on the proxy's |id| property. In the case when |act| is CALL, |id| is
233 * generally JS::PropertyKey::isVoid. The |mayThrow| parameter indicates
234 * whether a handler that wants to throw custom exceptions when denying
235 * should do so or not.
237 * The |act| parameter to enter() specifies the action being performed.
238 * If |bp| is false, the method suggests that the caller throw (though it
239 * may still decide to squelch the error).
241 * We make these OR-able so that assertEnteredPolicy can pass a union of them.
242 * For example, get{,Own}PropertyDescriptor is invoked by calls to ::get()
243 * ::set(), in addition to being invoked on its own, so there are several
244 * valid Actions that could have been entered.
246 typedef uint32_t Action
;
253 GET_PROPERTY_DESCRIPTOR
= 0x10
256 virtual bool enter(JSContext
* cx
, JS::HandleObject wrapper
, JS::HandleId id
,
257 Action act
, bool mayThrow
, bool* bp
) const;
259 /* Standard internal methods. */
260 virtual bool getOwnPropertyDescriptor(
261 JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
262 JS::MutableHandle
<mozilla::Maybe
<JS::PropertyDescriptor
>> desc
) const = 0;
263 virtual bool defineProperty(JSContext
* cx
, JS::HandleObject proxy
,
265 JS::Handle
<JS::PropertyDescriptor
> desc
,
266 JS::ObjectOpResult
& result
) const = 0;
267 virtual bool ownPropertyKeys(JSContext
* cx
, JS::HandleObject proxy
,
268 JS::MutableHandleIdVector props
) const = 0;
269 virtual bool delete_(JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
270 JS::ObjectOpResult
& result
) const = 0;
273 * These methods are standard, but the engine does not normally call them.
274 * They're opt-in. See "Proxy prototype chains" above.
276 * getPrototype() crashes if called. setPrototype() throws a TypeError.
278 virtual bool getPrototype(JSContext
* cx
, JS::HandleObject proxy
,
279 JS::MutableHandleObject protop
) const;
280 virtual bool setPrototype(JSContext
* cx
, JS::HandleObject proxy
,
281 JS::HandleObject proto
,
282 JS::ObjectOpResult
& result
) const;
284 /* Non-standard but conceptual kin to {g,s}etPrototype, so these live here. */
285 virtual bool getPrototypeIfOrdinary(JSContext
* cx
, JS::HandleObject proxy
,
287 JS::MutableHandleObject protop
) const = 0;
288 virtual bool setImmutablePrototype(JSContext
* cx
, JS::HandleObject proxy
,
289 bool* succeeded
) const;
291 virtual bool preventExtensions(JSContext
* cx
, JS::HandleObject proxy
,
292 JS::ObjectOpResult
& result
) const = 0;
293 virtual bool isExtensible(JSContext
* cx
, JS::HandleObject proxy
,
294 bool* extensible
) const = 0;
297 * These standard internal methods are implemented, as a convenience, so
298 * that ProxyHandler subclasses don't have to provide every single method.
300 * The base-class implementations work by calling getOwnPropertyDescriptor()
301 * and going up the [[Prototype]] chain if necessary. The algorithm for this
302 * follows what is defined for Ordinary Objects in the ES spec.
303 * They do not follow any standard. When in doubt, override them.
305 virtual bool has(JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
307 virtual bool get(JSContext
* cx
, JS::HandleObject proxy
,
308 JS::HandleValue receiver
, JS::HandleId id
,
309 JS::MutableHandleValue vp
) const;
310 virtual bool set(JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
311 JS::HandleValue v
, JS::HandleValue receiver
,
312 JS::ObjectOpResult
& result
) const;
314 // Use the ProxyExpando object for private fields, rather than taking the
315 // normal get/set/defineField paths.
316 virtual bool useProxyExpandoObjectForPrivateFields() const { return true; }
318 // For some exotic objects (WindowProxy, Location), we want to be able to
319 // throw rather than allow private fields on these objects.
321 // As a simplfying assumption, if throwOnPrivateFields returns true,
322 // we should also return true to useProxyExpandoObjectForPrivateFields.
323 virtual bool throwOnPrivateField() const { return false; }
326 * [[Call]] and [[Construct]] are standard internal methods but according
327 * to the spec, they are not present on every object.
329 * SpiderMonkey never calls a proxy's call()/construct() internal method
330 * unless isCallable()/isConstructor() returns true for that proxy.
332 * BaseProxyHandler::isCallable()/isConstructor() always return false, and
333 * BaseProxyHandler::call()/construct() crash if called. So if you're
334 * creating a kind of that is never callable, you don't have to override
335 * anything, but otherwise you probably want to override all four.
337 virtual bool call(JSContext
* cx
, JS::HandleObject proxy
,
338 const JS::CallArgs
& args
) const;
339 virtual bool construct(JSContext
* cx
, JS::HandleObject proxy
,
340 const JS::CallArgs
& args
) const;
342 /* SpiderMonkey extensions. */
343 virtual bool enumerate(JSContext
* cx
, JS::HandleObject proxy
,
344 JS::MutableHandleIdVector props
) const;
345 virtual bool hasOwn(JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
347 virtual bool getOwnEnumerablePropertyKeys(
348 JSContext
* cx
, JS::HandleObject proxy
,
349 JS::MutableHandleIdVector props
) const;
350 virtual bool nativeCall(JSContext
* cx
, JS::IsAcceptableThis test
,
351 JS::NativeImpl impl
, const JS::CallArgs
& args
) const;
352 virtual bool getBuiltinClass(JSContext
* cx
, JS::HandleObject proxy
,
354 virtual bool isArray(JSContext
* cx
, JS::HandleObject proxy
,
355 JS::IsArrayAnswer
* answer
) const;
356 virtual const char* className(JSContext
* cx
, JS::HandleObject proxy
) const;
357 virtual JSString
* fun_toString(JSContext
* cx
, JS::HandleObject proxy
,
358 bool isToSource
) const;
359 virtual RegExpShared
* regexp_toShared(JSContext
* cx
,
360 JS::HandleObject proxy
) const;
361 virtual bool boxedValue_unbox(JSContext
* cx
, JS::HandleObject proxy
,
362 JS::MutableHandleValue vp
) const;
363 virtual void trace(JSTracer
* trc
, JSObject
* proxy
) const;
364 virtual void finalize(JS::GCContext
* gcx
, JSObject
* proxy
) const;
365 virtual size_t objectMoved(JSObject
* proxy
, JSObject
* old
) const;
367 // Allow proxies, wrappers in particular, to specify callability at runtime.
368 // Note: These do not take const JSObject*, but they do in spirit.
369 // We are not prepared to do this, as there's little const correctness
370 // in the external APIs that handle proxies.
371 virtual bool isCallable(JSObject
* obj
) const;
372 virtual bool isConstructor(JSObject
* obj
) const;
374 virtual bool getElements(JSContext
* cx
, JS::HandleObject proxy
,
375 uint32_t begin
, uint32_t end
,
376 ElementAdder
* adder
) const;
378 virtual bool isScripted() const { return false; }
381 extern JS_PUBLIC_DATA
const JSClass ProxyClass
;
383 inline bool IsProxy(const JSObject
* obj
) {
384 return reinterpret_cast<const JS::shadow::Object
*>(obj
)->shape
->isProxy();
392 // Every proxy has a ProxyValueArray that contains the following Values:
394 // - The expando slot. This is used to hold private fields should they be
395 // stamped into a non-forwarding proxy type.
396 // - The private slot.
397 // - The reserved slots. The number of slots is determined by the proxy's Class.
399 // Proxy objects store a pointer to the reserved slots (ProxyReservedSlots*).
400 // The ProxyValueArray and the private slot can be accessed using
401 // ProxyValueArray::fromReservedSlots or ProxyDataLayout::values.
403 // Storing a pointer to ProxyReservedSlots instead of ProxyValueArray has a
404 // number of advantages. In particular, it means JS::GetReservedSlot and
405 // JS::SetReservedSlot can be used with both proxies and native objects. This
406 // works because the ProxyReservedSlots* pointer is stored where native objects
407 // store their dynamic slots pointer.
409 struct ProxyReservedSlots
{
412 static constexpr ptrdiff_t offsetOfPrivateSlot();
414 static inline int offsetOfSlot(size_t slot
) {
415 return offsetof(ProxyReservedSlots
, slots
[0]) + slot
* sizeof(JS::Value
);
418 void init(size_t nreserved
) {
419 for (size_t i
= 0; i
< nreserved
; i
++) {
420 slots
[i
] = JS::UndefinedValue();
424 ProxyReservedSlots(const ProxyReservedSlots
&) = delete;
425 void operator=(const ProxyReservedSlots
&) = delete;
428 struct ProxyValueArray
{
429 JS::Value expandoSlot
;
430 JS::Value privateSlot
;
431 ProxyReservedSlots reservedSlots
;
433 void init(size_t nreserved
) {
434 expandoSlot
= JS::ObjectOrNullValue(nullptr);
435 privateSlot
= JS::UndefinedValue();
436 reservedSlots
.init(nreserved
);
439 static MOZ_ALWAYS_INLINE ProxyValueArray
* fromReservedSlots(
440 ProxyReservedSlots
* slots
) {
441 uintptr_t p
= reinterpret_cast<uintptr_t>(slots
);
442 return reinterpret_cast<ProxyValueArray
*>(p
- offsetOfReservedSlots());
444 static constexpr size_t offsetOfReservedSlots() {
445 return offsetof(ProxyValueArray
, reservedSlots
);
448 static size_t allocCount(size_t nreserved
) {
449 static_assert(offsetOfReservedSlots() % sizeof(JS::Value
) == 0);
450 return offsetOfReservedSlots() / sizeof(JS::Value
) + nreserved
;
452 static size_t sizeOf(size_t nreserved
) {
453 return allocCount(nreserved
) * sizeof(JS::Value
);
456 ProxyValueArray(const ProxyValueArray
&) = delete;
457 void operator=(const ProxyValueArray
&) = delete;
461 constexpr ptrdiff_t ProxyReservedSlots::offsetOfPrivateSlot() {
462 return -ptrdiff_t(ProxyValueArray::offsetOfReservedSlots()) +
463 offsetof(ProxyValueArray
, privateSlot
);
466 // All proxies share the same data layout. Following the object's shape and
467 // type, the proxy has a ProxyDataLayout structure with a pointer to an array
468 // of values and the proxy's handler. This is designed both so that proxies can
469 // be easily swapped with other objects (via RemapWrapper) and to mimic the
470 // layout of other objects (proxies and other objects have the same size) so
471 // that common code can access either type of object.
473 // See GetReservedOrProxyPrivateSlot below.
474 struct ProxyDataLayout
{
475 ProxyReservedSlots
* reservedSlots
;
476 const BaseProxyHandler
* handler
;
478 MOZ_ALWAYS_INLINE ProxyValueArray
* values() const {
479 return ProxyValueArray::fromReservedSlots(reservedSlots
);
484 constexpr uint32_t ProxyDataOffset
= 1 * sizeof(void*);
486 constexpr uint32_t ProxyDataOffset
= 2 * sizeof(void*);
489 inline ProxyDataLayout
* GetProxyDataLayout(JSObject
* obj
) {
490 MOZ_ASSERT(IsProxy(obj
));
491 return reinterpret_cast<ProxyDataLayout
*>(reinterpret_cast<uint8_t*>(obj
) +
495 inline const ProxyDataLayout
* GetProxyDataLayout(const JSObject
* obj
) {
496 MOZ_ASSERT(IsProxy(obj
));
497 return reinterpret_cast<const ProxyDataLayout
*>(
498 reinterpret_cast<const uint8_t*>(obj
) + ProxyDataOffset
);
501 JS_PUBLIC_API
void SetValueInProxy(JS::Value
* slot
, const JS::Value
& value
);
503 inline void SetProxyReservedSlotUnchecked(JSObject
* obj
, size_t n
,
504 const JS::Value
& extra
) {
505 MOZ_ASSERT(n
< JSCLASS_RESERVED_SLOTS(JS::GetClass(obj
)));
507 JS::Value
* vp
= &GetProxyDataLayout(obj
)->reservedSlots
->slots
[n
];
509 // Trigger a barrier before writing the slot.
510 if (vp
->isGCThing() || extra
.isGCThing()) {
511 SetValueInProxy(vp
, extra
);
517 } // namespace detail
519 inline const BaseProxyHandler
* GetProxyHandler(const JSObject
* obj
) {
520 return detail::GetProxyDataLayout(obj
)->handler
;
523 inline const JS::Value
& GetProxyPrivate(const JSObject
* obj
) {
524 return detail::GetProxyDataLayout(obj
)->values()->privateSlot
;
527 inline const JS::Value
& GetProxyExpando(const JSObject
* obj
) {
528 return detail::GetProxyDataLayout(obj
)->values()->expandoSlot
;
531 inline JSObject
* GetProxyTargetObject(const JSObject
* obj
) {
532 return GetProxyPrivate(obj
).toObjectOrNull();
535 inline const JS::Value
& GetProxyReservedSlot(const JSObject
* obj
, size_t n
) {
536 MOZ_ASSERT(n
< JSCLASS_RESERVED_SLOTS(JS::GetClass(obj
)));
537 return detail::GetProxyDataLayout(obj
)->reservedSlots
->slots
[n
];
540 inline void SetProxyHandler(JSObject
* obj
, const BaseProxyHandler
* handler
) {
541 detail::GetProxyDataLayout(obj
)->handler
= handler
;
544 inline void SetProxyReservedSlot(JSObject
* obj
, size_t n
,
545 const JS::Value
& extra
) {
547 if (gc::detail::ObjectIsMarkedBlack(obj
)) {
548 JS::AssertValueIsNotGray(extra
);
552 detail::SetProxyReservedSlotUnchecked(obj
, n
, extra
);
555 inline void SetProxyPrivate(JSObject
* obj
, const JS::Value
& value
) {
557 if (gc::detail::ObjectIsMarkedBlack(obj
)) {
558 JS::AssertValueIsNotGray(value
);
562 JS::Value
* vp
= &detail::GetProxyDataLayout(obj
)->values()->privateSlot
;
564 // Trigger a barrier before writing the slot.
565 if (vp
->isGCThing() || value
.isGCThing()) {
566 detail::SetValueInProxy(vp
, value
);
572 inline bool IsScriptedProxy(const JSObject
* obj
) {
573 return IsProxy(obj
) && GetProxyHandler(obj
)->isScripted();
576 class MOZ_STACK_CLASS ProxyOptions
{
578 /* protected constructor for subclass */
579 explicit ProxyOptions(bool lazyProtoArg
)
580 : lazyProto_(lazyProtoArg
), clasp_(&ProxyClass
) {}
583 ProxyOptions() : ProxyOptions(false) {}
585 bool lazyProto() const { return lazyProto_
; }
586 ProxyOptions
& setLazyProto(bool flag
) {
591 const JSClass
* clasp() const { return clasp_
; }
592 ProxyOptions
& setClass(const JSClass
* claspArg
) {
599 const JSClass
* clasp_
;
602 JS_PUBLIC_API JSObject
* NewProxyObject(
603 JSContext
* cx
, const BaseProxyHandler
* handler
, JS::HandleValue priv
,
604 JSObject
* proto
, const ProxyOptions
& options
= ProxyOptions());
606 JSObject
* RenewProxyObject(JSContext
* cx
, JSObject
* obj
,
607 BaseProxyHandler
* handler
, const JS::Value
& priv
);
609 class JS_PUBLIC_API AutoEnterPolicy
{
611 typedef BaseProxyHandler::Action Action
;
612 AutoEnterPolicy(JSContext
* cx
, const BaseProxyHandler
* handler
,
613 JS::HandleObject wrapper
, JS::HandleId id
, Action act
,
619 allow
= handler
->hasSecurityPolicy()
620 ? handler
->enter(cx
, wrapper
, id
, act
, mayThrow
, &rv
)
622 recordEnter(cx
, wrapper
, id
, act
);
623 // We want to throw an exception if all of the following are true:
624 // * The policy disallowed access.
625 // * The policy set rv to false, indicating that we should throw.
626 // * The caller did not instruct us to ignore exceptions.
627 // * The policy did not throw itself.
628 if (!allow
&& !rv
&& mayThrow
) {
629 reportErrorIfExceptionIsNotPending(cx
, id
);
633 virtual ~AutoEnterPolicy() { recordLeave(); }
634 inline bool allowed() { return allow
; }
635 inline bool returnValue() {
636 MOZ_ASSERT(!allowed());
641 // no-op constructor for subclass
645 enteredAction(BaseProxyHandler::NONE
)
649 void reportErrorIfExceptionIsNotPending(JSContext
* cx
, JS::HandleId id
);
655 mozilla::Maybe
<JS::HandleObject
> enteredProxy
;
656 mozilla::Maybe
<JS::HandleId
> enteredId
;
657 Action enteredAction
;
659 // NB: We explicitly don't track the entered action here, because sometimes
660 // set() methods do an implicit get() during their implementation, leading
661 // to spurious assertions.
662 AutoEnterPolicy
* prev
;
663 void recordEnter(JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
667 friend JS_PUBLIC_API
void assertEnteredPolicy(JSContext
* cx
, JSObject
* proxy
,
668 jsid id
, Action act
);
670 inline void recordEnter(JSContext
* cx
, JSObject
* proxy
, jsid id
, Action act
) {
672 inline void recordLeave() {}
676 // This operator needs to be deleted explicitly, otherwise Visual C++ will
677 // create it automatically when it is part of the export JS API. In that
678 // case, compile would fail because HandleId is not allowed to be assigned
679 // and consequently instantiation of assign operator of mozilla::Maybe
680 // would fail. See bug 1325351 comment 16. Copy constructor is removed at
681 // the same time for consistency.
682 AutoEnterPolicy(const AutoEnterPolicy
&) = delete;
683 AutoEnterPolicy
& operator=(const AutoEnterPolicy
&) = delete;
687 class JS_PUBLIC_API AutoWaivePolicy
: public AutoEnterPolicy
{
689 AutoWaivePolicy(JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
690 BaseProxyHandler::Action act
) {
692 recordEnter(cx
, proxy
, id
, act
);
696 class JS_PUBLIC_API AutoWaivePolicy
{
698 AutoWaivePolicy(JSContext
* cx
, JS::HandleObject proxy
, JS::HandleId id
,
699 BaseProxyHandler::Action act
) {}
704 extern JS_PUBLIC_API
void assertEnteredPolicy(JSContext
* cx
, JSObject
* obj
,
706 BaseProxyHandler::Action act
);
708 inline void assertEnteredPolicy(JSContext
* cx
, JSObject
* obj
, jsid id
,
709 BaseProxyHandler::Action act
) {}
712 extern JS_PUBLIC_DATA
const JSClassOps ProxyClassOps
;
713 extern JS_PUBLIC_DATA
const js::ClassExtension ProxyClassExtension
;
714 extern JS_PUBLIC_DATA
const js::ObjectOps ProxyObjectOps
;
716 template <unsigned Flags
>
717 constexpr unsigned CheckProxyFlags() {
718 constexpr size_t reservedSlots
=
719 (Flags
>> JSCLASS_RESERVED_SLOTS_SHIFT
) & JSCLASS_RESERVED_SLOTS_MASK
;
721 // For now assert each Proxy Class has at least 1 reserved slot. This is
722 // not a hard requirement, but helps catch Classes that need an explicit
723 // JSCLASS_HAS_RESERVED_SLOTS since bug 1360523.
724 static_assert(reservedSlots
> 0,
725 "Proxy Classes must have at least 1 reserved slot");
727 constexpr size_t numSlots
=
728 offsetof(js::detail::ProxyValueArray
, reservedSlots
) / sizeof(JS::Value
);
730 // ProxyValueArray must fit inline in the object, so assert the number of
731 // slots does not exceed MAX_FIXED_SLOTS.
732 static_assert(numSlots
+ reservedSlots
<= JS::shadow::Object::MAX_FIXED_SLOTS
,
733 "ProxyValueArray size must not exceed max JSObject size");
735 // Proxies must not have the JSCLASS_SKIP_NURSERY_FINALIZE flag set: they
736 // always have finalizers, and whether they can be nursery allocated is
737 // controlled by the canNurseryAllocate() method on the proxy handler.
738 static_assert(!(Flags
& JSCLASS_SKIP_NURSERY_FINALIZE
),
739 "Proxies must not use JSCLASS_SKIP_NURSERY_FINALIZE; use "
740 "the canNurseryAllocate() proxy handler method instead.");
744 #define PROXY_CLASS_DEF_WITH_CLASS_SPEC(name, flags, classSpec) \
747 JSClass::NON_NATIVE | JSCLASS_IS_PROXY | \
748 JSCLASS_DELAY_METADATA_BUILDER | js::CheckProxyFlags<flags>(), \
749 &js::ProxyClassOps, classSpec, &js::ProxyClassExtension, \
750 &js::ProxyObjectOps \
753 #define PROXY_CLASS_DEF(name, flags) \
754 PROXY_CLASS_DEF_WITH_CLASS_SPEC(name, flags, JS_NULL_CLASS_SPEC)
756 // Converts a proxy into a DeadObjectProxy that will throw exceptions on all
757 // access. This will run the proxy's finalizer to perform clean-up before the
758 // conversion happens.
759 JS_PUBLIC_API
void NukeNonCCWProxy(JSContext
* cx
, JS::HandleObject proxy
);
761 // This is a variant of js::NukeNonCCWProxy() for CCWs. It should only be called
762 // on CCWs that have been removed from CCW tables.
763 JS_PUBLIC_API
void NukeRemovedCrossCompartmentWrapper(JSContext
* cx
,
768 #endif /* js_Proxy_h */