/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsGlobalWindow.h" #include #include "mozilla/MemoryReporting.h" // Local Includes #include "Navigator.h" #include "nsContentSecurityManager.h" #include "nsScreen.h" #include "nsHistory.h" #include "nsDOMNavigationTiming.h" #include "nsICookieService.h" #include "nsIDOMStorageManager.h" #include "nsIPermission.h" #include "nsIPermissionManager.h" #include "nsISecureBrowserUI.h" #include "nsIWebProgressListener.h" #include "mozilla/AntiTrackingCommon.h" #include "mozilla/dom/ContentFrameMessageManager.h" #include "mozilla/dom/EventTarget.h" #include "mozilla/dom/LocalStorage.h" #include "mozilla/dom/Storage.h" #include "mozilla/dom/IdleRequest.h" #include "mozilla/dom/Performance.h" #include "mozilla/dom/StorageEvent.h" #include "mozilla/dom/StorageEventBinding.h" #include "mozilla/dom/StorageNotifierService.h" #include "mozilla/dom/StorageUtils.h" #include "mozilla/dom/Timeout.h" #include "mozilla/dom/TimeoutHandler.h" #include "mozilla/dom/TimeoutManager.h" #include "mozilla/IntegerPrintfMacros.h" #if defined(MOZ_WIDGET_ANDROID) #include "mozilla/dom/WindowOrientationObserver.h" #endif #include "nsError.h" #include "nsIIdleService.h" #include "nsISizeOfEventTarget.h" #include "nsDOMJSUtils.h" #include "nsArrayUtils.h" #include "nsDOMWindowList.h" #include "mozilla/dom/WakeLock.h" #include "mozilla/dom/power/PowerManagerService.h" #include "nsIDocShellTreeOwner.h" #include "nsIInterfaceRequestorUtils.h" #include "nsIPermissionManager.h" #include "nsIScriptContext.h" #include "nsIScriptTimeoutHandler.h" #include "nsITimeoutHandler.h" #include "nsIController.h" #include "nsISlowScriptDebug.h" #include "nsWindowMemoryReporter.h" #include "nsWindowSizes.h" #include "WindowNamedPropertiesHandler.h" #include "nsFrameSelection.h" #include "nsNetUtil.h" #include "nsVariant.h" #include "nsPrintfCString.h" #include "mozilla/intl/LocaleService.h" #include "WindowDestroyedEvent.h" #include "nsDocShellLoadInfo.h" // Helper Classes #include "nsJSUtils.h" #include "jsapi.h" #include "js/Wrapper.h" #include "nsCharSeparatedTokenizer.h" #include "nsReadableUtils.h" #include "nsJSEnvironment.h" #include "mozilla/dom/ScriptSettings.h" #include "mozilla/Preferences.h" #include "mozilla/Likely.h" #include "mozilla/Sprintf.h" #include "mozilla/Unused.h" // Other Classes #include "mozilla/dom/BarProps.h" #include "nsContentCID.h" #include "nsLayoutStatics.h" #include "nsCCUncollectableMarker.h" #include "mozilla/dom/WorkerCommon.h" #include "mozilla/dom/ToJSValue.h" #include "nsJSPrincipals.h" #include "mozilla/Attributes.h" #include "mozilla/Debug.h" #include "mozilla/EventListenerManager.h" #include "mozilla/EventStates.h" #include "mozilla/MouseEvents.h" #include "mozilla/ProcessHangMonitor.h" #include "mozilla/StaticPrefs.h" #include "mozilla/ThrottledEventQueue.h" #include "AudioChannelService.h" #include "nsAboutProtocolUtils.h" #include "nsCharTraits.h" // NS_IS_HIGH/LOW_SURROGATE #include "PostMessageEvent.h" #include "mozilla/dom/DocGroup.h" #include "mozilla/dom/TabGroup.h" // Interfaces Needed #include "nsIFrame.h" #include "nsCanvasFrame.h" #include "nsIWidget.h" #include "nsIWidgetListener.h" #include "nsIBaseWindow.h" #include "nsIDeviceSensors.h" #include "nsIContent.h" #include "nsIDocShell.h" #include "nsIDocument.h" #include "Crypto.h" #include "nsDOMString.h" #include "nsIEmbeddingSiteWindow.h" #include "nsThreadUtils.h" #include "nsILoadContext.h" #include "nsIPresShell.h" #include "nsIScrollableFrame.h" #include "nsView.h" #include "nsViewManager.h" #include "nsISelectionController.h" #include "nsIPrompt.h" #include "nsIPromptService.h" #include "nsIPromptFactory.h" #include "nsIAddonPolicyService.h" #include "nsIWritablePropertyBag2.h" #include "nsIWebNavigation.h" #include "nsIWebBrowserChrome.h" #include "nsIWebBrowserFind.h" // For window.find() #include "nsIWindowMediator.h" // For window.find() #include "nsComputedDOMStyle.h" #include "nsDOMCID.h" #include "nsDOMWindowUtils.h" #include "nsIWindowWatcher.h" #include "nsPIWindowWatcher.h" #include "nsIContentViewer.h" #include "nsIScriptError.h" #include "nsIControllers.h" #include "nsIControllerContext.h" #include "nsGlobalWindowCommands.h" #include "nsQueryObject.h" #include "nsContentUtils.h" #include "nsCSSProps.h" #include "nsIURIFixup.h" #include "nsIURIMutator.h" #ifndef DEBUG #include "nsIAppStartup.h" #include "nsToolkitCompsCID.h" #endif #include "nsCDefaultURIFixup.h" #include "mozilla/EventDispatcher.h" #include "mozilla/EventStateManager.h" #include "nsIObserverService.h" #include "nsFocusManager.h" #include "nsIXULWindow.h" #include "nsITimedChannel.h" #include "nsServiceManagerUtils.h" #ifdef MOZ_XUL #include "nsIDOMXULControlElement.h" #include "nsMenuPopupFrame.h" #endif #include "mozilla/dom/CustomEvent.h" #include "nsIJARChannel.h" #include "nsIScreenManager.h" #include "nsIEffectiveTLDService.h" #include "xpcprivate.h" #ifdef NS_PRINTING #include "nsIPrintSettings.h" #include "nsIPrintSettingsService.h" #include "nsIWebBrowserPrint.h" #endif #include "nsWindowRoot.h" #include "nsNetCID.h" #include "nsIArray.h" #include "XULDocument.h" #include "nsIDOMXULCommandDispatcher.h" #include "nsBindingManager.h" #include "nsXBLService.h" #include "nsIDragService.h" #include "mozilla/dom/Element.h" #include "mozilla/dom/Selection.h" #include "nsFrameLoader.h" #include "nsISupportsPrimitives.h" #include "nsXPCOMCID.h" #include "mozilla/Logging.h" #include "prenv.h" #include "mozilla/dom/IDBFactory.h" #include "mozilla/dom/MessageChannel.h" #include "mozilla/dom/Promise.h" #include "mozilla/dom/Gamepad.h" #include "mozilla/dom/GamepadManager.h" #include "gfxVR.h" #include "mozilla/dom/VRDisplay.h" #include "mozilla/dom/VRDisplayEvent.h" #include "mozilla/dom/VRDisplayEventBinding.h" #include "mozilla/dom/VREventObserver.h" #include "nsRefreshDriver.h" #include "Layers.h" #include "mozilla/BasePrincipal.h" #include "mozilla/Services.h" #include "mozilla/Telemetry.h" #include "mozilla/dom/Location.h" #include "nsHTMLDocument.h" #include "nsWrapperCacheInlines.h" #include "mozilla/DOMEventTargetHelper.h" #include "prrng.h" #include "nsSandboxFlags.h" #include "nsBaseCommandController.h" #include "nsXULControllers.h" #include "mozilla/dom/AudioContext.h" #include "mozilla/dom/BrowserElementDictionariesBinding.h" #include "mozilla/dom/cache/CacheStorage.h" #include "mozilla/dom/Console.h" #include "mozilla/dom/Fetch.h" #include "mozilla/dom/FunctionBinding.h" #include "mozilla/dom/HashChangeEvent.h" #include "mozilla/dom/IntlUtils.h" #include "mozilla/dom/PopStateEvent.h" #include "mozilla/dom/PopupBlockedEvent.h" #include "mozilla/dom/PrimitiveConversions.h" #include "mozilla/dom/WindowBinding.h" #include "nsITabChild.h" #include "mozilla/dom/MediaQueryList.h" #include "mozilla/dom/ScriptSettings.h" #include "mozilla/dom/NavigatorBinding.h" #include "mozilla/dom/ImageBitmap.h" #include "mozilla/dom/ImageBitmapBinding.h" #include "mozilla/dom/ServiceWorkerRegistration.h" #include "mozilla/dom/U2F.h" #include "mozilla/dom/WebIDLGlobalNameHash.h" #include "mozilla/dom/Worklet.h" #ifdef HAVE_SIDEBAR #include "mozilla/dom/ExternalBinding.h" #endif #ifdef MOZ_WEBSPEECH #include "mozilla/dom/SpeechSynthesis.h" #endif // Apple system headers seem to have a check() macro. #ifdef check class nsIScriptTimeoutHandler; #undef check #endif // check #include "AccessCheck.h" #ifdef ANDROID #include #endif #ifdef XP_WIN #include #define getpid _getpid #else #include // for getpid() #endif using namespace mozilla; using namespace mozilla::dom; using namespace mozilla::dom::ipc; using mozilla::BasePrincipal; using mozilla::OriginAttributes; using mozilla::TimeStamp; #define FORWARD_TO_INNER(method, args, err_rval) \ PR_BEGIN_MACRO \ if (!mInnerWindow) { \ NS_WARNING("No inner window available!"); \ return err_rval; \ } \ return GetCurrentInnerWindowInternal()->method args; \ PR_END_MACRO #define FORWARD_TO_INNER_VOID(method, args) \ PR_BEGIN_MACRO \ if (!mInnerWindow) { \ NS_WARNING("No inner window available!"); \ return; \ } \ GetCurrentInnerWindowInternal()->method args; \ return; \ PR_END_MACRO // Same as FORWARD_TO_INNER, but this will create a fresh inner if an // inner doesn't already exists. #define FORWARD_TO_INNER_CREATE(method, args, err_rval) \ PR_BEGIN_MACRO \ if (!mInnerWindow) { \ if (mIsClosed) { \ return err_rval; \ } \ nsCOMPtr kungFuDeathGrip = GetDoc(); \ ::mozilla::Unused << kungFuDeathGrip; \ if (!mInnerWindow) { \ return err_rval; \ } \ } \ return GetCurrentInnerWindowInternal()->method args; \ PR_END_MACRO static LazyLogModule gDOMLeakPRLogOuter("DOMLeakOuter"); static int32_t gOpenPopupSpamCount = 0; nsGlobalWindowOuter::OuterWindowByIdTable *nsGlobalWindowOuter::sOuterWindowsById = nullptr; /* static */ nsPIDOMWindowOuter* nsPIDOMWindowOuter::GetFromCurrentInner(nsPIDOMWindowInner* aInner) { if (!aInner) { return nullptr; } nsPIDOMWindowOuter* outer = aInner->GetOuterWindow(); if (!outer || outer->GetCurrentInnerWindow() != aInner) { return nullptr; } return outer; } //***************************************************************************** // nsOuterWindowProxy: Outer Window Proxy //***************************************************************************** class nsOuterWindowProxy : public js::Wrapper { public: constexpr nsOuterWindowProxy() : js::Wrapper(0) { } bool finalizeInBackground(const JS::Value& priv) const override { return false; } // Standard internal methods bool getOwnPropertyDescriptor(JSContext* cx, JS::Handle proxy, JS::Handle id, JS::MutableHandle desc) const override; bool defineProperty(JSContext* cx, JS::Handle proxy, JS::Handle id, JS::Handle desc, JS::ObjectOpResult &result) const override; bool ownPropertyKeys(JSContext *cx, JS::Handle proxy, JS::AutoIdVector &props) const override; bool delete_(JSContext *cx, JS::Handle proxy, JS::Handle id, JS::ObjectOpResult &result) const override; bool getPrototypeIfOrdinary(JSContext* cx, JS::Handle proxy, bool* isOrdinary, JS::MutableHandle protop) const override; JSObject* enumerate(JSContext *cx, JS::Handle proxy) const override; bool preventExtensions(JSContext* cx, JS::Handle proxy, JS::ObjectOpResult& result) const override; bool isExtensible(JSContext *cx, JS::Handle proxy, bool *extensible) const override; bool has(JSContext *cx, JS::Handle proxy, JS::Handle id, bool *bp) const override; bool get(JSContext *cx, JS::Handle proxy, JS::Handle receiver, JS::Handle id, JS::MutableHandle vp) const override; bool set(JSContext *cx, JS::Handle proxy, JS::Handle id, JS::Handle v, JS::Handle receiver, JS::ObjectOpResult &result) const override; // SpiderMonkey extensions bool getPropertyDescriptor(JSContext* cx, JS::Handle proxy, JS::Handle id, JS::MutableHandle desc) const override; bool hasOwn(JSContext *cx, JS::Handle proxy, JS::Handle id, bool *bp) const override; bool getOwnEnumerablePropertyKeys(JSContext *cx, JS::Handle proxy, JS::AutoIdVector &props) const override; const char *className(JSContext *cx, JS::Handle wrapper) const override; void finalize(JSFreeOp *fop, JSObject *proxy) const override; size_t objectMoved(JSObject* proxy, JSObject* old) const override; bool isCallable(JSObject *obj) const override { return false; } bool isConstructor(JSObject *obj) const override { return false; } static const nsOuterWindowProxy singleton; protected: static nsGlobalWindowOuter* GetOuterWindow(JSObject *proxy) { nsGlobalWindowOuter* outerWindow = nsGlobalWindowOuter::FromSupports( static_cast(js::GetProxyReservedSlot(proxy, 0).toPrivate())); return outerWindow; } // False return value means we threw an exception. True return value // but false "found" means we didn't have a subframe at that index. bool GetSubframeWindow(JSContext *cx, JS::Handle proxy, JS::Handle id, JS::MutableHandle vp, bool &found) const; // Returns a non-null window only if id is an index and we have a // window at that index. already_AddRefed GetSubframeWindow(JSContext *cx, JS::Handle proxy, JS::Handle id) const; bool AppendIndexedPropertyNames(JSContext *cx, JSObject *proxy, JS::AutoIdVector &props) const; }; // Give OuterWindowProxyClass 2 reserved slots, like the other wrappers, so // JSObject::swap can swap it with CrossCompartmentWrappers without requiring // malloc. const js::Class OuterWindowProxyClass = PROXY_CLASS_DEF( "Proxy", JSCLASS_HAS_RESERVED_SLOTS(2)); /* additional class flags */ const char * nsOuterWindowProxy::className(JSContext *cx, JS::Handle proxy) const { MOZ_ASSERT(js::IsProxy(proxy)); return "Window"; } void nsOuterWindowProxy::finalize(JSFreeOp *fop, JSObject *proxy) const { nsGlobalWindowOuter* outerWindow = GetOuterWindow(proxy); if (outerWindow) { outerWindow->ClearWrapper(proxy); // Ideally we would use OnFinalize here, but it's possible that // EnsureScriptEnvironment will later be called on the window, and we don't // want to create a new script object in that case. Therefore, we need to // write a non-null value that will reliably crash when dereferenced. outerWindow->PoisonOuterWindowProxy(proxy); } } bool nsOuterWindowProxy::getPropertyDescriptor(JSContext* cx, JS::Handle proxy, JS::Handle id, JS::MutableHandle desc) const { // The only thing we can do differently from js::Wrapper is shadow stuff with // our indexed properties, so we can just try getOwnPropertyDescriptor and if // that gives us nothing call on through to js::Wrapper. desc.object().set(nullptr); if (!getOwnPropertyDescriptor(cx, proxy, id, desc)) { return false; } if (desc.object()) { return true; } return js::Wrapper::getPropertyDescriptor(cx, proxy, id, desc); } bool nsOuterWindowProxy::getOwnPropertyDescriptor(JSContext* cx, JS::Handle proxy, JS::Handle id, JS::MutableHandle desc) const { bool found; if (!GetSubframeWindow(cx, proxy, id, desc.value(), found)) { return false; } if (found) { FillPropertyDescriptor(desc, proxy, true); return true; } // else fall through to js::Wrapper return js::Wrapper::getOwnPropertyDescriptor(cx, proxy, id, desc); } bool nsOuterWindowProxy::defineProperty(JSContext* cx, JS::Handle proxy, JS::Handle id, JS::Handle desc, JS::ObjectOpResult &result) const { if (IsArrayIndex(GetArrayIndexFromId(cx, id))) { // Spec says to Reject whether this is a supported index or not, // since we have no indexed setter or indexed creator. It is up // to the caller to decide whether to throw a TypeError. return result.failCantDefineWindowElement(); } return js::Wrapper::defineProperty(cx, proxy, id, desc, result); } bool nsOuterWindowProxy::ownPropertyKeys(JSContext *cx, JS::Handle proxy, JS::AutoIdVector &props) const { // Just our indexed stuff followed by our "normal" own property names. if (!AppendIndexedPropertyNames(cx, proxy, props)) { return false; } JS::AutoIdVector innerProps(cx); if (!js::Wrapper::ownPropertyKeys(cx, proxy, innerProps)) { return false; } return js::AppendUnique(cx, props, innerProps); } bool nsOuterWindowProxy::delete_(JSContext *cx, JS::Handle proxy, JS::Handle id, JS::ObjectOpResult &result) const { if (nsCOMPtr frame = GetSubframeWindow(cx, proxy, id)) { // Fail (which means throw if strict, else return false). return result.failCantDeleteWindowElement(); } if (IsArrayIndex(GetArrayIndexFromId(cx, id))) { // Indexed, but not supported. Spec says return true. return result.succeed(); } return js::Wrapper::delete_(cx, proxy, id, result); } bool nsOuterWindowProxy::getPrototypeIfOrdinary(JSContext* cx, JS::Handle proxy, bool* isOrdinary, JS::MutableHandle protop) const { // Window's [[GetPrototypeOf]] trap isn't the ordinary definition: // // https://html.spec.whatwg.org/multipage/browsers.html#windowproxy-getprototypeof // // We nonetheless can implement it with a static [[Prototype]], because // wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply // all non-ordinary behavior. // // But from a spec point of view, it's the exact same object in both cases -- // only the observer's changed. So this getPrototypeIfOrdinary trap on the // non-wrapper object *must* report non-ordinary, even if static [[Prototype]] // usually means ordinary. *isOrdinary = false; return true; } bool nsOuterWindowProxy::preventExtensions(JSContext* cx, JS::Handle proxy, JS::ObjectOpResult& result) const { // If [[Extensible]] could be false, then navigating a window could navigate // to a window that's [[Extensible]] after being at one that wasn't: an // invariant violation. So never change a window's extensibility. return result.failCantPreventExtensions(); } bool nsOuterWindowProxy::isExtensible(JSContext *cx, JS::Handle proxy, bool *extensible) const { // See above. *extensible = true; return true; } bool nsOuterWindowProxy::has(JSContext *cx, JS::Handle proxy, JS::Handle id, bool *bp) const { if (nsCOMPtr frame = GetSubframeWindow(cx, proxy, id)) { *bp = true; return true; } return js::Wrapper::has(cx, proxy, id, bp); } bool nsOuterWindowProxy::hasOwn(JSContext *cx, JS::Handle proxy, JS::Handle id, bool *bp) const { if (nsCOMPtr frame = GetSubframeWindow(cx, proxy, id)) { *bp = true; return true; } return js::Wrapper::hasOwn(cx, proxy, id, bp); } bool nsOuterWindowProxy::get(JSContext *cx, JS::Handle proxy, JS::Handle receiver, JS::Handle id, JS::MutableHandle vp) const { if (id == GetJSIDByIndex(cx, XPCJSContext::IDX_WRAPPED_JSOBJECT) && xpc::AccessCheck::isChrome(js::GetContextCompartment(cx))) { vp.set(JS::ObjectValue(*proxy)); return true; } bool found; if (!GetSubframeWindow(cx, proxy, id, vp, found)) { return false; } if (found) { return true; } // Else fall through to js::Wrapper return js::Wrapper::get(cx, proxy, receiver, id, vp); } bool nsOuterWindowProxy::set(JSContext *cx, JS::Handle proxy, JS::Handle id, JS::Handle v, JS::Handle receiver, JS::ObjectOpResult &result) const { if (IsArrayIndex(GetArrayIndexFromId(cx, id))) { // Reject the set. It's up to the caller to decide whether to throw a // TypeError. If the caller is strict mode JS code, it'll throw. return result.failReadOnly(); } return js::Wrapper::set(cx, proxy, id, v, receiver, result); } bool nsOuterWindowProxy::getOwnEnumerablePropertyKeys(JSContext *cx, JS::Handle proxy, JS::AutoIdVector &props) const { // Like ownPropertyKeys, our indexed stuff followed by our "normal" enumerable // own property names. // // Note that this does not match current spec per // https://github.com/whatwg/html/issues/2753 but as that issue says I believe // the spec is wrong. if (!AppendIndexedPropertyNames(cx, proxy, props)) { return false; } JS::AutoIdVector innerProps(cx); if (!js::Wrapper::getOwnEnumerablePropertyKeys(cx, proxy, innerProps)) { return false; } return js::AppendUnique(cx, props, innerProps); } JSObject* nsOuterWindowProxy::enumerate(JSContext *cx, JS::Handle proxy) const { // BaseProxyHandler::enumerate seems to do what we want here: fall // back on the property names returned from js::GetPropertyKeys() return js::BaseProxyHandler::enumerate(cx, proxy); } bool nsOuterWindowProxy::GetSubframeWindow(JSContext *cx, JS::Handle proxy, JS::Handle id, JS::MutableHandle vp, bool& found) const { nsCOMPtr frame = GetSubframeWindow(cx, proxy, id); if (!frame) { found = false; return true; } found = true; // Just return the window's global nsGlobalWindowOuter* global = nsGlobalWindowOuter::Cast(frame); frame->EnsureInnerWindow(); JSObject* obj = global->FastGetGlobalJSObject(); // This null check fixes a hard-to-reproduce crash that occurs when we // get here when we're mid-call to nsDocShell::Destroy. See bug 640904 // comment 105. if (MOZ_UNLIKELY(!obj)) { return xpc::Throw(cx, NS_ERROR_FAILURE); } JS::ExposeObjectToActiveJS(obj); vp.setObject(*obj); return JS_WrapValue(cx, vp); } already_AddRefed nsOuterWindowProxy::GetSubframeWindow(JSContext *cx, JS::Handle proxy, JS::Handle id) const { uint32_t index = GetArrayIndexFromId(cx, id); if (!IsArrayIndex(index)) { return nullptr; } nsGlobalWindowOuter* win = GetOuterWindow(proxy); return win->IndexedGetterOuter(index); } bool nsOuterWindowProxy::AppendIndexedPropertyNames(JSContext *cx, JSObject *proxy, JS::AutoIdVector &props) const { uint32_t length = GetOuterWindow(proxy)->Length(); MOZ_ASSERT(int32_t(length) >= 0); if (!props.reserve(props.length() + length)) { return false; } for (int32_t i = 0; i < int32_t(length); ++i) { if (!props.append(INT_TO_JSID(i))) { return false; } } return true; } size_t nsOuterWindowProxy::objectMoved(JSObject *obj, JSObject *old) const { nsGlobalWindowOuter* outerWindow = GetOuterWindow(obj); if (outerWindow) { outerWindow->UpdateWrapper(obj, old); } return 0; } const nsOuterWindowProxy nsOuterWindowProxy::singleton; class nsChromeOuterWindowProxy : public nsOuterWindowProxy { public: constexpr nsChromeOuterWindowProxy() : nsOuterWindowProxy() { } const char *className(JSContext *cx, JS::Handle wrapper) const override; static const nsChromeOuterWindowProxy singleton; }; const char * nsChromeOuterWindowProxy::className(JSContext *cx, JS::Handle proxy) const { MOZ_ASSERT(js::IsProxy(proxy)); return "ChromeWindow"; } const nsChromeOuterWindowProxy nsChromeOuterWindowProxy::singleton; static JSObject* NewOuterWindowProxy(JSContext *cx, JS::Handle global, bool isChrome) { MOZ_ASSERT(JS_IsGlobalObject(global)); JSAutoRealm ar(cx, global); js::WrapperOptions options; options.setClass(&OuterWindowProxyClass); options.setSingleton(true); JSObject *obj = js::Wrapper::New(cx, global, isChrome ? &nsChromeOuterWindowProxy::singleton : &nsOuterWindowProxy::singleton, options); MOZ_ASSERT_IF(obj, js::IsWindowProxy(obj)); return obj; } //***************************************************************************** //*** nsGlobalWindowOuter: Object Management //***************************************************************************** nsGlobalWindowOuter::nsGlobalWindowOuter(uint64_t aWindowID) : nsPIDOMWindowOuter(aWindowID), mIdleFuzzFactor(0), mIdleCallbackIndex(-1), mCurrentlyIdle(false), mAddActiveEventFuzzTime(true), mFullscreen(false), mFullscreenMode(false), mIsClosed(false), mInClose(false), mHavePendingClose(false), mHadOriginalOpener(false), mIsPopupSpam(false), mBlockScriptedClosingFlag(false), mWasOffline(false), mCreatingInnerWindow(false), mIsChrome(false), mAllowScriptsToClose(false), mTopLevelOuterContentWindow(false), mHasStorageAccess(false), mSerial(0), #ifdef DEBUG mSetOpenerWindowCalled(false), #endif mCleanedUp(false), #ifdef DEBUG mIsValidatingTabGroup(false), #endif mCanSkipCCGeneration(0), mAutoActivateVRDisplayID(0) { AssertIsOnMainThread(); nsLayoutStatics::AddRef(); // Initialize the PRCList (this). PR_INIT_CLIST(this); // |this| is an outer window. Outer windows start out frozen and // remain frozen until they get an inner window. MOZ_ASSERT(IsFrozen()); // We could have failed the first time through trying // to create the entropy collector, so we should // try to get one until we succeed. mSerial = nsContentUtils::InnerOrOuterWindowCreated(); #ifdef DEBUG if (!PR_GetEnv("MOZ_QUIET")) { printf_stderr("++DOMWINDOW == %d (%p) [pid = %d] [serial = %d] [outer = %p]\n", nsContentUtils::GetCurrentInnerOrOuterWindowCount(), static_cast(ToCanonicalSupports(this)), getpid(), mSerial, nullptr); } #endif MOZ_LOG(gDOMLeakPRLogOuter, LogLevel::Debug, ("DOMWINDOW %p created outer=nullptr", this)); // Add ourselves to the outer windows list. MOZ_ASSERT(sOuterWindowsById, "Outer Windows hash table must be created!"); // |this| is an outer window, add to the outer windows list. MOZ_ASSERT(!sOuterWindowsById->Get(mWindowID), "This window shouldn't be in the hash table yet!"); // We seem to see crashes in release builds because of null |sOuterWindowsById|. if (sOuterWindowsById) { sOuterWindowsById->Put(mWindowID, this); } } #ifdef DEBUG /* static */ void nsGlobalWindowOuter::AssertIsOnMainThread() { MOZ_ASSERT(NS_IsMainThread()); } #endif // DEBUG /* static */ void nsGlobalWindowOuter::Init() { AssertIsOnMainThread(); NS_ASSERTION(gDOMLeakPRLogOuter, "gDOMLeakPRLogOuter should have been initialized!"); sOuterWindowsById = new OuterWindowByIdTable(); } nsGlobalWindowOuter::~nsGlobalWindowOuter() { AssertIsOnMainThread(); if (sOuterWindowsById) { MOZ_ASSERT(sOuterWindowsById->Get(mWindowID), "This window should be in the hash table"); sOuterWindowsById->Remove(mWindowID); } nsContentUtils::InnerOrOuterWindowDestroyed(); #ifdef DEBUG if (!PR_GetEnv("MOZ_QUIET")) { nsAutoCString url; if (mLastOpenedURI) { url = mLastOpenedURI->GetSpecOrDefault(); // Data URLs can be very long, so truncate to avoid flooding the log. const uint32_t maxURLLength = 1000; if (url.Length() > maxURLLength) { url.Truncate(maxURLLength); } } printf_stderr("--DOMWINDOW == %d (%p) [pid = %d] [serial = %d] [outer = %p] [url = %s]\n", nsContentUtils::GetCurrentInnerOrOuterWindowCount(), static_cast(ToCanonicalSupports(this)), getpid(), mSerial, nullptr, url.get()); } #endif MOZ_LOG(gDOMLeakPRLogOuter, LogLevel::Debug, ("DOMWINDOW %p destroyed", this)); JSObject *proxy = GetWrapperMaybeDead(); if (proxy) { js::SetProxyReservedSlot(proxy, 0, js::PrivateValue(nullptr)); } // An outer window is destroyed with inner windows still possibly // alive, iterate through the inner windows and null out their // back pointer to this outer, and pull them out of the list of // inner windows. // // Our linked list of inner windows both contains (an nsGlobalWindowOuter), // and our inner windows (nsGlobalWindowInners). This means that we need to // use PRCList*. We can then compare that PRCList* to `this` to see if its an // inner or outer window. PRCList* w; while ((w = PR_LIST_HEAD(this)) != this) { PR_REMOVE_AND_INIT_LINK(w); } DropOuterWindowDocs(); if (mTabGroup) { mTabGroup->Leave(this); } // Outer windows are always supposed to call CleanUp before letting themselves // be destroyed. MOZ_ASSERT(mCleanedUp); nsCOMPtr ac = do_GetService(NS_DEVICE_SENSORS_CONTRACTID); if (ac) ac->RemoveWindowAsListener(this); nsCOMPtr obs = mozilla::services::GetObserverService(); if (obs) { obs->RemoveObserver(this, PERM_CHANGE_NOTIFICATION); } nsLayoutStatics::Release(); } // static void nsGlobalWindowOuter::ShutDown() { AssertIsOnMainThread(); delete sOuterWindowsById; sOuterWindowsById = nullptr; } void nsGlobalWindowOuter::MaybeForgiveSpamCount() { if (IsPopupSpamWindow()) { SetIsPopupSpamWindow(false); } } void nsGlobalWindowOuter::SetIsPopupSpamWindow(bool aIsPopupSpam) { mIsPopupSpam = aIsPopupSpam; if (aIsPopupSpam) { ++gOpenPopupSpamCount; } else { --gOpenPopupSpamCount; NS_ASSERTION(gOpenPopupSpamCount >= 0, "Unbalanced decrement of gOpenPopupSpamCount"); } } void nsGlobalWindowOuter::DropOuterWindowDocs() { MOZ_ASSERT_IF(mDoc, !mDoc->EventHandlingSuppressed()); mDoc = nullptr; mSuspendedDoc = nullptr; } void nsGlobalWindowOuter::CleanUp() { // Guarantee idempotence. if (mCleanedUp) return; mCleanedUp = true; StartDying(); mFrames = nullptr; mWindowUtils = nullptr; ClearControllers(); mOpener = nullptr; // Forces Release if (mContext) { mContext = nullptr; // Forces Release } mChromeEventHandler = nullptr; // Forces Release mParentTarget = nullptr; mMessageManager = nullptr; mArguments = nullptr; if (mIdleTimer) { mIdleTimer->Cancel(); mIdleTimer = nullptr; } } void nsGlobalWindowOuter::ClearControllers() { if (mControllers) { uint32_t count; mControllers->GetControllerCount(&count); while (count--) { nsCOMPtr controller; mControllers->GetControllerAt(count, getter_AddRefs(controller)); nsCOMPtr context = do_QueryInterface(controller); if (context) context->SetCommandContext(nullptr); } mControllers = nullptr; } } //***************************************************************************** // nsGlobalWindowOuter::nsISupports //***************************************************************************** // QueryInterface implementation for nsGlobalWindowOuter NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsGlobalWindowOuter) NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, EventTarget) NS_INTERFACE_MAP_ENTRY(nsIDOMWindow) NS_INTERFACE_MAP_ENTRY(nsIGlobalObject) NS_INTERFACE_MAP_ENTRY(nsIScriptGlobalObject) NS_INTERFACE_MAP_ENTRY(nsIScriptObjectPrincipal) NS_INTERFACE_MAP_ENTRY(mozilla::dom::EventTarget) NS_INTERFACE_MAP_ENTRY(nsPIDOMWindowOuter) NS_INTERFACE_MAP_ENTRY(mozIDOMWindowProxy) NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIDOMChromeWindow, IsChromeWindow()) NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor) NS_INTERFACE_MAP_ENTRY(nsIObserver) NS_INTERFACE_MAP_END NS_IMPL_CYCLE_COLLECTING_ADDREF(nsGlobalWindowOuter) NS_IMPL_CYCLE_COLLECTING_RELEASE(nsGlobalWindowOuter) NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(nsGlobalWindowOuter) if (tmp->IsBlackForCC(false)) { if (nsCCUncollectableMarker::InGeneration(tmp->mCanSkipCCGeneration)) { return true; } tmp->mCanSkipCCGeneration = nsCCUncollectableMarker::sGeneration; if (EventListenerManager* elm = tmp->GetExistingListenerManager()) { elm->MarkForCC(); } return true; } NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(nsGlobalWindowOuter) return tmp->IsBlackForCC(true); NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(nsGlobalWindowOuter) return tmp->IsBlackForCC(false); NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END NS_IMPL_CYCLE_COLLECTION_CLASS(nsGlobalWindowOuter) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsGlobalWindowOuter) if (MOZ_UNLIKELY(cb.WantDebugInfo())) { char name[512]; nsAutoCString uri; if (tmp->mDoc && tmp->mDoc->GetDocumentURI()) { uri = tmp->mDoc->GetDocumentURI()->GetSpecOrDefault(); } SprintfLiteral(name, "nsGlobalWindowOuter # %" PRIu64 " outer %s", tmp->mWindowID, uri.get()); cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name); } else { NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsGlobalWindowOuter, tmp->mRefCnt.get()) } NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContext) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mControllers) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mArguments) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLocalStorage) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSuspendedDoc) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocumentPrincipal) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDoc) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIdleService) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIdleObservers) // Traverse stuff from nsPIDOMWindow NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChromeEventHandler) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mParentTarget) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMessageManager) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFrameElement) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOpenerForInitialContentBrowser) NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDocShell) tmp->TraverseHostObjectURIs(cb); NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChromeFields.mBrowserDOMWindow) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGlobalWindowOuter) NS_IMPL_CYCLE_COLLECTION_UNLINK(mContext) NS_IMPL_CYCLE_COLLECTION_UNLINK(mControllers) NS_IMPL_CYCLE_COLLECTION_UNLINK(mArguments) NS_IMPL_CYCLE_COLLECTION_UNLINK(mLocalStorage) NS_IMPL_CYCLE_COLLECTION_UNLINK(mSuspendedDoc) NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocumentPrincipal) NS_IMPL_CYCLE_COLLECTION_UNLINK(mDoc) NS_IMPL_CYCLE_COLLECTION_UNLINK(mIdleService) NS_IMPL_CYCLE_COLLECTION_UNLINK(mIdleObservers) // Unlink stuff from nsPIDOMWindow NS_IMPL_CYCLE_COLLECTION_UNLINK(mChromeEventHandler) NS_IMPL_CYCLE_COLLECTION_UNLINK(mParentTarget) NS_IMPL_CYCLE_COLLECTION_UNLINK(mMessageManager) NS_IMPL_CYCLE_COLLECTION_UNLINK(mFrameElement) NS_IMPL_CYCLE_COLLECTION_UNLINK(mOpenerForInitialContentBrowser) NS_IMPL_CYCLE_COLLECTION_UNLINK(mDocShell) tmp->UnlinkHostObjectURIs(); if (tmp->IsChromeWindow()) { NS_IMPL_CYCLE_COLLECTION_UNLINK(mChromeFields.mBrowserDOMWindow) } NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsGlobalWindowOuter) NS_IMPL_CYCLE_COLLECTION_TRACE_PRESERVED_WRAPPER NS_IMPL_CYCLE_COLLECTION_TRACE_END bool nsGlobalWindowOuter::IsBlackForCC(bool aTracingNeeded) { if (!nsCCUncollectableMarker::sGeneration) { return false; } return (nsCCUncollectableMarker::InGeneration(GetMarkedCCGeneration()) || HasKnownLiveWrapper()) && (!aTracingNeeded || HasNothingToTrace(ToSupports(this))); } //***************************************************************************** // nsGlobalWindowOuter::nsIScriptGlobalObject //***************************************************************************** nsresult nsGlobalWindowOuter::EnsureScriptEnvironment() { if (GetWrapperPreserveColor()) { return NS_OK; } NS_ASSERTION(!GetCurrentInnerWindowInternal(), "No cached wrapper, but we have an inner window?"); // If this window is a [i]frame, don't bother GC'ing when the frame's context // is destroyed since a GC will happen when the frameset or host document is // destroyed anyway. nsCOMPtr context = new nsJSContext(!IsFrame(), this); NS_ASSERTION(!mContext, "Will overwrite mContext!"); // should probably assert the context is clean??? context->WillInitializeContext(); nsresult rv = context->InitContext(); NS_ENSURE_SUCCESS(rv, rv); mContext = context; return NS_OK; } nsIScriptContext * nsGlobalWindowOuter::GetScriptContext() { return mContext; } JSObject * nsGlobalWindowOuter::GetGlobalJSObject() { return FastGetGlobalJSObject(); } bool nsGlobalWindowOuter::WouldReuseInnerWindow(nsIDocument* aNewDocument) { // We reuse the inner window when: // a. We are currently at our original document. // b. At least one of the following conditions are true: // -- The new document is the same as the old document. This means that we're // getting called from document.open(). // -- The new document has the same origin as what we have loaded right now. if (!mDoc || !aNewDocument) { return false; } if (!mDoc->IsInitialDocument()) { return false; } #ifdef DEBUG { nsCOMPtr uri; NS_GetURIWithoutRef(mDoc->GetDocumentURI(), getter_AddRefs(uri)); NS_ASSERTION(NS_IsAboutBlank(uri), "How'd this happen?"); } #endif // Great, we're the original document, check for one of the other // conditions. if (mDoc == aNewDocument) { return true; } bool equal; if (NS_SUCCEEDED(mDoc->NodePrincipal()->Equals(aNewDocument->NodePrincipal(), &equal)) && equal) { // The origin is the same. return true; } return false; } void nsGlobalWindowOuter::SetInitialPrincipalToSubject() { // First, grab the subject principal. nsCOMPtr newWindowPrincipal = nsContentUtils::SubjectPrincipalOrSystemIfNativeCaller(); // We should never create windows with an expanded principal. // If we have a system principal, make sure we're not using it for a content // docshell. // NOTE: Please keep this logic in sync with nsWebShellWindow::Initialize(). if (nsContentUtils::IsExpandedPrincipal(newWindowPrincipal) || (nsContentUtils::IsSystemPrincipal(newWindowPrincipal) && GetDocShell()->ItemType() != nsIDocShellTreeItem::typeChrome)) { newWindowPrincipal = nullptr; } // If there's an existing document, bail if it either: if (mDoc) { // (a) is not an initial about:blank document, or if (!mDoc->IsInitialDocument()) return; // (b) already has the correct principal. if (mDoc->NodePrincipal() == newWindowPrincipal) return; #ifdef DEBUG // If we have a document loaded at this point, it had better be about:blank. // Otherwise, something is really weird. An about:blank page has a // NullPrincipal. bool isNullPrincipal; MOZ_ASSERT(NS_SUCCEEDED(mDoc->NodePrincipal()->GetIsNullPrincipal(&isNullPrincipal)) && isNullPrincipal); #endif } GetDocShell()->CreateAboutBlankContentViewer(newWindowPrincipal); if (mDoc) { mDoc->SetIsInitialDocument(true); } nsCOMPtr shell = GetDocShell()->GetPresShell(); if (shell && !shell->DidInitialize()) { // Ensure that if someone plays with this document they will get // layout happening. shell->Initialize(); } } PopupControlState nsGlobalWindowOuter::PushPopupControlState(PopupControlState aState, bool aForce) const { return nsContentUtils::PushPopupControlState(aState, aForce); } void nsGlobalWindowOuter::PopPopupControlState(PopupControlState aState) const { nsContentUtils::PopPopupControlState(aState); } PopupControlState nsGlobalWindowOuter::GetPopupControlState() const { return nsContentUtils::GetPopupControlState(); } #define WINDOWSTATEHOLDER_IID \ {0x0b917c3e, 0xbd50, 0x4683, {0xaf, 0xc9, 0xc7, 0x81, 0x07, 0xae, 0x33, 0x26}} class WindowStateHolder final : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(WINDOWSTATEHOLDER_IID) NS_DECL_ISUPPORTS explicit WindowStateHolder(nsGlobalWindowInner *aWindow); nsGlobalWindowInner* GetInnerWindow() { return mInnerWindow; } void DidRestoreWindow() { mInnerWindow = nullptr; mInnerWindowReflector = nullptr; } protected: ~WindowStateHolder(); nsGlobalWindowInner *mInnerWindow; // We hold onto this to make sure the inner window doesn't go away. The outer // window ends up recalculating it anyway. JS::PersistentRooted mInnerWindowReflector; }; NS_DEFINE_STATIC_IID_ACCESSOR(WindowStateHolder, WINDOWSTATEHOLDER_IID) WindowStateHolder::WindowStateHolder(nsGlobalWindowInner* aWindow) : mInnerWindow(aWindow), mInnerWindowReflector(RootingCx(), aWindow->GetWrapper()) { MOZ_ASSERT(aWindow, "null window"); aWindow->Suspend(); // When a global goes into the bfcache, we disable script. xpc::Scriptability::Get(mInnerWindowReflector).SetDocShellAllowsScript(false); } WindowStateHolder::~WindowStateHolder() { if (mInnerWindow) { // This window was left in the bfcache and is now going away. We need to // free it up. // Note that FreeInnerObjects may already have been called on the // inner window if its outer has already had SetDocShell(null) // called. mInnerWindow->FreeInnerObjects(); } } NS_IMPL_ISUPPORTS(WindowStateHolder, WindowStateHolder) bool nsGlobalWindowOuter::ComputeIsSecureContext(nsIDocument* aDocument, SecureContextFlags aFlags) { nsCOMPtr principal = aDocument->NodePrincipal(); if (nsContentUtils::IsSystemPrincipal(principal)) { return true; } // Implement https://w3c.github.io/webappsec-secure-contexts/#settings-object // With some modifications to allow for aFlags. bool hadNonSecureContextCreator = false; nsPIDOMWindowOuter* parentOuterWin = GetScriptableParent(); MOZ_ASSERT(parentOuterWin, "How can we get here? No docShell somehow?"); if (nsGlobalWindowOuter::Cast(parentOuterWin) != this) { // There may be a small chance that parentOuterWin has navigated in // the time that it took us to start loading this sub-document. If that // were the case then parentOuterWin->GetCurrentInnerWindow() wouldn't // return the window for the document that is embedding us. For this // reason we only use the GetScriptableParent call above to check that we // have a same-type parent, but actually get the inner window via the // document that we know is embedding us. nsIDocument* creatorDoc = aDocument->GetParentDocument(); if (!creatorDoc) { return false; // we must be tearing down } nsGlobalWindowInner* parentWin = nsGlobalWindowInner::Cast(creatorDoc->GetInnerWindow()); if (!parentWin) { return false; // we must be tearing down } MOZ_ASSERT(parentWin == nsGlobalWindowInner::Cast(parentOuterWin->GetCurrentInnerWindow()), "Creator window mismatch while setting Secure Context state"); hadNonSecureContextCreator = !parentWin->IsSecureContext(); } if (hadNonSecureContextCreator) { return false; } if (nsContentUtils::HttpsStateIsModern(aDocument)) { return true; } if (principal->GetIsNullPrincipal()) { nsCOMPtr uri = aDocument->GetOriginalURI(); // IsOriginPotentiallyTrustworthy doesn't care about origin attributes so // it doesn't actually matter what we use here, but reusing the document // principal's attributes is convenient. const OriginAttributes& attrs = principal->OriginAttributesRef(); // CreateCodebasePrincipal correctly gets a useful principal for blob: and // other URI_INHERITS_SECURITY_CONTEXT URIs. principal = BasePrincipal::CreateCodebasePrincipal(uri, attrs); if (NS_WARN_IF(!principal)) { return false; } } nsCOMPtr csm = do_GetService(NS_CONTENTSECURITYMANAGER_CONTRACTID); NS_WARNING_ASSERTION(csm, "csm is null"); if (csm) { bool isTrustworthyOrigin = false; csm->IsOriginPotentiallyTrustworthy(principal, &isTrustworthyOrigin); if (isTrustworthyOrigin) { return true; } } return false; } // We need certain special behavior for remote XUL whitelisted domains, but we // don't want that behavior to take effect in automation, because we whitelist // all the mochitest domains. So we need to check a pref here. static bool TreatAsRemoteXUL(nsIPrincipal* aPrincipal) { MOZ_ASSERT(!nsContentUtils::IsSystemPrincipal(aPrincipal)); return nsContentUtils::AllowXULXBLForPrincipal(aPrincipal) && !Preferences::GetBool("dom.use_xbl_scopes_for_remote_xul", false); } static bool EnablePrivilege(JSContext* cx, unsigned argc, JS::Value* vp) { Telemetry::Accumulate(Telemetry::ENABLE_PRIVILEGE_EVER_CALLED, true); return xpc::EnableUniversalXPConnect(cx); } static const JSFunctionSpec EnablePrivilegeSpec[] = { JS_FN("enablePrivilege", EnablePrivilege, 1, 0), JS_FS_END }; static bool InitializeLegacyNetscapeObject(JSContext* aCx, JS::Handle aGlobal) { JSAutoRealm ar(aCx, aGlobal); // Note: MathJax depends on window.netscape being exposed. See bug 791526. JS::Rooted obj(aCx); obj = JS_DefineObject(aCx, aGlobal, "netscape", nullptr); NS_ENSURE_TRUE(obj, false); obj = JS_DefineObject(aCx, obj, "security", nullptr); NS_ENSURE_TRUE(obj, false); // We hide enablePrivilege behind a pref because it has been altered in a // way that makes it fundamentally insecure to use in production. Mozilla // uses this pref during automated testing to support legacy test code that // uses enablePrivilege. If you're not doing test automation, you _must_ not // flip this pref, or you will be exposing all your users to security // vulnerabilities. if (!xpc::IsInAutomation()) { return true; } /* Define PrivilegeManager object with the necessary "static" methods. */ obj = JS_DefineObject(aCx, obj, "PrivilegeManager", nullptr); NS_ENSURE_TRUE(obj, false); return JS_DefineFunctions(aCx, obj, EnablePrivilegeSpec); } static JS::RealmCreationOptions& SelectZone(nsGlobalWindowInner* aNewInner, JS::RealmCreationOptions& aOptions) { if (aNewInner->GetOuterWindow()) { nsGlobalWindowOuter *top = aNewInner->GetTopInternal(); // If we have a top-level window, use its zone. if (top && top->GetGlobalJSObject()) { return aOptions.setNewCompartmentInExistingZone(top->GetGlobalJSObject()); } } return aOptions.setNewCompartmentAndZone(); } /** * Create a new global object that will be used for an inner window. * Return the native global and an nsISupports 'holder' that can be used * to manage the lifetime of it. */ static nsresult CreateNativeGlobalForInner(JSContext* aCx, nsGlobalWindowInner* aNewInner, nsIURI* aURI, nsIPrincipal* aPrincipal, JS::MutableHandle aGlobal, bool aIsSecureContext) { MOZ_ASSERT(aCx); MOZ_ASSERT(aNewInner); MOZ_ASSERT(aPrincipal); // DOMWindow with nsEP is not supported, we have to make sure // no one creates one accidentally. nsCOMPtr nsEP = do_QueryInterface(aPrincipal); MOZ_RELEASE_ASSERT(!nsEP, "DOMWindow with nsEP is not supported"); JS::RealmOptions options; SelectZone(aNewInner, options.creationOptions()); options.creationOptions().setSecureContext(aIsSecureContext); xpc::InitGlobalObjectOptions(options, aPrincipal); // Determine if we need the Components object. bool needComponents = nsContentUtils::IsSystemPrincipal(aPrincipal) || TreatAsRemoteXUL(aPrincipal); uint32_t flags = needComponents ? 0 : xpc::OMIT_COMPONENTS_OBJECT; flags |= xpc::DONT_FIRE_ONNEWGLOBALHOOK; if (!Window_Binding::Wrap(aCx, aNewInner, aNewInner, options, nsJSPrincipals::get(aPrincipal), false, aGlobal) || !xpc::InitGlobalObject(aCx, aGlobal, flags)) { return NS_ERROR_FAILURE; } MOZ_ASSERT(aNewInner->GetWrapperPreserveColor() == aGlobal); // Set the location information for the new global, so that tools like // about:memory may use that information xpc::SetLocationForGlobal(aGlobal, aURI); if (!InitializeLegacyNetscapeObject(aCx, aGlobal)) { return NS_ERROR_FAILURE; } return NS_OK; } nsresult nsGlobalWindowOuter::SetNewDocument(nsIDocument* aDocument, nsISupports* aState, bool aForceReuseInnerWindow) { MOZ_ASSERT(mDocumentPrincipal == nullptr, "mDocumentPrincipal prematurely set!"); MOZ_ASSERT(aDocument); // Bail out early if we're in process of closing down the window. NS_ENSURE_STATE(!mCleanedUp); NS_ASSERTION(!GetCurrentInnerWindow() || GetCurrentInnerWindow()->GetExtantDoc() == mDoc, "Uh, mDoc doesn't match the current inner window " "document!"); bool wouldReuseInnerWindow = WouldReuseInnerWindow(aDocument); if (aForceReuseInnerWindow && !wouldReuseInnerWindow && mDoc && mDoc->NodePrincipal() != aDocument->NodePrincipal()) { NS_ERROR("Attempted forced inner window reuse while changing principal"); return NS_ERROR_UNEXPECTED; } nsCOMPtr oldDoc = mDoc; AutoJSAPI jsapi; jsapi.Init(); JSContext *cx = jsapi.cx(); // Check if we're anywhere near the stack limit before we reach the // transplanting code, since it has no good way to handle errors. This uses // the untrusted script limit, which is not strictly necessary since no // actual script should run. if (!js::CheckRecursionLimitConservativeDontReport(cx)) { NS_WARNING("Overrecursion in SetNewDocument"); return NS_ERROR_FAILURE; } if (!mDoc) { // First document load. // Get our private root. If it is equal to us, then we need to // attach our global key bindings that handles browser scrolling // and other browser commands. nsPIDOMWindowOuter* privateRoot = GetPrivateRoot(); if (privateRoot == this) { nsXBLService::AttachGlobalKeyHandler(mChromeEventHandler); } } /* No mDocShell means we're already been partially closed down. When that happens, setting status isn't a big requirement, so don't. (Doesn't happen under normal circumstances, but bug 49615 describes a case.) */ nsContentUtils::AddScriptRunner(NewRunnableMethod( "nsGlobalWindowOuter::ClearStatus", this, &nsGlobalWindowOuter::ClearStatus)); // Sometimes, WouldReuseInnerWindow() returns true even if there's no inner // window (see bug 776497). Be safe. bool reUseInnerWindow = (aForceReuseInnerWindow || wouldReuseInnerWindow) && GetCurrentInnerWindowInternal(); nsresult rv; // We set mDoc even though this is an outer window to avoid // having to *always* reach into the inner window to find the // document. mDoc = aDocument; // Take this opportunity to clear mSuspendedDoc. Our old inner window is now // responsible for unsuspending it. mSuspendedDoc = nullptr; #ifdef DEBUG mLastOpenedURI = aDocument->GetDocumentURI(); #endif mContext->WillInitializeContext(); RefPtr currentInner = GetCurrentInnerWindowInternal(); if (currentInner && currentInner->mNavigator) { currentInner->mNavigator->OnNavigation(); } RefPtr newInnerWindow; bool createdInnerWindow = false; bool thisChrome = IsChromeWindow(); nsCOMPtr wsh = do_QueryInterface(aState); NS_ASSERTION(!aState || wsh, "What kind of weird state are you giving me here?"); bool handleDocumentOpen = false; bool doomCurrentInner = false; JS::Rooted newInnerGlobal(cx); if (reUseInnerWindow) { // We're reusing the current inner window. NS_ASSERTION(!currentInner->IsFrozen(), "We should never be reusing a shared inner window"); newInnerWindow = currentInner; newInnerGlobal = currentInner->GetWrapperPreserveColor(); if (aDocument != oldDoc) { JS::ExposeObjectToActiveJS(newInnerGlobal); } // We're reusing the inner window, but this still counts as a navigation, // so all expandos and such defined on the outer window should go away. Force // all Xray wrappers to be recomputed. JS::Rooted rootedObject(cx, GetWrapper()); if (!JS_RefreshCrossCompartmentWrappers(cx, rootedObject)) { return NS_ERROR_FAILURE; } // Inner windows are only reused for same-origin principals, but the principals // don't necessarily match exactly. Update the principal on the realm to match // the new document. // NB: We don't just call currentInner->RefreshRealmPrincipals() here // because we haven't yet set its mDoc to aDocument. JS::Realm* realm = js::GetNonCCWObjectRealm(newInnerGlobal); #ifdef DEBUG bool sameOrigin = false; nsIPrincipal *existing = nsJSPrincipals::get(JS::GetRealmPrincipals(realm)); aDocument->NodePrincipal()->Equals(existing, &sameOrigin); MOZ_ASSERT(sameOrigin); MOZ_ASSERT_IF(aDocument == oldDoc, xpc::GetRealmPrincipal(realm) == aDocument->NodePrincipal()); #endif if (aDocument != oldDoc) { JS::SetRealmPrincipals(realm, nsJSPrincipals::get(aDocument->NodePrincipal())); // Make sure we clear out the old content XBL scope, so the new one will // get created with a principal that subsumes our new principal. xpc::ClearContentXBLScope(newInnerGlobal); } } else { if (aState) { newInnerWindow = wsh->GetInnerWindow(); newInnerGlobal = newInnerWindow->GetWrapperPreserveColor(); } else { newInnerWindow = nsGlobalWindowInner::Create(this, thisChrome); // The outer window is automatically treated as frozen when we // null out the inner window. As a result, initializing classes // on the new inner won't end up reaching into the old inner // window for classes etc. // // [This happens with Object.prototype when XPConnect creates // a temporary global while initializing classes; the reason // being that xpconnect creates the temp global w/o a parent // and proto, which makes the JS engine look up classes in // cx->globalObject, i.e. this outer window]. mInnerWindow = nullptr; mCreatingInnerWindow = true; // Every script context we are initialized with must create a // new global. rv = CreateNativeGlobalForInner(cx, newInnerWindow, aDocument->GetDocumentURI(), aDocument->NodePrincipal(), &newInnerGlobal, ComputeIsSecureContext(aDocument)); NS_ASSERTION(NS_SUCCEEDED(rv) && newInnerGlobal && newInnerWindow->GetWrapperPreserveColor() == newInnerGlobal, "Failed to get script global"); mCreatingInnerWindow = false; createdInnerWindow = true; NS_ENSURE_SUCCESS(rv, rv); } if (currentInner && currentInner->GetWrapperPreserveColor()) { if (oldDoc == aDocument) { handleDocumentOpen = true; } // Don't free objects on our current inner window if it's going to be // held in the bfcache. if (!currentInner->IsFrozen()) { doomCurrentInner = true; } } mInnerWindow = newInnerWindow->AsInner(); MOZ_ASSERT(mInnerWindow); mInnerWindow->TryToCacheTopInnerWindow(); if (!GetWrapperPreserveColor()) { JS::Rooted outer(cx, NewOuterWindowProxy(cx, newInnerGlobal, thisChrome)); NS_ENSURE_TRUE(outer, NS_ERROR_FAILURE); js::SetProxyReservedSlot(outer, 0, js::PrivateValue(ToSupports(this))); // Inform the nsJSContext, which is the canonical holder of the outer. mContext->SetWindowProxy(outer); mContext->DidInitializeContext(); SetWrapper(mContext->GetWindowProxy()); } else { JS::ExposeObjectToActiveJS(newInnerGlobal); JS::Rooted outerObject(cx, NewOuterWindowProxy(cx, newInnerGlobal, thisChrome)); if (!outerObject) { NS_ERROR("out of memory"); return NS_ERROR_FAILURE; } JS::Rooted obj(cx, GetWrapperPreserveColor()); js::SetProxyReservedSlot(obj, 0, js::PrivateValue(nullptr)); js::SetProxyReservedSlot(outerObject, 0, js::PrivateValue(nullptr)); outerObject = xpc::TransplantObject(cx, obj, outerObject); if (!outerObject) { NS_ERROR("unable to transplant wrappers, probably OOM"); return NS_ERROR_FAILURE; } js::SetProxyReservedSlot(outerObject, 0, js::PrivateValue(ToSupports(this))); SetWrapper(outerObject); MOZ_ASSERT(JS::GetNonCCWObjectGlobal(outerObject) == newInnerGlobal); // Inform the nsJSContext, which is the canonical holder of the outer. mContext->SetWindowProxy(outerObject); } // Enter the new global's realm. JSAutoRealm ar(cx, GetWrapperPreserveColor()); { JS::Rooted outer(cx, GetWrapperPreserveColor()); js::SetWindowProxy(cx, newInnerGlobal, outer); } // Set scriptability based on the state of the docshell. bool allow = GetDocShell()->GetCanExecuteScripts(); xpc::Scriptability::Get(GetWrapperPreserveColor()).SetDocShellAllowsScript(allow); if (!aState) { // Get the "window" property once so it will be cached on our inner. We // have to do this here, not in binding code, because this has to happen // after we've created the outer window proxy and stashed it in the outer // nsGlobalWindowOuter, so GetWrapperPreserveColor() on that outer // nsGlobalWindowOuter doesn't return null and nsGlobalWindowOuter::OuterObject // works correctly. JS::Rooted unused(cx); if (!JS_GetProperty(cx, newInnerGlobal, "window", &unused)) { NS_ERROR("can't create the 'window' property"); return NS_ERROR_FAILURE; } // And same thing for the "self" property. if (!JS_GetProperty(cx, newInnerGlobal, "self", &unused)) { NS_ERROR("can't create the 'self' property"); return NS_ERROR_FAILURE; } } } JSAutoRealm ar(cx, GetWrapperPreserveColor()); if (!aState && !reUseInnerWindow) { // Loading a new page and creating a new inner window, *not* // restoring from session history. // Now that both the the inner and outer windows are initialized // let the script context do its magic to hook them together. MOZ_ASSERT(mContext->GetWindowProxy() == GetWrapperPreserveColor()); #ifdef DEBUG JS::Rooted rootedJSObject(cx, GetWrapperPreserveColor()); JS::Rooted proto1(cx), proto2(cx); JS_GetPrototype(cx, rootedJSObject, &proto1); JS_GetPrototype(cx, newInnerGlobal, &proto2); NS_ASSERTION(proto1 == proto2, "outer and inner globals should have the same prototype"); #endif mInnerWindow->SyncStateFromParentWindow(); } // Add an extra ref in case we release mContext during GC. nsCOMPtr kungFuDeathGrip(mContext); aDocument->SetScriptGlobalObject(newInnerWindow); MOZ_ASSERT(newInnerWindow->mTabGroup, "We must have a TabGroup cached at this point"); if (!aState) { if (reUseInnerWindow) { if (newInnerWindow->mDoc != aDocument) { newInnerWindow->mDoc = aDocument; // The storage objects contain the URL of the window. We have to // recreate them when the innerWindow is reused. newInnerWindow->mLocalStorage = nullptr; newInnerWindow->mSessionStorage = nullptr; newInnerWindow->mPerformance = nullptr; // This must be called after nullifying the internal objects because // here we could recreate them, calling the getter methods, and store // them into the JS slots. If we nullify them after, the slot values and // the objects will be out of sync. newInnerWindow->ClearDocumentDependentSlots(cx); // When replacing an initial about:blank document we call // ExecutionReady again to update the client creation URL. rv = newInnerWindow->ExecutionReady(); NS_ENSURE_SUCCESS(rv, rv); } } else { newInnerWindow->InnerSetNewDocument(cx, aDocument); // Initialize DOM classes etc on the inner window. JS::Rooted obj(cx, newInnerGlobal); rv = kungFuDeathGrip->InitClasses(obj); NS_ENSURE_SUCCESS(rv, rv); rv = newInnerWindow->ExecutionReady(); NS_ENSURE_SUCCESS(rv, rv); } if (mArguments) { newInnerWindow->DefineArgumentsProperty(mArguments); mArguments = nullptr; } // Give the new inner window our chrome event handler (since it // doesn't have one). newInnerWindow->mChromeEventHandler = mChromeEventHandler; } // Handle any document.open() logic after we setup the new inner window // so that any bound DETH objects can see the top window, document, etc. if (handleDocumentOpen) { newInnerWindow->MigrateStateForDocumentOpen(currentInner); } // We no longer need the old inner window. Start its destruction if // its not being reused and clear our reference. if (doomCurrentInner) { currentInner->FreeInnerObjects(handleDocumentOpen); } currentInner = nullptr; // Ask the JS engine to assert that it's valid to access our DocGroup whenever // it runs JS code for this realm. We skip the check if this window is for // chrome JS or an add-on. nsCOMPtr principal = mDoc->NodePrincipal(); if (GetDocGroup() && !nsContentUtils::IsSystemPrincipal(principal) && !BasePrincipal::Cast(principal)->AddonPolicy()) { js::SetRealmValidAccessPtr(cx, newInnerGlobal, newInnerWindow->GetDocGroup()->GetValidAccessPtr()); } kungFuDeathGrip->DidInitializeContext(); // We wait to fire the debugger hook until the window is all set up and hooked // up with the outer. See bug 969156. if (createdInnerWindow) { nsContentUtils::AddScriptRunner( NewRunnableMethod("nsGlobalWindowInner::FireOnNewGlobalObject", newInnerWindow, &nsGlobalWindowInner::FireOnNewGlobalObject)); } if (newInnerWindow && !newInnerWindow->mHasNotifiedGlobalCreated && mDoc) { // We should probably notify. However if this is the, arguably bad, // situation when we're creating a temporary non-chrome-about-blank // document in a chrome docshell, don't notify just yet. Instead wait // until we have a real chrome doc. if (!mDocShell || mDocShell->ItemType() != nsIDocShellTreeItem::typeChrome || nsContentUtils::IsSystemPrincipal(mDoc->NodePrincipal())) { newInnerWindow->mHasNotifiedGlobalCreated = true; nsContentUtils::AddScriptRunner( NewRunnableMethod("nsGlobalWindowOuter::DispatchDOMWindowCreated", this, &nsGlobalWindowOuter::DispatchDOMWindowCreated)); } } PreloadLocalStorage(); // If we have a recorded interesting Large-Allocation header status, report it // to the newly attached document. ReportLargeAllocStatus(); mLargeAllocStatus = LargeAllocStatus::NONE; mHasStorageAccess = false; nsIURI* uri = aDocument->GetDocumentURI(); if (newInnerWindow) { if (AntiTrackingCommon::ShouldHonorContentBlockingCookieRestrictions() && StaticPrefs::network_cookie_cookieBehavior() == nsICookieService::BEHAVIOR_REJECT_TRACKER && nsContentUtils::IsThirdPartyWindowOrChannel(newInnerWindow, nullptr, uri) && nsContentUtils::IsTrackingResourceWindow(newInnerWindow)) { // Grant storage access by default if the first-party storage access // permission has been granted already. // Don't notify in this case, since we would be notifying the user needlessly. mHasStorageAccess = AntiTrackingCommon::IsFirstPartyStorageAccessGrantedFor(newInnerWindow, uri, nullptr); } } return NS_OK; } void nsGlobalWindowOuter::PreloadLocalStorage() { if (!Storage::StoragePrefIsEnabled()) { return; } if (IsChromeWindow()) { return; } nsIPrincipal* principal = GetPrincipal(); if (!principal) { return; } nsresult rv; nsCOMPtr storageManager = do_GetService("@mozilla.org/dom/localStorage-manager;1", &rv); if (NS_FAILED(rv)) { return; } // private browsing windows do not persist local storage to disk so we should // only try to precache storage when we're not a private browsing window. if (principal->GetPrivateBrowsingId() == 0) { RefPtr storage; rv = storageManager->PrecacheStorage(principal, getter_AddRefs(storage)); if (NS_SUCCEEDED(rv)) { mLocalStorage = storage; } } } void nsGlobalWindowOuter::DispatchDOMWindowCreated() { if (!mDoc) { return; } // Fire DOMWindowCreated at chrome event listeners nsContentUtils::DispatchChromeEvent(mDoc, mDoc, NS_LITERAL_STRING("DOMWindowCreated"), CanBubble::eYes, Cancelable::eNo); nsCOMPtr observerService = mozilla::services::GetObserverService(); // The event dispatching could possibly cause docshell destory, and // consequently cause mDoc to be set to nullptr by DropOuterWindowDocs(), // so check it again here. if (observerService && mDoc) { nsAutoString origin; nsIPrincipal* principal = mDoc->NodePrincipal(); nsContentUtils::GetUTFOrigin(principal, origin); observerService-> NotifyObservers(static_cast(this), nsContentUtils::IsSystemPrincipal(principal) ? "chrome-document-global-created" : "content-document-global-created", origin.get()); } } void nsGlobalWindowOuter::ClearStatus() { SetStatusOuter(EmptyString()); } void nsGlobalWindowOuter::SetDocShell(nsIDocShell* aDocShell) { MOZ_ASSERT(aDocShell); if (aDocShell == mDocShell) { return; } mDocShell = aDocShell; // Weak Reference nsCOMPtr parentWindow = GetScriptableParentOrNull(); MOZ_RELEASE_ASSERT(!parentWindow || !mTabGroup || mTabGroup == nsGlobalWindowOuter::Cast(parentWindow)->mTabGroup); mTopLevelOuterContentWindow = !mIsChrome && GetScriptableTopInternal() == this; if (mFrames) { mFrames->SetDocShell(aDocShell); } // Get our enclosing chrome shell and retrieve its global window impl, so // that we can do some forwarding to the chrome document. RefPtr chromeEventHandler; mDocShell->GetChromeEventHandler(getter_AddRefs(chromeEventHandler)); mChromeEventHandler = chromeEventHandler; if (!mChromeEventHandler) { // We have no chrome event handler. If we have a parent, // get our chrome event handler from the parent. If // we don't have a parent, then we need to make a new // window root object that will function as a chrome event // handler and receive all events that occur anywhere inside // our window. nsCOMPtr parentWindow = GetParent(); if (parentWindow.get() != this) { mChromeEventHandler = parentWindow->GetChromeEventHandler(); } else { mChromeEventHandler = NS_NewWindowRoot(this); mIsRootOuterWindow = true; } } bool docShellActive; mDocShell->GetIsActive(&docShellActive); SetIsBackgroundInternal(!docShellActive); } void nsGlobalWindowOuter::DetachFromDocShell() { // DetachFromDocShell means the window is being torn down. Drop our // reference to the script context, allowing it to be deleted // later. Meanwhile, keep our weak reference to the script object // so that it can be retrieved later (until it is finalized by the JS GC). // Call FreeInnerObjects on all inner windows, not just the current // one, since some could be held by WindowStateHolder objects that // are GC-owned. RefPtr inner; for (PRCList* node = PR_LIST_HEAD(this); node != this; node = PR_NEXT_LINK(inner)) { // This cast is safe because `node != this`. Non-this nodes are inner windows. inner = static_cast(node); MOZ_ASSERT(!inner->mOuterWindow || inner->mOuterWindow == this); inner->FreeInnerObjects(); } // Don't report that we were detached to the nsWindowMemoryReporter, as it // only tracks inner windows. NotifyWindowIDDestroyed("outer-window-destroyed"); nsGlobalWindowInner *currentInner = GetCurrentInnerWindowInternal(); if (currentInner) { NS_ASSERTION(mDoc, "Must have doc!"); // Remember the document's principal and URI. mDocumentPrincipal = mDoc->NodePrincipal(); mDocumentURI = mDoc->GetDocumentURI(); // Release our document reference DropOuterWindowDocs(); } ClearControllers(); mChromeEventHandler = nullptr; // force release now if (mContext) { // When we're about to destroy a top level content window // (for example a tab), we trigger a full GC by passing null as the last // param. We also trigger a full GC for chrome windows. nsJSContext::PokeGC(JS::gcreason::SET_DOC_SHELL, (mTopLevelOuterContentWindow || mIsChrome) ? nullptr : GetWrapperPreserveColor()); mContext = nullptr; } mDocShell = nullptr; // Weak Reference if (mFrames) { mFrames->SetDocShell(nullptr); } MaybeForgiveSpamCount(); CleanUp(); } void nsGlobalWindowOuter::SetOpenerWindow(nsPIDOMWindowOuter* aOpener, bool aOriginalOpener) { nsWeakPtr opener = do_GetWeakReference(aOpener); if (opener == mOpener) { return; } NS_ASSERTION(!aOriginalOpener || !mSetOpenerWindowCalled, "aOriginalOpener is true, but not first call to " "SetOpenerWindow!"); NS_ASSERTION(aOpener || !aOriginalOpener, "Shouldn't set mHadOriginalOpener if aOpener is null"); mOpener = opener.forget(); NS_ASSERTION(mOpener || !aOpener, "Opener must support weak references!"); // Check that the js visible opener matches! We currently don't depend on this // being true outside of nightly, so we disable the assertion in optimized // release / beta builds. nsPIDOMWindowOuter* contentOpener = GetSanitizedOpener(aOpener); // contentOpener is not used when the DIAGNOSTIC_ASSERT is compiled out. mozilla::Unused << contentOpener; MOZ_DIAGNOSTIC_ASSERT(!contentOpener || !mTabGroup || mTabGroup == nsGlobalWindowOuter::Cast(contentOpener)->mTabGroup); if (aOriginalOpener) { MOZ_ASSERT(!mHadOriginalOpener, "Probably too late to call ComputeIsSecureContext again"); mHadOriginalOpener = true; } #ifdef DEBUG mSetOpenerWindowCalled = true; #endif } void nsGlobalWindowOuter::UpdateParentTarget() { // NOTE: This method is nearly identical to // nsGlobalWindowInner::UpdateParentTarget(). IF YOU UPDATE THIS METHOD, // UPDATE THE OTHER ONE TOO! The one difference is that this method updates // mMessageManager as well, which inner windows don't have. // Try to get our frame element's tab child global (its in-process message // manager). If that fails, fall back to the chrome event handler's tab // child global, and if it doesn't have one, just use the chrome event // handler itself. nsCOMPtr frameElement = GetOuterWindow()->GetFrameElementInternal(); mMessageManager = nsContentUtils::TryGetTabChildGlobal(frameElement); if (!mMessageManager) { nsGlobalWindowOuter* topWin = GetScriptableTopInternal(); if (topWin) { frameElement = topWin->GetFrameElementInternal(); mMessageManager = nsContentUtils::TryGetTabChildGlobal(frameElement); } } if (!mMessageManager) { mMessageManager = nsContentUtils::TryGetTabChildGlobal(mChromeEventHandler); } if (mMessageManager) { mParentTarget = mMessageManager; } else { mParentTarget = mChromeEventHandler; } } EventTarget* nsGlobalWindowOuter::GetTargetForEventTargetChain() { return GetCurrentInnerWindowInternal(); } void nsGlobalWindowOuter::GetEventTargetParent(EventChainPreVisitor& aVisitor) { MOZ_CRASH("The outer window should not be part of an event path"); } bool nsGlobalWindowOuter::ShouldPromptToBlockDialogs() { nsGlobalWindowOuter *topWindowOuter = GetScriptableTopInternal(); if (!topWindowOuter) { NS_ASSERTION(!mDocShell, "ShouldPromptToBlockDialogs() called without a top window?"); return true; } nsGlobalWindowInner* topWindow = topWindowOuter->GetCurrentInnerWindowInternal(); if (!topWindow) { return true; } return topWindow->DialogsAreBeingAbused(); } bool nsGlobalWindowOuter::AreDialogsEnabled() { nsGlobalWindowOuter *topWindowOuter = GetScriptableTopInternal(); if (!topWindowOuter) { NS_ERROR("AreDialogsEnabled() called without a top window?"); return false; } // TODO: Warn if no top window? nsGlobalWindowInner* topWindow = topWindowOuter->GetCurrentInnerWindowInternal(); if (!topWindow) { return false; } // Dialogs are blocked if the content viewer is hidden if (mDocShell) { nsCOMPtr cv; mDocShell->GetContentViewer(getter_AddRefs(cv)); bool isHidden; cv->GetIsHidden(&isHidden); if (isHidden) { return false; } } // Dialogs are also blocked if the document is sandboxed with SANDBOXED_MODALS // (or if we have no document, of course). Which document? Who knows; the // spec is daft. See . For now // just go ahead and check mDoc, since in everything except edge cases in // which a frame is allow-same-origin but not allow-scripts and is being poked // at by some other window this should be the right thing anyway. if (!mDoc || (mDoc->GetSandboxFlags() & SANDBOXED_MODALS)) { return false; } return topWindow->mAreDialogsEnabled; } bool nsGlobalWindowOuter::ConfirmDialogIfNeeded() { NS_ENSURE_TRUE(mDocShell, false); nsCOMPtr promptSvc = do_GetService("@mozilla.org/embedcomp/prompt-service;1"); if (!promptSvc) { return true; } // Reset popup state while opening a modal dialog, and firing events // about the dialog, to prevent the current state from being active // the whole time a modal dialog is open. nsAutoPopupStatePusher popupStatePusher(openAbused, true); bool disableDialog = false; nsAutoString label, title; nsContentUtils::GetLocalizedString(nsContentUtils::eCOMMON_DIALOG_PROPERTIES, "ScriptDialogLabel", label); nsContentUtils::GetLocalizedString(nsContentUtils::eCOMMON_DIALOG_PROPERTIES, "ScriptDialogPreventTitle", title); promptSvc->Confirm(this, title.get(), label.get(), &disableDialog); if (disableDialog) { DisableDialogs(); return false; } return true; } void nsGlobalWindowOuter::DisableDialogs() { nsGlobalWindowOuter *topWindowOuter = GetScriptableTopInternal(); if (!topWindowOuter) { NS_ERROR("DisableDialogs() called without a top window?"); return; } nsGlobalWindowInner* topWindow = topWindowOuter->GetCurrentInnerWindowInternal(); // TODO: Warn if no top window? if (topWindow) { topWindow->mAreDialogsEnabled = false; } } void nsGlobalWindowOuter::EnableDialogs() { nsGlobalWindowOuter *topWindowOuter = GetScriptableTopInternal(); if (!topWindowOuter) { NS_ERROR("EnableDialogs() called without a top window?"); return; } // TODO: Warn if no top window? nsGlobalWindowInner* topWindow = topWindowOuter->GetCurrentInnerWindowInternal(); if (topWindow) { topWindow->mAreDialogsEnabled = true; } } nsresult nsGlobalWindowOuter::PostHandleEvent(EventChainPostVisitor& aVisitor) { MOZ_CRASH("The outer window should not be part of an event path"); } void nsGlobalWindowOuter::PoisonOuterWindowProxy(JSObject *aObject) { if (aObject == GetWrapperMaybeDead()) { PoisonWrapper(); } } nsresult nsGlobalWindowOuter::SetArguments(nsIArray *aArguments) { nsresult rv; // Historically, we've used the same machinery to handle openDialog arguments // (exposed via window.arguments) and showModalDialog arguments (exposed via // window.dialogArguments), even though the former is XUL-only and uses an XPCOM // array while the latter is web-exposed and uses an arbitrary JS value. // Moreover, per-spec |dialogArguments| is a property of the browsing context // (outer), whereas |arguments| lives on the inner. // // We've now mostly separated them, but the difference is still opaque to // nsWindowWatcher (the caller of SetArguments in this little back-and-forth // embedding waltz we do here). // // So we need to demultiplex the two cases here. nsGlobalWindowInner *currentInner = GetCurrentInnerWindowInternal(); mArguments = aArguments; rv = currentInner->DefineArgumentsProperty(aArguments); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } //***************************************************************************** // nsGlobalWindowOuter::nsIScriptObjectPrincipal //***************************************************************************** nsIPrincipal* nsGlobalWindowOuter::GetPrincipal() { if (mDoc) { // If we have a document, get the principal from the document return mDoc->NodePrincipal(); } if (mDocumentPrincipal) { return mDocumentPrincipal; } // If we don't have a principal and we don't have a document we // ask the parent window for the principal. This can happen when // loading a frameset that has a , in // that case the global window is used in JS before we've loaded // a document into the window. nsCOMPtr objPrincipal = do_QueryInterface(GetParentInternal()); if (objPrincipal) { return objPrincipal->GetPrincipal(); } return nullptr; } //***************************************************************************** // nsGlobalWindowOuter::nsIDOMWindow //***************************************************************************** void nsPIDOMWindowOuter::SetInitialKeyboardIndicators( UIStateChangeType aShowAccelerators, UIStateChangeType aShowFocusRings) { MOZ_ASSERT(!GetCurrentInnerWindow()); nsPIDOMWindowOuter* piWin = GetPrivateRoot(); if (!piWin) { return; } MOZ_ASSERT(piWin == this); // only change the flags that have been modified nsCOMPtr windowRoot = do_QueryInterface(mChromeEventHandler); if (!windowRoot) { return; } if (aShowAccelerators != UIStateChangeType_NoChange) { windowRoot->SetShowAccelerators(aShowAccelerators == UIStateChangeType_Set); } if (aShowFocusRings != UIStateChangeType_NoChange) { windowRoot->SetShowFocusRings(aShowFocusRings == UIStateChangeType_Set); } nsContentUtils::SetKeyboardIndicatorsOnRemoteChildren(GetOuterWindow(), aShowAccelerators, aShowFocusRings); } Element* nsPIDOMWindowOuter::GetFrameElementInternal() const { return mFrameElement; } void nsPIDOMWindowOuter::SetFrameElementInternal(Element* aFrameElement) { mFrameElement = aFrameElement; } Navigator* nsGlobalWindowOuter::GetNavigator() { FORWARD_TO_INNER(Navigator, (), nullptr); } nsScreen* nsGlobalWindowOuter::GetScreen() { FORWARD_TO_INNER(GetScreen, (IgnoreErrors()), nullptr); } void nsPIDOMWindowOuter::MaybeActiveMediaComponents() { if (mMediaSuspend != nsISuspendedTypes::SUSPENDED_BLOCK) { return; } MOZ_LOG(AudioChannelService::GetAudioChannelLog(), LogLevel::Debug, ("nsPIDOMWindowOuter, MaybeActiveMediaComponents, " "resume the window from blocked, this = %p\n", this)); SetMediaSuspend(nsISuspendedTypes::NONE_SUSPENDED); } SuspendTypes nsPIDOMWindowOuter::GetMediaSuspend() const { return mMediaSuspend; } void nsPIDOMWindowOuter::SetMediaSuspend(SuspendTypes aSuspend) { if (!IsDisposableSuspend(aSuspend)) { MaybeNotifyMediaResumedFromBlock(aSuspend); mMediaSuspend = aSuspend; } RefreshMediaElementsSuspend(aSuspend); } void nsPIDOMWindowOuter::MaybeNotifyMediaResumedFromBlock(SuspendTypes aSuspend) { if (mMediaSuspend == nsISuspendedTypes::SUSPENDED_BLOCK && aSuspend == nsISuspendedTypes::NONE_SUSPENDED) { RefPtr service = AudioChannelService::GetOrCreate(); if (service) { service->NotifyMediaResumedFromBlock(GetOuterWindow()); } } } bool nsPIDOMWindowOuter::GetAudioMuted() const { return mAudioMuted; } void nsPIDOMWindowOuter::SetAudioMuted(bool aMuted) { if (mAudioMuted == aMuted) { return; } mAudioMuted = aMuted; RefreshMediaElementsVolume(); } float nsPIDOMWindowOuter::GetAudioVolume() const { return mAudioVolume; } nsresult nsPIDOMWindowOuter::SetAudioVolume(float aVolume) { if (aVolume < 0.0) { return NS_ERROR_DOM_INDEX_SIZE_ERR; } if (mAudioVolume == aVolume) { return NS_OK; } mAudioVolume = aVolume; RefreshMediaElementsVolume(); return NS_OK; } void nsPIDOMWindowOuter::RefreshMediaElementsVolume() { RefPtr service = AudioChannelService::GetOrCreate(); if (service) { service->RefreshAgentsVolume(GetOuterWindow()); } } void nsPIDOMWindowOuter::RefreshMediaElementsSuspend(SuspendTypes aSuspend) { RefPtr service = AudioChannelService::GetOrCreate(); if (service) { service->RefreshAgentsSuspend(GetOuterWindow(), aSuspend); } } bool nsPIDOMWindowOuter::IsDisposableSuspend(SuspendTypes aSuspend) const { return (aSuspend == nsISuspendedTypes::SUSPENDED_PAUSE_DISPOSABLE || aSuspend == nsISuspendedTypes::SUSPENDED_STOP_DISPOSABLE); } void nsPIDOMWindowOuter::SetServiceWorkersTestingEnabled(bool aEnabled) { // Devtools should only be setting this on the top level window. Its // ok if devtools clears the flag on clean up of nested windows, though. // It will have no affect. #ifdef DEBUG nsCOMPtr topWindow = GetScriptableTop(); MOZ_ASSERT_IF(aEnabled, this == topWindow); #endif mServiceWorkersTestingEnabled = aEnabled; } bool nsPIDOMWindowOuter::GetServiceWorkersTestingEnabled() { // Automatically get this setting from the top level window so that nested // iframes get the correct devtools setting. nsCOMPtr topWindow = GetScriptableTop(); if (!topWindow) { return false; } return topWindow->mServiceWorkersTestingEnabled; } already_AddRefed nsGlobalWindowOuter::GetParentOuter() { if (!mDocShell) { return nullptr; } nsCOMPtr parent; if (mDocShell->GetIsMozBrowser()) { parent = this; } else { parent = GetParent(); } return parent.forget(); } /** * GetScriptableParent is called when script reads window.parent. * * In contrast to GetRealParent, GetScriptableParent respects