Bug 1943761 - Add class alignment to the mozsearch analysis file. r=asuth
[gecko.git] / js / xpconnect / wrappers / WrapperFactory.cpp
blob0fcc9249954ffc7a3b5fd12009c33c6b3ba3e753
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"
16 #include "XPCMaps.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"
28 using namespace JS;
29 using namespace js;
30 using namespace mozilla;
32 namespace xpc {
34 #ifndef MOZ_UNIFIED_BUILD
35 extern template class FilteringWrapper<js::CrossCompartmentSecurityWrapper,
36 Opaque>;
37 extern template class FilteringWrapper<js::CrossCompartmentSecurityWrapper,
38 OpaqueWithCall>;
39 #endif
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
53 // off it.
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);
71 MOZ_ASSERT(scope);
73 if (!scope->mWaiverWrapperMap) {
74 return nullptr;
77 return scope->mWaiverWrapperMap->Find(obj);
80 JSObject* WrapperFactory::CreateXrayWaiver(JSContext* cx, HandleObject obj,
81 bool allowExisting) {
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);
90 if (!waiver) {
91 return nullptr;
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)) {
100 return nullptr;
102 return 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);
111 if (!waiver) {
112 waiver = CreateXrayWaiver(cx, obj);
114 JS::AssertObjectIsNotGray(waiver);
115 return waiver;
118 /* static */
119 bool WrapperFactory::AllowWaiver(JS::Compartment* target,
120 JS::Compartment* origin) {
121 return CompartmentPrivate::Get(target)->allowWaivers &&
122 CompartmentOriginInfo::Subsumes(target, origin);
125 /* static */
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) {
133 unsigned flags;
134 (void)js::UncheckedUnwrap(originalObj, /* stopAtWindowProxy = */ true,
135 &flags);
137 // If the original object did not point through an Xray waiver, we're done.
138 if (!(flags & WrapperFactory::WAIVE_XRAY_WRAPPER_FLAG)) {
139 return false;
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)) {
146 return true;
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()) {
156 sameOrigin =
157 CompartmentOriginInfo::Subsumes(oldCompartment, newCompartment) &&
158 CompartmentOriginInfo::Subsumes(newCompartment, oldCompartment);
159 } else {
160 sameOrigin = CompartmentOriginInfo::SubsumesIgnoringFPD(oldCompartment,
161 newCompartment) &&
162 CompartmentOriginInfo::SubsumesIgnoringFPD(newCompartment,
163 oldCompartment);
165 return sameOrigin;
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)) {
176 return false;
179 dom::BrowsingContext* bc = nullptr;
180 if (isWindowProxy) {
181 nsGlobalWindowInner* win =
182 WindowOrNull(js::UncheckedUnwrap(obj, /* stopAtWindowProxy = */ false));
183 if (win && win->GetOuterWindow()) {
184 bc = win->GetOuterWindow()->GetBrowsingContext();
186 if (!bc) {
187 retObj.set(obj);
188 return true;
190 } else {
191 bc = dom::GetBrowsingContext(obj);
192 MOZ_ASSERT(bc);
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()) {
201 retObj.set(obj);
202 } else {
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");
210 return true;
213 void WrapperFactory::PrepareForWrapping(JSContext* cx, HandleObject scope,
214 HandleObject origObj,
215 HandleObject objArg,
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);
224 retObj.set(nullptr);
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)) {
229 if (waive) {
230 // We don't put remote window proxies in a waiving wrapper.
231 MOZ_ASSERT(js::IsWindowProxy(obj));
232 retObj.set(WaiveXray(cx, retObj));
234 return;
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);
248 return;
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
264 // wrapper?"
265 nsresult rv = wn->GetScriptable()->PreCreate(wn->Native(), cx, scope,
266 wrapScope.address());
267 if (NS_FAILED(rv)) {
268 retObj.set(waive ? WaiveXray(cx, obj) : obj);
269 return;
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
275 // wrapper.
277 // Note: The only two objects that still use PreCreate are SystemGlobal
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);
285 return;
288 // This public WrapNativeToJSVal API enters the compartment of 'wrapScope'
289 // so we don't have to.
290 RootedValue v(cx);
291 nsresult rv = nsXPConnect::XPConnect()->WrapNativeToJSVal(
292 cx, wrapScope, wn->Native(), nullptr, &NS_GET_IID(nsISupports), false,
293 &v);
294 if (NS_FAILED(rv)) {
295 return;
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
306 // compartments.
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);
314 if (!unionSet) {
315 return;
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())) {
333 return false;
336 return info1.GetPrincipalIgnoringDocumentDomain()->FastEquals(
337 info2.GetPrincipalIgnoringDocumentDomain()) ||
338 (info1.HasChangedDocumentDomain() && info2.HasChangedDocumentDomain());
341 #ifdef DEBUG
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
353 // it dynamically.
354 MOZ_ASSERT(!handler->hasSecurityPolicy() ||
355 handler == &CrossOriginObjectWrapper::singleton);
356 } else {
357 // Otherwise, it should depend on whether the target subsumes the origin.
358 bool subsumes =
359 (OriginAttributes::IsRestrictOpenerAccessForFPI()
360 ? AccessCheck::subsumesConsideringDomain(target, origin)
361 : AccessCheck::subsumesConsideringDomainIgnoringFPD(target,
362 origin));
363 if (!subsumes) {
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
370 // longer true.
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);
383 } else {
384 MOZ_ASSERT(handler->hasSecurityPolicy());
386 } else {
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);
394 #else
395 # define DEBUG_CheckUnwrapSafety(obj, handler, origin, target) \
398 #endif
400 const CrossOriginObjectWrapper CrossOriginObjectWrapper::singleton;
402 bool CrossOriginObjectWrapper::dynamicCheckedUnwrapAllowed(
403 HandleObject obj, JSContext* cx) const {
404 MOZ_ASSERT(js::GetProxyHandler(obj) == this,
405 "Why are we getting called for some random object?");
406 JSObject* target = wrappedObject(obj);
407 return dom::MaybeCrossOriginObjectMixins::IsPlatformObjectSameOrigin(cx,
408 target);
411 static const Wrapper* SelectWrapper(bool securityWrapper, XrayType xrayType,
412 bool waiveXrays, JSObject* obj) {
413 // Waived Xray uses a modified CCW that has transparent behavior but
414 // transitively waives Xrays on arguments.
415 if (waiveXrays) {
416 MOZ_ASSERT(!securityWrapper);
417 return &WaiveXrayWrapper::singleton;
420 // If we don't want or can't use Xrays, select a wrapper that's either
421 // entirely transparent or entirely opaque.
422 if (xrayType == NotXray) {
423 if (!securityWrapper) {
424 return &CrossCompartmentWrapper::singleton;
426 return &FilteringWrapper<CrossCompartmentSecurityWrapper,
427 Opaque>::singleton;
430 // Ok, we're using Xray. If this isn't a security wrapper, use the permissive
431 // version and skip the filter.
432 if (!securityWrapper) {
433 if (xrayType == XrayForDOMObject) {
434 return &PermissiveXrayDOM::singleton;
435 } else if (xrayType == XrayForJSObject) {
436 return &PermissiveXrayJS::singleton;
438 MOZ_ASSERT(xrayType == XrayForOpaqueObject);
439 return &PermissiveXrayOpaque::singleton;
442 // There's never any reason to expose other objects to non-subsuming actors.
443 // Just use an opaque wrapper in these cases.
444 return &FilteringWrapper<CrossCompartmentSecurityWrapper, Opaque>::singleton;
447 JSObject* WrapperFactory::Rewrap(JSContext* cx, HandleObject existing,
448 HandleObject obj) {
449 MOZ_ASSERT(!IsWrapper(obj) || GetProxyHandler(obj) == &XrayWaiver ||
450 js::IsWindowProxy(obj),
451 "wrapped object passed to rewrap");
452 MOZ_ASSERT(!js::IsWindow(obj));
453 MOZ_ASSERT(dom::IsJSAPIActive());
455 // Compute the information we need to select the right wrapper.
456 JS::Realm* origin = js::GetNonCCWObjectRealm(obj);
457 JS::Realm* target = js::GetContextRealm(cx);
458 MOZ_ASSERT(target, "Why is our JSContext not in a Realm?");
459 bool originIsChrome = AccessCheck::isChrome(origin);
460 bool targetIsChrome = AccessCheck::isChrome(target);
461 bool originSubsumesTarget =
462 OriginAttributes::IsRestrictOpenerAccessForFPI()
463 ? AccessCheck::subsumesConsideringDomain(origin, target)
464 : AccessCheck::subsumesConsideringDomainIgnoringFPD(origin, target);
465 bool targetSubsumesOrigin =
466 OriginAttributes::IsRestrictOpenerAccessForFPI()
467 ? AccessCheck::subsumesConsideringDomain(target, origin)
468 : AccessCheck::subsumesConsideringDomainIgnoringFPD(target, origin);
469 bool sameOrigin = targetSubsumesOrigin && originSubsumesTarget;
471 const Wrapper* wrapper;
473 CompartmentPrivate* originCompartmentPrivate =
474 CompartmentPrivate::Get(origin);
475 CompartmentPrivate* targetCompartmentPrivate =
476 CompartmentPrivate::Get(target);
478 // Track whether we decided to use a transparent wrapper because of
479 // document.domain usage, so we don't override that decision.
480 bool isTransparentWrapperDueToDocumentDomain = false;
483 // First, handle the special cases.
486 // Special handling for chrome objects being exposed to content.
487 if (originIsChrome && !targetIsChrome) {
488 // If this is a chrome function being exposed to content, we need to allow
489 // call (but nothing else).
490 JSProtoKey key = IdentifyStandardInstance(obj);
491 if (key == JSProto_Function || key == JSProto_BoundFunction) {
492 wrapper = &FilteringWrapper<CrossCompartmentSecurityWrapper,
493 OpaqueWithCall>::singleton;
496 // For vanilla JSObjects exposed from chrome to content, we use a wrapper
497 // that fails silently in a few cases. We'd like to get rid of this
498 // eventually, but in their current form they don't cause much trouble.
499 else if (key == JSProto_Object) {
500 wrapper = &ChromeObjectWrapper::singleton;
503 // Otherwise we get an opaque wrapper.
504 else {
505 wrapper =
506 &FilteringWrapper<CrossCompartmentSecurityWrapper, Opaque>::singleton;
510 // Special handling for the web's cross-origin objects (WindowProxy and
511 // Location). We only need or want to do this in web-like contexts, where all
512 // security relationships are symmetric and there are no forced Xrays.
513 else if (originSubsumesTarget == targetSubsumesOrigin &&
514 // Check for the more rare case of cross-origin objects before doing
515 // the more-likely-to-pass checks for wantXrays.
516 IsCrossOriginAccessibleObject(obj) &&
517 (!targetSubsumesOrigin || (!originCompartmentPrivate->wantXrays &&
518 !targetCompartmentPrivate->wantXrays))) {
519 wrapper = &CrossOriginObjectWrapper::singleton;
522 // Special handling for other web objects. Again, we only want this in
523 // web-like contexts (symmetric security relationships, no forced Xrays). In
524 // this situation, if the two compartments may ever have had transparent CCWs
525 // between them, we want to keep using transparent CCWs.
526 else if (originSubsumesTarget == targetSubsumesOrigin &&
527 !originCompartmentPrivate->wantXrays &&
528 !targetCompartmentPrivate->wantXrays &&
529 CompartmentsMayHaveHadTransparentCCWs(originCompartmentPrivate,
530 targetCompartmentPrivate)) {
531 isTransparentWrapperDueToDocumentDomain = true;
532 wrapper = &CrossCompartmentWrapper::singleton;
536 // Now, handle the regular cases.
538 // These are wrappers we can compute using a rule-based approach. In order
539 // to do so, we need to compute some parameters.
541 else {
542 // The wrapper is a security wrapper (protecting the wrappee) if and
543 // only if the target does not subsume the origin.
544 bool securityWrapper = !targetSubsumesOrigin;
546 // Xrays are warranted if either the target or the origin don't trust
547 // each other. This is generally the case, unless the two are same-origin
548 // and the caller has not requested same-origin Xrays.
550 // Xrays are a bidirectional protection, since it affords clarity to the
551 // caller and privacy to the callee.
552 bool sameOriginXrays = originCompartmentPrivate->wantXrays ||
553 targetCompartmentPrivate->wantXrays;
554 bool wantXrays = !sameOrigin || sameOriginXrays;
556 XrayType xrayType = wantXrays ? GetXrayType(obj) : NotXray;
558 // If Xrays are warranted, the caller may waive them for non-security
559 // wrappers (unless explicitly forbidden from doing so).
560 bool waiveXrays = wantXrays && !securityWrapper &&
561 targetCompartmentPrivate->allowWaivers &&
562 HasWaiveXrayFlag(obj);
564 wrapper = SelectWrapper(securityWrapper, xrayType, waiveXrays, obj);
567 if (!targetSubsumesOrigin && !isTransparentWrapperDueToDocumentDomain) {
568 // Do a belt-and-suspenders check against exposing eval()/Function() to
569 // non-subsuming content.
570 if (JSFunction* fun = JS_GetObjectFunction(obj)) {
571 if (JS_IsBuiltinEvalFunction(fun) ||
572 JS_IsBuiltinFunctionConstructor(fun)) {
573 NS_WARNING(
574 "Trying to expose eval or Function to non-subsuming content!");
575 wrapper = &FilteringWrapper<CrossCompartmentSecurityWrapper,
576 Opaque>::singleton;
581 DEBUG_CheckUnwrapSafety(obj, wrapper, origin, target);
583 if (existing) {
584 return Wrapper::Renew(existing, obj, wrapper);
587 return Wrapper::New(cx, obj, wrapper);
590 // Call WaiveXrayAndWrap when you have a JS object that you don't want to be
591 // wrapped in an Xray wrapper. cx->compartment is the compartment that will be
592 // using the returned object. If the object to be wrapped is already in the
593 // correct compartment, then this returns the unwrapped object.
594 bool WrapperFactory::WaiveXrayAndWrap(JSContext* cx, MutableHandleValue vp) {
595 if (vp.isPrimitive()) {
596 return JS_WrapValue(cx, vp);
599 RootedObject obj(cx, &vp.toObject());
600 if (!WaiveXrayAndWrap(cx, &obj)) {
601 return false;
604 vp.setObject(*obj);
605 return true;
608 bool WrapperFactory::WaiveXrayAndWrap(JSContext* cx,
609 MutableHandleObject argObj) {
610 MOZ_ASSERT(argObj);
611 RootedObject obj(cx, js::UncheckedUnwrap(argObj));
612 MOZ_ASSERT(!js::IsWindow(obj));
613 if (js::IsObjectInContextCompartment(obj, cx)) {
614 argObj.set(obj);
615 return true;
618 // Even though waivers have no effect on access by scopes that don't subsume
619 // the underlying object, good defense-in-depth dictates that we should avoid
620 // handing out waivers to callers that can't use them. The transitive waiving
621 // machinery unconditionally calls WaiveXrayAndWrap on return values from
622 // waived functions, even though the return value might be not be same-origin
623 // with the function. So if we find ourselves trying to create a waiver for
624 // |cx|, we should check whether the caller has any business with waivers
625 // to things in |obj|'s compartment.
626 JS::Compartment* target = js::GetContextCompartment(cx);
627 JS::Compartment* origin = JS::GetCompartment(obj);
628 obj = AllowWaiver(target, origin) ? WaiveXray(cx, obj) : obj;
629 if (!obj) {
630 return false;
633 if (!JS_WrapObject(cx, &obj)) {
634 return false;
636 argObj.set(obj);
637 return true;
641 * Calls to JS_TransplantObject* should go through these helpers here so that
642 * waivers get fixed up properly.
645 static bool FixWaiverAfterTransplant(JSContext* cx, HandleObject oldWaiver,
646 HandleObject newobj,
647 bool crossCompartmentTransplant) {
648 MOZ_ASSERT(Wrapper::wrapperHandler(oldWaiver) == &XrayWaiver);
649 MOZ_ASSERT(!js::IsCrossCompartmentWrapper(newobj));
651 if (crossCompartmentTransplant) {
652 // If the new compartment has a CCW for oldWaiver, nuke this CCW. This
653 // prevents confusing RemapAllWrappersForObject: it would call RemapWrapper
654 // with two same-compartment objects (the CCW and the new waiver).
656 // This can happen when loading a chrome page in a content frame and there
657 // exists a CCW from the chrome compartment to oldWaiver wrapping the window
658 // we just transplanted:
660 // Compartment 1 | Compartment 2
661 // ----------------------------------------
662 // CCW1 -----------> oldWaiver --> CCW2 --+
663 // newWaiver |
664 // WindowProxy <--------------------------+
665 js::NukeCrossCompartmentWrapperIfExists(cx, JS::GetCompartment(newobj),
666 oldWaiver);
667 } else {
668 // We kept the same object identity, so the waiver should be a
669 // waiver for our object, just in the wrong Realm.
670 MOZ_ASSERT(newobj == Wrapper::wrappedObject(oldWaiver));
673 // Create a waiver in the new compartment. We know there's not one already in
674 // the crossCompartmentTransplant case because we _just_ transplanted, which
675 // means that |newobj| was either created from scratch, or was previously
676 // cross-compartment wrapper (which should have no waiver). On the other hand,
677 // in the !crossCompartmentTransplant case we know one already exists.
678 // CreateXrayWaiver asserts all this.
679 RootedObject newWaiver(
680 cx, WrapperFactory::CreateXrayWaiver(
681 cx, newobj, /* allowExisting = */ !crossCompartmentTransplant));
682 if (!newWaiver) {
683 return false;
686 if (!crossCompartmentTransplant) {
687 // CreateXrayWaiver should have updated the map to point to the new waiver.
688 MOZ_ASSERT(WrapperFactory::GetXrayWaiver(newobj) == newWaiver);
691 // Update all the cross-compartment references to oldWaiver to point to
692 // newWaiver.
693 if (!js::RemapAllWrappersForObject(cx, oldWaiver, newWaiver)) {
694 return false;
697 if (crossCompartmentTransplant) {
698 // There should be no same-compartment references to oldWaiver, and we
699 // just remapped all cross-compartment references. It's dead, so we can
700 // remove it from the map.
701 XPCWrappedNativeScope* scope = ObjectScope(oldWaiver);
702 JSObject* key = Wrapper::wrappedObject(oldWaiver);
703 MOZ_ASSERT(scope->mWaiverWrapperMap->Find(key));
704 scope->mWaiverWrapperMap->Remove(key);
707 return true;
710 JSObject* TransplantObject(JSContext* cx, JS::HandleObject origobj,
711 JS::HandleObject target) {
712 RootedObject oldWaiver(cx, WrapperFactory::GetXrayWaiver(origobj));
713 MOZ_ASSERT_IF(oldWaiver, GetNonCCWObjectRealm(oldWaiver) ==
714 GetNonCCWObjectRealm(origobj));
715 RootedObject newIdentity(cx, JS_TransplantObject(cx, origobj, target));
716 if (!newIdentity || !oldWaiver) {
717 return newIdentity;
720 bool crossCompartmentTransplant = (newIdentity != origobj);
721 if (!crossCompartmentTransplant) {
722 // We might still have been transplanted across realms within a single
723 // compartment.
724 if (GetNonCCWObjectRealm(oldWaiver) == GetNonCCWObjectRealm(newIdentity)) {
725 // The old waiver is same-realm with the new object; nothing else to do
726 // here.
727 return newIdentity;
731 if (!FixWaiverAfterTransplant(cx, oldWaiver, newIdentity,
732 crossCompartmentTransplant)) {
733 return nullptr;
735 return newIdentity;
738 JSObject* TransplantObjectRetainingXrayExpandos(JSContext* cx,
739 JS::HandleObject origobj,
740 JS::HandleObject target) {
741 // Save the chain of objects that carry origobj's Xray expando properties
742 // (from all compartments). TransplantObject will blow this away; we'll
743 // restore it manually afterwards.
744 RootedObject expandoChain(
745 cx, GetXrayTraits(origobj)->detachExpandoChain(origobj));
747 RootedObject newIdentity(cx, TransplantObject(cx, origobj, target));
749 // Copy Xray expando properties to the new wrapper.
750 if (!GetXrayTraits(newIdentity)
751 ->cloneExpandoChain(cx, newIdentity, expandoChain)) {
752 // Failure here means some expandos were not copied over. The object graph
753 // and the Xray machinery are left in a consistent state, but mysteriously
754 // losing these expandos is too weird to allow.
755 MOZ_CRASH();
758 return newIdentity;
761 static void NukeXrayWaiver(JSContext* cx, JS::HandleObject obj) {
762 RootedObject waiver(cx, WrapperFactory::GetXrayWaiver(obj));
763 if (!waiver) {
764 return;
767 XPCWrappedNativeScope* scope = ObjectScope(waiver);
768 JSObject* key = Wrapper::wrappedObject(waiver);
769 MOZ_ASSERT(scope->mWaiverWrapperMap->Find(key));
770 scope->mWaiverWrapperMap->Remove(key);
772 js::NukeNonCCWProxy(cx, waiver);
774 // Get rid of any CCWs the waiver may have had.
775 if (!JS_RefreshCrossCompartmentWrappers(cx, waiver)) {
776 MOZ_CRASH();
780 JSObject* TransplantObjectNukingXrayWaiver(JSContext* cx,
781 JS::HandleObject origObj,
782 JS::HandleObject target) {
783 NukeXrayWaiver(cx, origObj);
784 return JS_TransplantObject(cx, origObj, target);
787 nsIGlobalObject* NativeGlobal(JSObject* obj) {
788 obj = JS::GetNonCCWObjectGlobal(obj);
790 // Every global needs to hold a native as its first reserved slot or be a
791 // WebIDL object with an nsISupports DOM object.
792 MOZ_ASSERT(JS::GetClass(obj)->slot0IsISupports() ||
793 dom::UnwrapDOMObjectToISupports(obj));
795 nsISupports* native = dom::UnwrapDOMObjectToISupports(obj);
796 if (!native) {
797 native = JS::GetObjectISupports<nsISupports>(obj);
798 MOZ_ASSERT(native);
800 // In some cases (like for windows) it is a wrapped native,
801 // in other cases (sandboxes, system globals) it's just
802 // a direct pointer to the native. If it's a wrapped native
803 // let's unwrap it first.
804 if (nsCOMPtr<nsIXPConnectWrappedNative> wn = do_QueryInterface(native)) {
805 native = wn->Native();
809 nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(native);
810 MOZ_ASSERT(global,
811 "Native held by global needs to implement nsIGlobalObject!");
813 return global;
816 nsIGlobalObject* CurrentNativeGlobal(JSContext* cx) {
817 return xpc::NativeGlobal(JS::CurrentGlobalOrNull(cx));
820 } // namespace xpc