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/. */
7 #include "WaiveXrayWrapper.h"
8 #include "FilteringWrapper.h"
9 #include "XrayWrapper.h"
10 #include "AccessCheck.h"
11 #include "XPCWrapper.h"
12 #include "ChromeObjectWrapper.h"
13 #include "WrapperFactory.h"
15 #include "xpcprivate.h"
17 #include "mozilla/dom/BindingUtils.h"
18 #include "jsfriendapi.h"
19 #include "js/friend/WindowProxy.h" // js::IsWindow, js::IsWindowProxy
20 #include "js/Object.h" // JS::GetPrivate, JS::GetCompartment
21 #include "mozilla/Likely.h"
22 #include "mozilla/dom/ScriptSettings.h"
23 #include "mozilla/dom/MaybeCrossOriginObject.h"
24 #include "nsContentUtils.h"
25 #include "nsGlobalWindowInner.h"
26 #include "nsXULAppAPI.h"
30 using namespace mozilla
;
34 #ifndef MOZ_UNIFIED_BUILD
35 extern template class FilteringWrapper
<js::CrossCompartmentSecurityWrapper
,
37 extern template class FilteringWrapper
<js::CrossCompartmentSecurityWrapper
,
41 // When chrome pulls a naked property across the membrane using
42 // .wrappedJSObject, we want it to cross the membrane into the
43 // chrome compartment without automatically being wrapped into an
44 // X-ray wrapper. We achieve this by wrapping it into a special
45 // transparent wrapper in the origin (non-chrome) compartment. When
46 // an object with that special wrapper applied crosses into chrome,
47 // we know to not apply an X-ray wrapper.
48 const Wrapper
XrayWaiver(WrapperFactory::WAIVE_XRAY_WRAPPER_FLAG
);
50 // When objects for which we waived the X-ray wrapper cross into
51 // chrome, we wrap them into a special cross-compartment wrapper
52 // that transitively extends the waiver to all properties we get
54 const WaiveXrayWrapper
WaiveXrayWrapper::singleton(0);
56 bool WrapperFactory::IsOpaqueWrapper(JSObject
* obj
) {
57 return IsWrapper(obj
) &&
58 Wrapper::wrapperHandler(obj
) == &PermissiveXrayOpaque::singleton
;
61 bool WrapperFactory::IsCOW(JSObject
* obj
) {
62 return IsWrapper(obj
) &&
63 Wrapper::wrapperHandler(obj
) == &ChromeObjectWrapper::singleton
;
66 JSObject
* WrapperFactory::GetXrayWaiver(HandleObject obj
) {
67 // Object should come fully unwrapped but outerized.
68 MOZ_ASSERT(obj
== UncheckedUnwrap(obj
));
69 MOZ_ASSERT(!js::IsWindow(obj
));
70 XPCWrappedNativeScope
* scope
= ObjectScope(obj
);
73 if (!scope
->mWaiverWrapperMap
) {
77 return scope
->mWaiverWrapperMap
->Find(obj
);
80 JSObject
* WrapperFactory::CreateXrayWaiver(JSContext
* cx
, HandleObject obj
,
82 // The caller is required to have already done a lookup, unless it's
83 // trying to replace an existing waiver.
84 // NB: This implictly performs the assertions of GetXrayWaiver.
85 MOZ_ASSERT(bool(GetXrayWaiver(obj
)) == allowExisting
);
86 XPCWrappedNativeScope
* scope
= ObjectScope(obj
);
88 JSAutoRealm
ar(cx
, obj
);
89 JSObject
* waiver
= Wrapper::New(cx
, obj
, &XrayWaiver
);
94 // Add the new waiver to the map. It's important that we only ever have
95 // one waiver for the lifetime of the target object.
96 if (!scope
->mWaiverWrapperMap
) {
97 scope
->mWaiverWrapperMap
= mozilla::MakeUnique
<JSObject2JSObjectMap
>();
99 if (!scope
->mWaiverWrapperMap
->Add(cx
, obj
, waiver
)) {
105 JSObject
* WrapperFactory::WaiveXray(JSContext
* cx
, JSObject
* objArg
) {
106 RootedObject
obj(cx
, objArg
);
107 obj
= UncheckedUnwrap(obj
);
108 MOZ_ASSERT(!js::IsWindow(obj
));
110 JSObject
* waiver
= GetXrayWaiver(obj
);
112 waiver
= CreateXrayWaiver(cx
, obj
);
114 JS::AssertObjectIsNotGray(waiver
);
119 bool WrapperFactory::AllowWaiver(JS::Compartment
* target
,
120 JS::Compartment
* origin
) {
121 return CompartmentPrivate::Get(target
)->allowWaivers
&&
122 CompartmentOriginInfo::Subsumes(target
, origin
);
126 bool WrapperFactory::AllowWaiver(JSObject
* wrapper
) {
127 MOZ_ASSERT(js::IsCrossCompartmentWrapper(wrapper
));
128 return AllowWaiver(JS::GetCompartment(wrapper
),
129 JS::GetCompartment(js::UncheckedUnwrap(wrapper
)));
132 inline bool ShouldWaiveXray(JSContext
* cx
, JSObject
* originalObj
) {
134 (void)js::UncheckedUnwrap(originalObj
, /* stopAtWindowProxy = */ true,
137 // If the original object did not point through an Xray waiver, we're done.
138 if (!(flags
& WrapperFactory::WAIVE_XRAY_WRAPPER_FLAG
)) {
142 // If the original object was not a cross-compartment wrapper, that means
143 // that the caller explicitly created a waiver. Preserve it so that things
144 // like WaiveXrayAndWrap work.
145 if (!(flags
& Wrapper::CROSS_COMPARTMENT
)) {
149 // Otherwise, this is a case of explicitly passing a wrapper across a
150 // compartment boundary. In that case, we only want to preserve waivers
151 // in transactions between same-origin compartments.
152 JS::Compartment
* oldCompartment
= JS::GetCompartment(originalObj
);
153 JS::Compartment
* newCompartment
= js::GetContextCompartment(cx
);
154 bool sameOrigin
= false;
155 if (OriginAttributes::IsRestrictOpenerAccessForFPI()) {
157 CompartmentOriginInfo::Subsumes(oldCompartment
, newCompartment
) &&
158 CompartmentOriginInfo::Subsumes(newCompartment
, oldCompartment
);
160 sameOrigin
= CompartmentOriginInfo::SubsumesIgnoringFPD(oldCompartment
,
162 CompartmentOriginInfo::SubsumesIgnoringFPD(newCompartment
,
168 // Special handling is needed when wrapping local and remote window proxies.
169 // This function returns true if it found a window proxy and dealt with it.
170 static bool MaybeWrapWindowProxy(JSContext
* cx
, HandleObject origObj
,
171 HandleObject obj
, MutableHandleObject retObj
) {
172 bool isWindowProxy
= js::IsWindowProxy(obj
);
174 if (!isWindowProxy
&&
175 !dom::IsRemoteObjectProxy(obj
, dom::prototypes::id::Window
)) {
179 dom::BrowsingContext
* bc
= nullptr;
181 nsGlobalWindowInner
* win
=
182 WindowOrNull(js::UncheckedUnwrap(obj
, /* stopAtWindowProxy = */ false));
183 if (win
&& win
->GetOuterWindow()) {
184 bc
= win
->GetOuterWindow()->GetBrowsingContext();
191 bc
= dom::GetBrowsingContext(obj
);
195 // We should only have a remote window proxy if bc is in a state where we
196 // expect remote window proxies. Otherwise, they should have been cleaned up
197 // by a call to CleanUpDanglingRemoteOuterWindowProxies().
198 MOZ_RELEASE_ASSERT(isWindowProxy
|| bc
->CanHaveRemoteOuterProxies());
200 if (bc
->IsInProcess()) {
203 // If bc is not in process, then use a remote window proxy, whether or not
204 // obj is one already.
205 if (!dom::GetRemoteOuterWindowProxy(cx
, bc
, origObj
, retObj
)) {
206 MOZ_CRASH("GetRemoteOuterWindowProxy failed");
213 void WrapperFactory::PrepareForWrapping(JSContext
* cx
, HandleObject scope
,
214 HandleObject origObj
,
216 HandleObject objectPassedToWrap
,
217 MutableHandleObject retObj
) {
218 // The JS engine calls ToWindowProxyIfWindow and deals with dead wrappers.
219 MOZ_ASSERT(!js::IsWindow(objArg
));
220 MOZ_ASSERT(!JS_IsDeadWrapper(objArg
));
222 bool waive
= ShouldWaiveXray(cx
, objectPassedToWrap
);
223 RootedObject
obj(cx
, objArg
);
226 // There are a few cases related to window proxies that are handled first to
227 // allow us to assert against wrappers below.
228 if (MaybeWrapWindowProxy(cx
, origObj
, obj
, retObj
)) {
230 // We don't put remote window proxies in a waiving wrapper.
231 MOZ_ASSERT(js::IsWindowProxy(obj
));
232 retObj
.set(WaiveXray(cx
, retObj
));
237 // Here are the rules for wrapping:
238 // We should never get a proxy here (the JS engine unwraps those for us).
239 MOZ_ASSERT(!IsWrapper(obj
));
241 // Now, our object is ready to be wrapped, but several objects (notably
242 // nsJSIIDs) have a wrapper per scope. If we are about to wrap one of
243 // those objects in a security wrapper, then we need to hand back the
244 // wrapper for the new scope instead. Also, global objects don't move
245 // between scopes so for those we also want to return the wrapper. So...
246 if (!IsWrappedNativeReflector(obj
) || JS_IsGlobalObject(obj
)) {
247 retObj
.set(waive
? WaiveXray(cx
, obj
) : obj
);
251 XPCWrappedNative
* wn
= XPCWrappedNative::Get(obj
);
253 JSAutoRealm
ar(cx
, obj
);
254 XPCCallContext
ccx(cx
, obj
);
255 RootedObject
wrapScope(cx
, scope
);
257 if (ccx
.GetScriptable() && ccx
.GetScriptable()->WantPreCreate()) {
258 // We have a precreate hook. This object might enforce that we only
259 // ever create JS object for it.
261 // Note: this penalizes objects that only have one wrapper, but are
262 // being accessed across compartments. We would really prefer to
263 // replace the above code with a test that says "do you only have one
265 nsresult rv
= wn
->GetScriptable()->PreCreate(wn
->Native(), cx
, scope
,
266 wrapScope
.address());
268 retObj
.set(waive
? WaiveXray(cx
, obj
) : obj
);
272 // If the handed back scope differs from the passed-in scope and is in
273 // a separate compartment, then this object is explicitly requesting
274 // that we don't create a second JS object for it: create a security
277 // Note: The only two objects that still use PreCreate are BackstagePass
278 // and Components, both of which unconditionally request their canonical
279 // scope. Since SpiderMonkey only invokes the prewrap callback in
280 // situations where the object is nominally cross-compartment, we should
281 // always get a different scope here.
282 MOZ_RELEASE_ASSERT(JS::GetCompartment(scope
) !=
283 JS::GetCompartment(wrapScope
));
284 retObj
.set(waive
? WaiveXray(cx
, obj
) : obj
);
288 // This public WrapNativeToJSVal API enters the compartment of 'wrapScope'
289 // so we don't have to.
291 nsresult rv
= nsXPConnect::XPConnect()->WrapNativeToJSVal(
292 cx
, wrapScope
, wn
->Native(), nullptr, &NS_GET_IID(nsISupports
), false,
298 obj
.set(&v
.toObject());
299 MOZ_ASSERT(IsWrappedNativeReflector(obj
), "bad object");
300 JS::AssertObjectIsNotGray(obj
); // We should never return gray reflectors.
302 // Because the underlying native didn't have a PreCreate hook, we had
303 // to a new (or possibly pre-existing) XPCWN in our compartment.
304 // This could be a problem for chrome code that passes XPCOM objects
305 // across compartments, because the effects of QI would disappear across
308 // So whenever we pull an XPCWN across compartments in this manner, we
309 // give the destination object the union of the two native sets. We try
310 // to do this cleverly in the common case to avoid too much overhead.
311 XPCWrappedNative
* newwn
= XPCWrappedNative::Get(obj
);
312 RefPtr
<XPCNativeSet
> unionSet
=
313 XPCNativeSet::GetNewOrUsed(cx
, newwn
->GetSet(), wn
->GetSet(), false);
317 newwn
->SetSet(unionSet
.forget());
319 retObj
.set(waive
? WaiveXray(cx
, obj
) : obj
);
322 // This check is completely symmetric, so we don't need to keep track of origin
323 // vs target here. Two compartments may have had transparent CCWs between them
324 // only if they are same-origin (ignoring document.domain) or have both had
325 // document.domain set at some point and are same-site. In either case they
326 // will have the same SiteIdentifier, so check that first.
327 static bool CompartmentsMayHaveHadTransparentCCWs(
328 CompartmentPrivate
* private1
, CompartmentPrivate
* private2
) {
329 auto& info1
= private1
->originInfo
;
330 auto& info2
= private2
->originInfo
;
332 if (!info1
.SiteRef().Equals(info2
.SiteRef())) {
336 return info1
.GetPrincipalIgnoringDocumentDomain()->FastEquals(
337 info2
.GetPrincipalIgnoringDocumentDomain()) ||
338 (info1
.HasChangedDocumentDomain() && info2
.HasChangedDocumentDomain());
342 static void DEBUG_CheckUnwrapSafety(HandleObject obj
,
343 const js::Wrapper
* handler
,
344 JS::Realm
* origin
, JS::Realm
* target
) {
345 JS::Compartment
* targetCompartment
= JS::GetCompartmentForRealm(target
);
346 if (!js::AllowNewWrapper(targetCompartment
, obj
)) {
347 // The JS engine should have returned a dead wrapper in this case and we
348 // shouldn't even get here.
349 MOZ_ASSERT_UNREACHABLE("CheckUnwrapSafety called for a dead wrapper");
350 } else if (AccessCheck::isChrome(targetCompartment
)) {
351 // If the caller is chrome (or effectively so), unwrap should always be
352 // allowed, but we might have a CrossOriginObjectWrapper here which allows
354 MOZ_ASSERT(!handler
->hasSecurityPolicy() ||
355 handler
== &CrossOriginObjectWrapper::singleton
);
357 // Otherwise, it should depend on whether the target subsumes the origin.
359 (OriginAttributes::IsRestrictOpenerAccessForFPI()
360 ? AccessCheck::subsumesConsideringDomain(target
, origin
)
361 : AccessCheck::subsumesConsideringDomainIgnoringFPD(target
,
364 // If the target (which is where the wrapper lives) does not subsume the
365 // origin (which is where the wrapped object lives), then we should
366 // generally have a security check on the wrapper here. There is one
367 // exception, though: things that used to be same-origin and then stopped
368 // due to document.domain changes. In that case we will have a
369 // transparent cross-compartment wrapper here even though "subsumes" is no
371 CompartmentPrivate
* originCompartmentPrivate
=
372 CompartmentPrivate::Get(origin
);
373 CompartmentPrivate
* targetCompartmentPrivate
=
374 CompartmentPrivate::Get(target
);
375 if (!originCompartmentPrivate
->wantXrays
&&
376 !targetCompartmentPrivate
->wantXrays
&&
377 CompartmentsMayHaveHadTransparentCCWs(originCompartmentPrivate
,
378 targetCompartmentPrivate
)) {
379 // We should have a transparent CCW, unless we have a cross-origin
380 // object, in which case it will be a CrossOriginObjectWrapper.
381 MOZ_ASSERT(handler
== &CrossCompartmentWrapper::singleton
||
382 handler
== &CrossOriginObjectWrapper::singleton
);
384 MOZ_ASSERT(handler
->hasSecurityPolicy());
387 // Even if target subsumes origin, we might have a wrapper with a security
388 // policy here, if it happens to be a CrossOriginObjectWrapper.
389 MOZ_ASSERT(!handler
->hasSecurityPolicy() ||
390 handler
== &CrossOriginObjectWrapper::singleton
);
395 # define DEBUG_CheckUnwrapSafety(obj, handler, origin, target) \
399 const CrossOriginObjectWrapper
CrossOriginObjectWrapper::singleton
;
401 bool CrossOriginObjectWrapper::dynamicCheckedUnwrapAllowed(
402 HandleObject obj
, JSContext
* cx
) const {
403 MOZ_ASSERT(js::GetProxyHandler(obj
) == this,
404 "Why are we getting called for some random object?");
405 JSObject
* target
= wrappedObject(obj
);
406 return dom::MaybeCrossOriginObjectMixins::IsPlatformObjectSameOrigin(cx
,
410 static const Wrapper
* SelectWrapper(bool securityWrapper
, XrayType xrayType
,
411 bool waiveXrays
, JSObject
* obj
) {
412 // Waived Xray uses a modified CCW that has transparent behavior but
413 // transitively waives Xrays on arguments.
415 MOZ_ASSERT(!securityWrapper
);
416 return &WaiveXrayWrapper::singleton
;
419 // If we don't want or can't use Xrays, select a wrapper that's either
420 // entirely transparent or entirely opaque.
421 if (xrayType
== NotXray
) {
422 if (!securityWrapper
) {
423 return &CrossCompartmentWrapper::singleton
;
425 return &FilteringWrapper
<CrossCompartmentSecurityWrapper
,
429 // Ok, we're using Xray. If this isn't a security wrapper, use the permissive
430 // version and skip the filter.
431 if (!securityWrapper
) {
432 if (xrayType
== XrayForDOMObject
) {
433 return &PermissiveXrayDOM::singleton
;
434 } else if (xrayType
== XrayForJSObject
) {
435 return &PermissiveXrayJS::singleton
;
437 MOZ_ASSERT(xrayType
== XrayForOpaqueObject
);
438 return &PermissiveXrayOpaque::singleton
;
441 // There's never any reason to expose other objects to non-subsuming actors.
442 // Just use an opaque wrapper in these cases.
443 return &FilteringWrapper
<CrossCompartmentSecurityWrapper
, Opaque
>::singleton
;
446 JSObject
* WrapperFactory::Rewrap(JSContext
* cx
, HandleObject existing
,
448 MOZ_ASSERT(!IsWrapper(obj
) || GetProxyHandler(obj
) == &XrayWaiver
||
449 js::IsWindowProxy(obj
),
450 "wrapped object passed to rewrap");
451 MOZ_ASSERT(!js::IsWindow(obj
));
452 MOZ_ASSERT(dom::IsJSAPIActive());
454 // Compute the information we need to select the right wrapper.
455 JS::Realm
* origin
= js::GetNonCCWObjectRealm(obj
);
456 JS::Realm
* target
= js::GetContextRealm(cx
);
457 MOZ_ASSERT(target
, "Why is our JSContext not in a Realm?");
458 bool originIsChrome
= AccessCheck::isChrome(origin
);
459 bool targetIsChrome
= AccessCheck::isChrome(target
);
460 bool originSubsumesTarget
=
461 OriginAttributes::IsRestrictOpenerAccessForFPI()
462 ? AccessCheck::subsumesConsideringDomain(origin
, target
)
463 : AccessCheck::subsumesConsideringDomainIgnoringFPD(origin
, target
);
464 bool targetSubsumesOrigin
=
465 OriginAttributes::IsRestrictOpenerAccessForFPI()
466 ? AccessCheck::subsumesConsideringDomain(target
, origin
)
467 : AccessCheck::subsumesConsideringDomainIgnoringFPD(target
, origin
);
468 bool sameOrigin
= targetSubsumesOrigin
&& originSubsumesTarget
;
470 const Wrapper
* wrapper
;
472 CompartmentPrivate
* originCompartmentPrivate
=
473 CompartmentPrivate::Get(origin
);
474 CompartmentPrivate
* targetCompartmentPrivate
=
475 CompartmentPrivate::Get(target
);
477 // Track whether we decided to use a transparent wrapper because of
478 // document.domain usage, so we don't override that decision.
479 bool isTransparentWrapperDueToDocumentDomain
= false;
482 // First, handle the special cases.
485 // Special handling for chrome objects being exposed to content.
486 if (originIsChrome
&& !targetIsChrome
) {
487 // If this is a chrome function being exposed to content, we need to allow
488 // call (but nothing else).
489 JSProtoKey key
= IdentifyStandardInstance(obj
);
490 if (key
== JSProto_Function
|| key
== JSProto_BoundFunction
) {
491 wrapper
= &FilteringWrapper
<CrossCompartmentSecurityWrapper
,
492 OpaqueWithCall
>::singleton
;
495 // For vanilla JSObjects exposed from chrome to content, we use a wrapper
496 // that fails silently in a few cases. We'd like to get rid of this
497 // eventually, but in their current form they don't cause much trouble.
498 else if (key
== JSProto_Object
) {
499 wrapper
= &ChromeObjectWrapper::singleton
;
502 // Otherwise we get an opaque wrapper.
505 &FilteringWrapper
<CrossCompartmentSecurityWrapper
, Opaque
>::singleton
;
509 // Special handling for the web's cross-origin objects (WindowProxy and
510 // Location). We only need or want to do this in web-like contexts, where all
511 // security relationships are symmetric and there are no forced Xrays.
512 else if (originSubsumesTarget
== targetSubsumesOrigin
&&
513 // Check for the more rare case of cross-origin objects before doing
514 // the more-likely-to-pass checks for wantXrays.
515 IsCrossOriginAccessibleObject(obj
) &&
516 (!targetSubsumesOrigin
|| (!originCompartmentPrivate
->wantXrays
&&
517 !targetCompartmentPrivate
->wantXrays
))) {
518 wrapper
= &CrossOriginObjectWrapper::singleton
;
521 // Special handling for other web objects. Again, we only want this in
522 // web-like contexts (symmetric security relationships, no forced Xrays). In
523 // this situation, if the two compartments may ever have had transparent CCWs
524 // between them, we want to keep using transparent CCWs.
525 else if (originSubsumesTarget
== targetSubsumesOrigin
&&
526 !originCompartmentPrivate
->wantXrays
&&
527 !targetCompartmentPrivate
->wantXrays
&&
528 CompartmentsMayHaveHadTransparentCCWs(originCompartmentPrivate
,
529 targetCompartmentPrivate
)) {
530 isTransparentWrapperDueToDocumentDomain
= true;
531 wrapper
= &CrossCompartmentWrapper::singleton
;
535 // Now, handle the regular cases.
537 // These are wrappers we can compute using a rule-based approach. In order
538 // to do so, we need to compute some parameters.
541 // The wrapper is a security wrapper (protecting the wrappee) if and
542 // only if the target does not subsume the origin.
543 bool securityWrapper
= !targetSubsumesOrigin
;
545 // Xrays are warranted if either the target or the origin don't trust
546 // each other. This is generally the case, unless the two are same-origin
547 // and the caller has not requested same-origin Xrays.
549 // Xrays are a bidirectional protection, since it affords clarity to the
550 // caller and privacy to the callee.
551 bool sameOriginXrays
= originCompartmentPrivate
->wantXrays
||
552 targetCompartmentPrivate
->wantXrays
;
553 bool wantXrays
= !sameOrigin
|| sameOriginXrays
;
555 XrayType xrayType
= wantXrays
? GetXrayType(obj
) : NotXray
;
557 // If Xrays are warranted, the caller may waive them for non-security
558 // wrappers (unless explicitly forbidden from doing so).
559 bool waiveXrays
= wantXrays
&& !securityWrapper
&&
560 targetCompartmentPrivate
->allowWaivers
&&
561 HasWaiveXrayFlag(obj
);
563 wrapper
= SelectWrapper(securityWrapper
, xrayType
, waiveXrays
, obj
);
566 if (!targetSubsumesOrigin
&& !isTransparentWrapperDueToDocumentDomain
) {
567 // Do a belt-and-suspenders check against exposing eval()/Function() to
568 // non-subsuming content.
569 if (JSFunction
* fun
= JS_GetObjectFunction(obj
)) {
570 if (JS_IsBuiltinEvalFunction(fun
) ||
571 JS_IsBuiltinFunctionConstructor(fun
)) {
573 "Trying to expose eval or Function to non-subsuming content!");
574 wrapper
= &FilteringWrapper
<CrossCompartmentSecurityWrapper
,
580 DEBUG_CheckUnwrapSafety(obj
, wrapper
, origin
, target
);
583 return Wrapper::Renew(existing
, obj
, wrapper
);
586 return Wrapper::New(cx
, obj
, wrapper
);
589 // Call WaiveXrayAndWrap when you have a JS object that you don't want to be
590 // wrapped in an Xray wrapper. cx->compartment is the compartment that will be
591 // using the returned object. If the object to be wrapped is already in the
592 // correct compartment, then this returns the unwrapped object.
593 bool WrapperFactory::WaiveXrayAndWrap(JSContext
* cx
, MutableHandleValue vp
) {
594 if (vp
.isPrimitive()) {
595 return JS_WrapValue(cx
, vp
);
598 RootedObject
obj(cx
, &vp
.toObject());
599 if (!WaiveXrayAndWrap(cx
, &obj
)) {
607 bool WrapperFactory::WaiveXrayAndWrap(JSContext
* cx
,
608 MutableHandleObject argObj
) {
610 RootedObject
obj(cx
, js::UncheckedUnwrap(argObj
));
611 MOZ_ASSERT(!js::IsWindow(obj
));
612 if (js::IsObjectInContextCompartment(obj
, cx
)) {
617 // Even though waivers have no effect on access by scopes that don't subsume
618 // the underlying object, good defense-in-depth dictates that we should avoid
619 // handing out waivers to callers that can't use them. The transitive waiving
620 // machinery unconditionally calls WaiveXrayAndWrap on return values from
621 // waived functions, even though the return value might be not be same-origin
622 // with the function. So if we find ourselves trying to create a waiver for
623 // |cx|, we should check whether the caller has any business with waivers
624 // to things in |obj|'s compartment.
625 JS::Compartment
* target
= js::GetContextCompartment(cx
);
626 JS::Compartment
* origin
= JS::GetCompartment(obj
);
627 obj
= AllowWaiver(target
, origin
) ? WaiveXray(cx
, obj
) : obj
;
632 if (!JS_WrapObject(cx
, &obj
)) {
640 * Calls to JS_TransplantObject* should go through these helpers here so that
641 * waivers get fixed up properly.
644 static bool FixWaiverAfterTransplant(JSContext
* cx
, HandleObject oldWaiver
,
646 bool crossCompartmentTransplant
) {
647 MOZ_ASSERT(Wrapper::wrapperHandler(oldWaiver
) == &XrayWaiver
);
648 MOZ_ASSERT(!js::IsCrossCompartmentWrapper(newobj
));
650 if (crossCompartmentTransplant
) {
651 // If the new compartment has a CCW for oldWaiver, nuke this CCW. This
652 // prevents confusing RemapAllWrappersForObject: it would call RemapWrapper
653 // with two same-compartment objects (the CCW and the new waiver).
655 // This can happen when loading a chrome page in a content frame and there
656 // exists a CCW from the chrome compartment to oldWaiver wrapping the window
657 // we just transplanted:
659 // Compartment 1 | Compartment 2
660 // ----------------------------------------
661 // CCW1 -----------> oldWaiver --> CCW2 --+
663 // WindowProxy <--------------------------+
664 js::NukeCrossCompartmentWrapperIfExists(cx
, JS::GetCompartment(newobj
),
667 // We kept the same object identity, so the waiver should be a
668 // waiver for our object, just in the wrong Realm.
669 MOZ_ASSERT(newobj
== Wrapper::wrappedObject(oldWaiver
));
672 // Create a waiver in the new compartment. We know there's not one already in
673 // the crossCompartmentTransplant case because we _just_ transplanted, which
674 // means that |newobj| was either created from scratch, or was previously
675 // cross-compartment wrapper (which should have no waiver). On the other hand,
676 // in the !crossCompartmentTransplant case we know one already exists.
677 // CreateXrayWaiver asserts all this.
678 RootedObject
newWaiver(
679 cx
, WrapperFactory::CreateXrayWaiver(
680 cx
, newobj
, /* allowExisting = */ !crossCompartmentTransplant
));
685 if (!crossCompartmentTransplant
) {
686 // CreateXrayWaiver should have updated the map to point to the new waiver.
687 MOZ_ASSERT(WrapperFactory::GetXrayWaiver(newobj
) == newWaiver
);
690 // Update all the cross-compartment references to oldWaiver to point to
692 if (!js::RemapAllWrappersForObject(cx
, oldWaiver
, newWaiver
)) {
696 if (crossCompartmentTransplant
) {
697 // There should be no same-compartment references to oldWaiver, and we
698 // just remapped all cross-compartment references. It's dead, so we can
699 // remove it from the map.
700 XPCWrappedNativeScope
* scope
= ObjectScope(oldWaiver
);
701 JSObject
* key
= Wrapper::wrappedObject(oldWaiver
);
702 MOZ_ASSERT(scope
->mWaiverWrapperMap
->Find(key
));
703 scope
->mWaiverWrapperMap
->Remove(key
);
709 JSObject
* TransplantObject(JSContext
* cx
, JS::HandleObject origobj
,
710 JS::HandleObject target
) {
711 RootedObject
oldWaiver(cx
, WrapperFactory::GetXrayWaiver(origobj
));
712 MOZ_ASSERT_IF(oldWaiver
, GetNonCCWObjectRealm(oldWaiver
) ==
713 GetNonCCWObjectRealm(origobj
));
714 RootedObject
newIdentity(cx
, JS_TransplantObject(cx
, origobj
, target
));
715 if (!newIdentity
|| !oldWaiver
) {
719 bool crossCompartmentTransplant
= (newIdentity
!= origobj
);
720 if (!crossCompartmentTransplant
) {
721 // We might still have been transplanted across realms within a single
723 if (GetNonCCWObjectRealm(oldWaiver
) == GetNonCCWObjectRealm(newIdentity
)) {
724 // The old waiver is same-realm with the new object; nothing else to do
730 if (!FixWaiverAfterTransplant(cx
, oldWaiver
, newIdentity
,
731 crossCompartmentTransplant
)) {
737 JSObject
* TransplantObjectRetainingXrayExpandos(JSContext
* cx
,
738 JS::HandleObject origobj
,
739 JS::HandleObject target
) {
740 // Save the chain of objects that carry origobj's Xray expando properties
741 // (from all compartments). TransplantObject will blow this away; we'll
742 // restore it manually afterwards.
743 RootedObject
expandoChain(
744 cx
, GetXrayTraits(origobj
)->detachExpandoChain(origobj
));
746 RootedObject
newIdentity(cx
, TransplantObject(cx
, origobj
, target
));
748 // Copy Xray expando properties to the new wrapper.
749 if (!GetXrayTraits(newIdentity
)
750 ->cloneExpandoChain(cx
, newIdentity
, expandoChain
)) {
751 // Failure here means some expandos were not copied over. The object graph
752 // and the Xray machinery are left in a consistent state, but mysteriously
753 // losing these expandos is too weird to allow.
760 static void NukeXrayWaiver(JSContext
* cx
, JS::HandleObject obj
) {
761 RootedObject
waiver(cx
, WrapperFactory::GetXrayWaiver(obj
));
766 XPCWrappedNativeScope
* scope
= ObjectScope(waiver
);
767 JSObject
* key
= Wrapper::wrappedObject(waiver
);
768 MOZ_ASSERT(scope
->mWaiverWrapperMap
->Find(key
));
769 scope
->mWaiverWrapperMap
->Remove(key
);
771 js::NukeNonCCWProxy(cx
, waiver
);
773 // Get rid of any CCWs the waiver may have had.
774 if (!JS_RefreshCrossCompartmentWrappers(cx
, waiver
)) {
779 JSObject
* TransplantObjectNukingXrayWaiver(JSContext
* cx
,
780 JS::HandleObject origObj
,
781 JS::HandleObject target
) {
782 NukeXrayWaiver(cx
, origObj
);
783 return JS_TransplantObject(cx
, origObj
, target
);
786 nsIGlobalObject
* NativeGlobal(JSObject
* obj
) {
787 obj
= JS::GetNonCCWObjectGlobal(obj
);
789 // Every global needs to hold a native as its first reserved slot or be a
790 // WebIDL object with an nsISupports DOM object.
791 MOZ_ASSERT(JS::GetClass(obj
)->slot0IsISupports() ||
792 dom::UnwrapDOMObjectToISupports(obj
));
794 nsISupports
* native
= dom::UnwrapDOMObjectToISupports(obj
);
796 native
= JS::GetObjectISupports
<nsISupports
>(obj
);
799 // In some cases (like for windows) it is a wrapped native,
800 // in other cases (sandboxes, backstage passes) it's just
801 // a direct pointer to the native. If it's a wrapped native
802 // let's unwrap it first.
803 if (nsCOMPtr
<nsIXPConnectWrappedNative
> wn
= do_QueryInterface(native
)) {
804 native
= wn
->Native();
808 nsCOMPtr
<nsIGlobalObject
> global
= do_QueryInterface(native
);
810 "Native held by global needs to implement nsIGlobalObject!");
815 nsIGlobalObject
* CurrentNativeGlobal(JSContext
* cx
) {
816 return xpc::NativeGlobal(JS::CurrentGlobalOrNull(cx
));