From 39a4e30ae8c90809d825b81a9a8a00c8d66b0fa6 Mon Sep 17 00:00:00 2001 From: roytam1 Date: Fri, 18 Sep 2020 21:45:13 +0800 Subject: [PATCH] import changes from `dev' branch of rmottola/Arctic-Fox: - pointer style (db52d9c32) - Bug 1158407 - Stop using this one weird allocation fallback for MCreateThisWithTemplate. (r=terrence) (5b489cd5d) - Bug 1170124 - Remove unnecessary type monitoring in jit::InvokeFunction. r=bhackett (1603ee063) - Bug 1141865 - Part 2: Plumb new.target on the stack and make it accessible to JSNatives. (r=jorendorff, r=jandem, r=shu) (25cfa92ec) - Bug 1129795 - Convert rest of docshell/ to Gecko style. r=mccr8 (20acc2d82) - Bug 1162309 - Part 1: Remove instances of #ifdef PR_LOGGING in uriloader. r=froydnj (8768f60c0) - Bug 1162309 - Part 2: Remove instances of #ifdef PR_LOGGING in docshell. r=froydnj (e9de046f3) - Bug 1096908 - forward network security messages to the content process; r=hurley (69b38e624) - Bug 1156493 - e10s: move .cacheKey to nsICacheInfoChannel so child channels can get/set it, r=jduell (507efbe2b) - Bug 1017758 - Use infallible getters for appId/isInBrowserElement/unknownAppId; r=bz (8021f0ae8) --- docshell/base/LoadContext.cpp | 14 +- docshell/base/LoadContext.h | 13 +- docshell/base/SerializedLoadContext.cpp | 1 - docshell/base/SerializedLoadContext.h | 11 +- docshell/base/nsDSURIContentListener.cpp | 38 +- docshell/base/nsDefaultURIFixup.cpp | 3 +- docshell/base/nsDocShell.cpp | 159 +++--- docshell/base/nsDocShell.h | 100 ++-- docshell/base/nsDocShellEditorData.h | 1 - docshell/base/nsDocShellEnumerator.h | 1 - docshell/base/nsDocShellLoadInfo.cpp | 13 - docshell/base/nsDocShellLoadTypes.h | 7 +- docshell/base/nsDocShellTransferableHooks.cpp | 4 - docshell/base/nsDownloadHistory.cpp | 9 +- docshell/base/nsILinkHandler.h | 1 - docshell/base/nsIWebShellServices.h | 6 +- docshell/base/nsWebNavigationInfo.h | 1 - docshell/build/nsDocShellCID.h | 18 +- docshell/build/nsDocShellModule.cpp | 5 +- docshell/shistory/src/nsSHEntry.cpp | 272 +++++----- docshell/shistory/src/nsSHEntry.h | 38 +- docshell/shistory/src/nsSHEntryShared.cpp | 46 +- docshell/shistory/src/nsSHEntryShared.h | 93 ++-- docshell/shistory/src/nsSHTransaction.cpp | 92 ++-- docshell/shistory/src/nsSHTransaction.h | 22 +- docshell/shistory/src/nsSHistory.cpp | 500 +++++++++--------- docshell/shistory/src/nsSHistory.h | 44 +- dom/base/nsDocument.cpp | 29 +- dom/base/nsGlobalWindow.cpp | 9 +- dom/storage/DOMStorageManager.cpp | 32 +- .../webbrowserpersist/nsWebBrowserPersist.cpp | 4 +- js/public/CallArgs.h | 19 +- js/src/frontend/BytecodeEmitter.cpp | 13 + .../tests/basic/newTargetRectifier.js | 12 + .../tests/debug/Frame-newTargetOverflow-01.js | 37 ++ .../tests/proxy/testDirectProxyConstruct1.js | 4 +- .../tests/proxy/testDirectProxyConstruct2.js | 6 +- js/src/jit/BaselineBailouts.cpp | 28 +- js/src/jit/BaselineCompiler.cpp | 8 +- js/src/jit/BaselineFrame.cpp | 2 +- js/src/jit/BaselineIC.cpp | 174 ++++-- js/src/jit/BaselineIC.h | 7 +- js/src/jit/CodeGenerator.cpp | 73 +-- js/src/jit/CodeGenerator.h | 7 +- js/src/jit/Ion.cpp | 8 +- js/src/jit/IonBuilder.cpp | 13 +- js/src/jit/IonBuilder.h | 25 +- js/src/jit/JitFrameIterator.h | 5 +- js/src/jit/JitFrames.cpp | 8 +- js/src/jit/LIR-Common.h | 4 + js/src/jit/MCallOptimize.cpp | 11 +- js/src/jit/MacroAssembler.cpp | 91 ++-- js/src/jit/MacroAssembler.h | 62 ++- js/src/jit/VMFunctions.cpp | 45 +- js/src/jit/VMFunctions.h | 27 +- js/src/jit/arm/Trampoline-arm.cpp | 38 +- js/src/jit/x64/Trampoline-x64.cpp | 53 +- .../x86-shared/MacroAssembler-x86-shared.h | 5 + js/src/jit/x86/Trampoline-x86.cpp | 49 +- js/src/jsapi.cpp | 5 +- js/src/jsarray.cpp | 6 +- js/src/jsfun.cpp | 10 +- js/src/jsiter.cpp | 8 +- js/src/jsopcode.cpp | 4 +- js/src/proxy/CrossCompartmentWrapper.cpp | 2 + js/src/proxy/DirectProxyHandler.cpp | 2 +- js/src/proxy/ScriptedDirectProxyHandler.cpp | 5 +- js/src/proxy/ScriptedIndirectProxyHandler.cpp | 2 +- js/src/tests/ecma_6/Class/newTargetCCW.js | 10 + .../js1_7/extensions/regress-354945-01.js | 2 +- .../js1_7/extensions/regress-354945-02.js | 2 +- js/src/vm/Interpreter.cpp | 66 ++- js/src/vm/Interpreter.h | 4 +- js/src/vm/Opcodes.h | 8 +- js/src/vm/Stack-inl.h | 10 +- js/src/vm/Stack.cpp | 2 +- js/src/vm/Stack.h | 10 +- js/src/vm/Xdr.h | 2 +- netwerk/base/nsICacheInfoChannel.idl | 19 + netwerk/base/nsICachingChannel.idl | 21 +- netwerk/ipc/NeckoChannelParams.ipdlh | 13 + netwerk/protocol/http/HttpBaseChannel.h | 2 +- netwerk/protocol/http/HttpChannelChild.cpp | 59 ++- netwerk/protocol/http/HttpChannelChild.h | 10 +- netwerk/protocol/http/HttpChannelParent.cpp | 46 +- netwerk/protocol/http/HttpChannelParent.h | 5 + netwerk/protocol/http/PHttpChannel.ipdl | 11 +- netwerk/protocol/http/nsHttpChannel.cpp | 56 +- netwerk/protocol/http/nsHttpChannel.h | 51 ++ .../viewsource/nsViewSourceChannel.cpp | 4 + .../protocol/viewsource/nsViewSourceChannel.h | 3 +- uriloader/base/nsDocLoader.cpp | 9 +- uriloader/base/nsURILoader.cpp | 10 - uriloader/base/nsURILoader.h | 2 - .../exthandler/nsExternalHelperAppService.cpp | 8 - .../exthandler/nsExternalHelperAppService.h | 2 - .../prefetch/OfflineCacheUpdateChild.cpp | 4 - uriloader/prefetch/OfflineCacheUpdateGlue.cpp | 4 - .../prefetch/OfflineCacheUpdateParent.cpp | 2 - uriloader/prefetch/nsOfflineCacheUpdate.cpp | 8 - .../prefetch/nsOfflineCacheUpdateService.cpp | 4 - uriloader/prefetch/nsPrefetchService.cpp | 8 - 102 files changed, 1632 insertions(+), 1309 deletions(-) create mode 100644 js/src/jit-test/tests/basic/newTargetRectifier.js create mode 100644 js/src/jit-test/tests/debug/Frame-newTargetOverflow-01.js create mode 100644 js/src/tests/ecma_6/Class/newTargetCCW.js diff --git a/docshell/base/LoadContext.cpp b/docshell/base/LoadContext.cpp index 1d2df18742..5631b79896 100644 --- a/docshell/base/LoadContext.cpp +++ b/docshell/base/LoadContext.cpp @@ -11,7 +11,8 @@ namespace mozilla { NS_IMPL_ISUPPORTS(LoadContext, nsILoadContext, nsIInterfaceRequestor) -LoadContext::LoadContext(nsIPrincipal* aPrincipal, nsILoadContext* aOptionalBase) +LoadContext::LoadContext(nsIPrincipal* aPrincipal, + nsILoadContext* aOptionalBase) : mTopFrameElement(nullptr) , mNestedFrameId(0) , mIsContent(true) @@ -22,17 +23,18 @@ LoadContext::LoadContext(nsIPrincipal* aPrincipal, nsILoadContext* aOptionalBase #endif { MOZ_ALWAYS_TRUE(NS_SUCCEEDED(aPrincipal->GetAppId(&mAppId))); - MOZ_ALWAYS_TRUE(NS_SUCCEEDED( - aPrincipal->GetIsInBrowserElement(&mIsInBrowserElement))); + MOZ_ALWAYS_TRUE( + NS_SUCCEEDED(aPrincipal->GetIsInBrowserElement(&mIsInBrowserElement))); if (!aOptionalBase) { return; } MOZ_ALWAYS_TRUE(NS_SUCCEEDED(aOptionalBase->GetIsContent(&mIsContent))); - MOZ_ALWAYS_TRUE(NS_SUCCEEDED( - aOptionalBase->GetUsePrivateBrowsing(&mUsePrivateBrowsing))); - MOZ_ALWAYS_TRUE(NS_SUCCEEDED(aOptionalBase->GetUseRemoteTabs(&mUseRemoteTabs))); + MOZ_ALWAYS_TRUE( + NS_SUCCEEDED(aOptionalBase->GetUsePrivateBrowsing(&mUsePrivateBrowsing))); + MOZ_ALWAYS_TRUE( + NS_SUCCEEDED(aOptionalBase->GetUseRemoteTabs(&mUseRemoteTabs))); } //----------------------------------------------------------------------------- diff --git a/docshell/base/LoadContext.h b/docshell/base/LoadContext.h index 22fd28583d..ff0c9adfd0 100644 --- a/docshell/base/LoadContext.h +++ b/docshell/base/LoadContext.h @@ -53,7 +53,8 @@ public: #ifdef DEBUG , mIsNotNull(aToCopy.mIsNotNull) #endif - {} + { + } // AppId/inBrowser arguments override those in SerializedLoadContext provided // by child process. @@ -70,7 +71,8 @@ public: #ifdef DEBUG , mIsNotNull(aToCopy.mIsNotNull) #endif - {} + { + } LoadContext(dom::Element* aTopFrameElement, uint32_t aAppId, @@ -88,7 +90,8 @@ public: #ifdef DEBUG , mIsNotNull(true) #endif - {} + { + } // Constructor taking reserved appId for the safebrowsing cookie. explicit LoadContext(uint32_t aAppId) @@ -102,7 +105,8 @@ public: #ifdef DEBUG , mIsNotNull(true) #endif - {} + { + } // Constructor for creating a LoadContext with a given principal's appId and // browser flag. @@ -127,4 +131,3 @@ private: } // namespace mozilla #endif // LoadContext_h - diff --git a/docshell/base/SerializedLoadContext.cpp b/docshell/base/SerializedLoadContext.cpp index 0c746bd2b9..f328845b64 100644 --- a/docshell/base/SerializedLoadContext.cpp +++ b/docshell/base/SerializedLoadContext.cpp @@ -77,4 +77,3 @@ SerializedLoadContext::Init(nsILoadContext* aLoadContext) } } // namespace IPC - diff --git a/docshell/base/SerializedLoadContext.h b/docshell/base/SerializedLoadContext.h index fe2fb2e4db..4655dca68a 100644 --- a/docshell/base/SerializedLoadContext.h +++ b/docshell/base/SerializedLoadContext.h @@ -72,11 +72,11 @@ struct ParamTraits static bool Read(const Message* aMsg, void** aIter, paramType* aResult) { if (!ReadParam(aMsg, aIter, &aResult->mIsNotNull) || - !ReadParam(aMsg, aIter, &aResult->mIsContent) || - !ReadParam(aMsg, aIter, &aResult->mIsPrivateBitValid) || - !ReadParam(aMsg, aIter, &aResult->mUsePrivateBrowsing) || - !ReadParam(aMsg, aIter, &aResult->mUseRemoteTabs) || - !ReadParam(aMsg, aIter, &aResult->mAppId) || + !ReadParam(aMsg, aIter, &aResult->mIsContent) || + !ReadParam(aMsg, aIter, &aResult->mIsPrivateBitValid) || + !ReadParam(aMsg, aIter, &aResult->mUsePrivateBrowsing) || + !ReadParam(aMsg, aIter, &aResult->mUseRemoteTabs) || + !ReadParam(aMsg, aIter, &aResult->mAppId) || !ReadParam(aMsg, aIter, &aResult->mIsInBrowserElement)) { return false; } @@ -88,4 +88,3 @@ struct ParamTraits } // namespace IPC #endif // SerializedLoadContext_h - diff --git a/docshell/base/nsDSURIContentListener.cpp b/docshell/base/nsDSURIContentListener.cpp index 043e03315d..60d39f6313 100644 --- a/docshell/base/nsDSURIContentListener.cpp +++ b/docshell/base/nsDSURIContentListener.cpp @@ -26,10 +26,6 @@ using namespace mozilla; -//***************************************************************************** -//*** nsDSURIContentListener: Object Management -//***************************************************************************** - nsDSURIContentListener::nsDSURIContentListener(nsDocShell* aDocShell) : mDocShell(aDocShell) , mExistingJPEGRequest(nullptr) @@ -50,10 +46,6 @@ nsDSURIContentListener::Init() return rv; } -//***************************************************************************** -// nsDSURIContentListener::nsISupports -//***************************************************************************** - NS_IMPL_ADDREF(nsDSURIContentListener) NS_IMPL_RELEASE(nsDSURIContentListener) @@ -63,16 +55,11 @@ NS_INTERFACE_MAP_BEGIN(nsDSURIContentListener) NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) NS_INTERFACE_MAP_END -//***************************************************************************** -// nsDSURIContentListener::nsIURIContentListener -//***************************************************************************** - NS_IMETHODIMP nsDSURIContentListener::OnStartURIOpen(nsIURI* aURI, bool* aAbortOpen) { - // If mDocShell is null here, that means someone's starting a load - // in our docshell after it's already been destroyed. Don't let - // that happen. + // If mDocShell is null here, that means someone's starting a load in our + // docshell after it's already been destroyed. Don't let that happen. if (!mDocShell) { *aAbortOpen = true; return NS_OK; @@ -188,17 +175,16 @@ nsDSURIContentListener::IsPreferred(const char* aContentType, aDesiredContentType, aCanHandle); } - // we used to return false here if we didn't have a parent properly - // registered at the top of the docshell hierarchy to dictate what - // content types this docshell should be a preferred handler for. But - // this really makes it hard for developers using iframe or browser tags - // because then they need to make sure they implement - // nsIURIContentListener otherwise all link clicks would get sent to - // another window because we said we weren't the preferred handler type. - // I'm going to change the default now...if we can handle the content, - // and someone didn't EXPLICITLY set a nsIURIContentListener at the top - // of our docshell chain, then we'll now always attempt to process the - // content ourselves... + // we used to return false here if we didn't have a parent properly registered + // at the top of the docshell hierarchy to dictate what content types this + // docshell should be a preferred handler for. But this really makes it hard + // for developers using iframe or browser tags because then they need to make + // sure they implement nsIURIContentListener otherwise all link clicks would + // get sent to another window because we said we weren't the preferred handler + // type. I'm going to change the default now... if we can handle the content, + // and someone didn't EXPLICITLY set a nsIURIContentListener at the top of our + // docshell chain, then we'll now always attempt to process the content + // ourselves... return CanHandleContent(aContentType, true, aDesiredContentType, aCanHandle); } diff --git a/docshell/base/nsDefaultURIFixup.cpp b/docshell/base/nsDefaultURIFixup.cpp index f9bd0adf5e..c03e05543d 100644 --- a/docshell/base/nsDefaultURIFixup.cpp +++ b/docshell/base/nsDefaultURIFixup.cpp @@ -982,7 +982,8 @@ nsDefaultURIFixup::KeywordURIFixup(const nsACString& aURIString, // If we're at the end of the string or this is the first slash, // check if the thing before the slash looks like ipv4: - if ((iter.size_forward() == 1 || (lastSlashLoc == uint32_t(kNotFound) && *iter == '/')) && + if ((iter.size_forward() == 1 || + (lastSlashLoc == uint32_t(kNotFound) && *iter == '/')) && // Need 2 or 3 dots + only digits (foundDots == 2 || foundDots == 3) && // and they should be all that came before now: diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp index 5a65a06afc..16aab4311b 100644 --- a/docshell/base/nsDocShell.cpp +++ b/docshell/base/nsDocShell.cpp @@ -246,12 +246,10 @@ static uint32_t gValidateOrigin = 0xffffffff; // Can be overridden with docshell.event_starvation_delay_hint pref. #define NS_EVENT_STARVATION_DELAY_HINT 2000 -#ifdef PR_LOGGING #ifdef DEBUG static PRLogModuleInfo* gDocShellLog; #endif static PRLogModuleInfo* gDocShellLeakLog; -#endif const char kBrandBundleURL[] = "chrome://branding/locale/brand.properties"; const char kAppstringsBundleURL[] = "chrome://global/locale/appstrings.properties"; @@ -712,7 +710,8 @@ SendPing(void* aClosure, nsIContent* aContent, nsIURI* aURI, nsPingListener* pingListener = new nsPingListener(info->requireSameHost, aContent, loadGroup); - nsCOMPtr interceptController = do_QueryInterface(info->docShell); + nsCOMPtr interceptController = + do_QueryInterface(info->docShell); pingListener->SetInterceptController(interceptController); nsCOMPtr listener(pingListener); @@ -845,10 +844,6 @@ DecreasePrivateDocShellCount() } } -//***************************************************************************** -//*** nsDocShell: Object Management -//***************************************************************************** - static uint64_t gDocshellIDCounter = 0; nsDocShell::nsDocShell() @@ -922,7 +917,6 @@ nsDocShell::nsDocShell() CallGetService(NS_URIFIXUP_CONTRACTID, &sURIFixup); } -#ifdef PR_LOGGING #ifdef DEBUG if (!gDocShellLog) { gDocShellLog = PR_NewLogModule("nsDocShell"); @@ -934,7 +928,6 @@ nsDocShell::nsDocShell() if (gDocShellLeakLog) { PR_LOG(gDocShellLeakLog, PR_LOG_DEBUG, ("DOCSHELL %p created\n", this)); } -#endif #ifdef DEBUG // We're counting the number of |nsDocShells| to help find leaks @@ -967,11 +960,9 @@ nsDocShell::~nsDocShell() NS_IF_RELEASE(sURIFixup); } -#ifdef PR_LOGGING if (gDocShellLeakLog) { PR_LOG(gDocShellLeakLog, PR_LOG_DEBUG, ("DOCSHELL %p destroyed\n", this)); } -#endif #ifdef DEBUG // We're counting the number of |nsDocShells| to help find leaks @@ -1035,10 +1026,6 @@ nsDocShell::DestroyChildren() nsDocLoader::DestroyChildren(); } -//***************************************************************************** -// nsDocShell::nsISupports -//***************************************************************************** - NS_IMPL_ADDREF_INHERITED(nsDocShell, nsDocLoader) NS_IMPL_RELEASE_INHERITED(nsDocShell, nsDocLoader) @@ -1066,9 +1053,6 @@ NS_INTERFACE_MAP_BEGIN(nsDocShell) NS_INTERFACE_MAP_ENTRY(nsINetworkInterceptController) NS_INTERFACE_MAP_END_INHERITING(nsDocLoader) -///***************************************************************************** -// nsDocShell::nsIInterfaceRequestor -//***************************************************************************** NS_IMETHODIMP nsDocShell::GetInterface(const nsIID& aIID, void** aSink) { @@ -1115,7 +1099,7 @@ nsDocShell::GetInterface(const nsIID& aIID, void** aSink) return NS_ERROR_NO_INTERFACE; } -#if defined(PR_LOGGING) && defined(DEBUG) +#if defined(DEBUG) PR_LOG(gDocShellLog, PR_LOG_DEBUG, ("nsDocShell[%p]: returning app cache container %p", this, domDoc.get())); @@ -1366,9 +1350,6 @@ nsDocShell::ConvertLoadTypeToDocShellLoadInfo(uint32_t aLoadType) return docShellLoadType; } -//***************************************************************************** -// nsDocShell::nsIDocShell -//***************************************************************************** NS_IMETHODIMP nsDocShell::LoadURI(nsIURI* aURI, nsIDocShellLoadInfo* aLoadInfo, @@ -1450,7 +1431,7 @@ nsDocShell::LoadURI(nsIURI* aURI, aLoadInfo->GetBaseURI(getter_AddRefs(baseURI)); } -#if defined(PR_LOGGING) && defined(DEBUG) +#if defined(DEBUG) if (PR_LOG_TEST(gDocShellLog, PR_LOG_DEBUG)) { nsAutoCString uristr; aURI->GetAsciiSpec(uristr); @@ -2025,7 +2006,6 @@ bool nsDocShell::SetCurrentURI(nsIURI* aURI, nsIRequest* aRequest, bool aFireOnLocationChange, uint32_t aLocationFlags) { -#ifdef PR_LOGGING if (gDocShellLeakLog && PR_LOG_TEST(gDocShellLeakLog, PR_LOG_DEBUG)) { nsAutoCString spec; if (aURI) { @@ -2033,7 +2013,6 @@ nsDocShell::SetCurrentURI(nsIURI* aURI, nsIRequest* aRequest, } PR_LogPrint("DOCSHELL %p SetCurrentURI %s\n", this, spec.get()); } -#endif // We don't want to send a location change when we're displaying an error // page, and we don't want to change our idea of "current URI" either @@ -2630,14 +2609,16 @@ nsDocShell::SetAllowContentRetargeting(bool aAllowContentRetargeting) } NS_IMETHODIMP -nsDocShell::GetAllowContentRetargetingOnChildren(bool* aAllowContentRetargetingOnChildren) +nsDocShell::GetAllowContentRetargetingOnChildren( + bool* aAllowContentRetargetingOnChildren) { *aAllowContentRetargetingOnChildren = mAllowContentRetargetingOnChildren; return NS_OK; } NS_IMETHODIMP -nsDocShell::SetAllowContentRetargetingOnChildren(bool aAllowContentRetargetingOnChildren) +nsDocShell::SetAllowContentRetargetingOnChildren( + bool aAllowContentRetargetingOnChildren) { mAllowContentRetargetingOnChildren = aAllowContentRetargetingOnChildren; return NS_OK; @@ -3527,7 +3508,8 @@ nsDocShell::SetDocLoaderParent(nsDocLoader* aParent) if (NS_SUCCEEDED(parentAsDocShell->GetAllowWindowControl(&value))) { SetAllowWindowControl(value); } - SetAllowContentRetargeting(parentAsDocShell->GetAllowContentRetargetingOnChildren()); + SetAllowContentRetargeting( + parentAsDocShell->GetAllowContentRetargetingOnChildren()); if (NS_SUCCEEDED(parentAsDocShell->GetIsActive(&value))) { SetIsActive(value); } @@ -5336,7 +5318,7 @@ nsDocShell::LoadErrorPage(nsIURI* aURI, const char16_t* aURL, const char* aCSSClass, nsIChannel* aFailedChannel) { -#if defined(PR_LOGGING) && defined(DEBUG) +#if defined(DEBUG) if (PR_LOG_TEST(gDocShellLog, PR_LOG_DEBUG)) { nsAutoCString spec; aURI->GetSpec(spec); @@ -5664,6 +5646,7 @@ nsDocShell::GetSessionHistory(nsISHistory** aSessionHistory) //***************************************************************************** // nsDocShell::nsIWebPageDescriptor //***************************************************************************** + NS_IMETHODIMP nsDocShell::LoadPage(nsISupports* aPageDescriptor, uint32_t aDisplayType) { @@ -6749,11 +6732,7 @@ nsDocShell::DoAppRedirectIfNeeded(nsIURI* aURI, nsIDocShellLoadInfo* aLoadInfo, bool aFirstParty) { - uint32_t appId; - nsresult rv = GetAppId(&appId); - if (NS_FAILED(rv)) { - return false; - } + uint32_t appId = nsIDocShell::GetAppId(); if (appId != nsIScriptSecurityManager::NO_APP_ID && appId != nsIScriptSecurityManager::UNKNOWN_APP_ID) { @@ -6761,7 +6740,7 @@ nsDocShell::DoAppRedirectIfNeeded(nsIURI* aURI, do_GetService(APPS_SERVICE_CONTRACTID); NS_ASSERTION(appsService, "No AppsService available"); nsCOMPtr redirect; - rv = appsService->GetRedirect(appId, aURI, getter_AddRefs(redirect)); + nsresult rv = appsService->GetRedirect(appId, aURI, getter_AddRefs(redirect)); if (NS_SUCCEEDED(rv) && redirect) { rv = LoadURI(redirect, aLoadInfo, nsIWebNavigation::LOAD_FLAGS_NONE, aFirstParty); @@ -7243,7 +7222,7 @@ nsDocShell::RefreshURIFromQueue() timer->InitWithCallback(refreshInfo, delay, nsITimer::TYPE_ONE_SHOT); } } - } // while + } return NS_OK; } @@ -7890,19 +7869,18 @@ nsDocShell::EndPageLoad(nsIWebProgress* aProgress, aStatus == NS_ERROR_PROXY_CONNECTION_REFUSED) && (isTopFrame || UseErrorPages())) { DisplayLoadError(aStatus, url, nullptr, aChannel); - } - else if (aStatus == NS_ERROR_NET_TIMEOUT || - aStatus == NS_ERROR_REDIRECT_LOOP || - aStatus == NS_ERROR_UNKNOWN_SOCKET_TYPE || - aStatus == NS_ERROR_NET_INTERRUPT || - aStatus == NS_ERROR_NET_RESET || - aStatus == NS_ERROR_OFFLINE || - aStatus == NS_ERROR_MALWARE_URI || - aStatus == NS_ERROR_PHISHING_URI || - aStatus == NS_ERROR_UNSAFE_CONTENT_TYPE || - aStatus == NS_ERROR_REMOTE_XUL || - aStatus == NS_ERROR_OFFLINE || - NS_ERROR_GET_MODULE(aStatus) == NS_ERROR_MODULE_SECURITY) { + } else if (aStatus == NS_ERROR_NET_TIMEOUT || + aStatus == NS_ERROR_REDIRECT_LOOP || + aStatus == NS_ERROR_UNKNOWN_SOCKET_TYPE || + aStatus == NS_ERROR_NET_INTERRUPT || + aStatus == NS_ERROR_NET_RESET || + aStatus == NS_ERROR_OFFLINE || + aStatus == NS_ERROR_MALWARE_URI || + aStatus == NS_ERROR_PHISHING_URI || + aStatus == NS_ERROR_UNSAFE_CONTENT_TYPE || + aStatus == NS_ERROR_REMOTE_XUL || + aStatus == NS_ERROR_OFFLINE || + NS_ERROR_GET_MODULE(aStatus) == NS_ERROR_MODULE_SECURITY) { // Errors to be shown for any frame DisplayLoadError(aStatus, url, nullptr, aChannel); } else if (aStatus == NS_ERROR_DOCUMENT_NOT_CACHED) { @@ -7914,8 +7892,7 @@ nsDocShell::EndPageLoad(nsIWebProgress* aProgress, } DisplayLoadError(aStatus, url, nullptr, aChannel); } - } - else if (url && NS_SUCCEEDED(aStatus)) { + } else if (url && NS_SUCCEEDED(aStatus)) { // If we have a host mozilla::net::PredictorLearnRedirect(url, aChannel, this); } @@ -8069,9 +8046,9 @@ nsDocShell::CreateAboutBlankContentViewer(nsIPrincipal* aPrincipal, blankDoc->SetSandboxFlags(mSandboxFlags); // create a content viewer for us and the new document - docFactory->CreateInstanceForDocument(NS_ISUPPORTS_CAST(nsIDocShell*, this), - blankDoc, "view", - getter_AddRefs(viewer)); + docFactory->CreateInstanceForDocument( + NS_ISUPPORTS_CAST(nsIDocShell*, this), blankDoc, "view", + getter_AddRefs(viewer)); // hook 'em up if (viewer) { @@ -8473,8 +8450,8 @@ class MOZ_STACK_CLASS PresentationEventForgetter { public: explicit PresentationEventForgetter( - nsRevocableEventPtr& - aRestorePresentationEvent) + nsRevocableEventPtr& + aRestorePresentationEvent) : mRestorePresentationEvent(aRestorePresentationEvent) , mEvent(aRestorePresentationEvent.get()) { @@ -8854,7 +8831,8 @@ nsDocShell::RestoreFromHistory() childShell->GetAllowDNSPrefetch(&allowDNSPrefetch); bool allowContentRetargeting = childShell->GetAllowContentRetargeting(); - bool allowContentRetargetingOnChildren = childShell->GetAllowContentRetargetingOnChildren(); + bool allowContentRetargetingOnChildren = + childShell->GetAllowContentRetargetingOnChildren(); uint32_t defaultLoadFlags; childShell->GetDefaultLoadFlags(&defaultLoadFlags); @@ -8873,7 +8851,8 @@ nsDocShell::RestoreFromHistory() childShell->SetAllowMedia(allowMedia); childShell->SetAllowDNSPrefetch(allowDNSPrefetch); childShell->SetAllowContentRetargeting(allowContentRetargeting); - childShell->SetAllowContentRetargetingOnChildren(allowContentRetargetingOnChildren); + childShell->SetAllowContentRetargetingOnChildren( + allowContentRetargetingOnChildren); childShell->SetDefaultLoadFlags(defaultLoadFlags); rv = childShell->BeginRestore(nullptr, false); @@ -9156,8 +9135,9 @@ nsDocShell::CreateContentViewer(const nsACString& aContentType, aOpenedChannel->SetLoadFlags(loadFlags); mLoadGroup->AddRequest(aRequest, nullptr); - if (currentLoadGroup) + if (currentLoadGroup) { currentLoadGroup->RemoveRequest(aRequest, nullptr, NS_BINDING_RETARGETED); + } // Update the notification callbacks, so that progress and // status information are sent to the right docshell... @@ -9476,6 +9456,7 @@ nsDocShell::CheckLoadingPermissions() //***************************************************************************** // nsDocShell: Site Loading //***************************************************************************** + namespace { #ifdef MOZ_PLACES @@ -9591,7 +9572,8 @@ public: } } - NS_IMETHOD Run() + NS_IMETHOD + Run() { return mDocShell->InternalLoad2(mURI, mOriginalURI, mLoadReplace, @@ -9721,7 +9703,6 @@ nsDocShell::InternalLoad2(nsIURI* aURI, nsresult rv = NS_OK; mOriginalUriString.Truncate(); -#ifdef PR_LOGGING if (gDocShellLeakLog && PR_LOG_TEST(gDocShellLeakLog, PR_LOG_DEBUG)) { nsAutoCString spec; if (aURI) { @@ -9729,7 +9710,6 @@ nsDocShell::InternalLoad2(nsIURI* aURI, } PR_LogPrint("DOCSHELL %p InternalLoad %s\n", this, spec.get()); } -#endif // Initialize aDocShell/aRequest if (aDocShell) { *aDocShell = nullptr; @@ -10905,7 +10885,7 @@ nsDocShell::DoURILoad(nsIURI* aURI, // (ie. POST data, referrer, ...) // if (httpChannel) { - nsCOMPtr cacheChannel(do_QueryInterface(httpChannel)); + nsCOMPtr cacheChannel(do_QueryInterface(httpChannel)); /* Get the cache Key from SH */ nsCOMPtr cacheKey; if (mLSHE) { @@ -11328,7 +11308,7 @@ nsDocShell::OnNewURI(nsIURI* aURI, nsIChannel* aChannel, nsISupports* aOwner, NS_PRECONDITION(aURI, "uri is null"); NS_PRECONDITION(!aChannel || !aOwner, "Shouldn't have both set"); -#if defined(PR_LOGGING) && defined(DEBUG) +#if defined(DEBUG) if (PR_LOG_TEST(gDocShellLog, PR_LOG_DEBUG)) { nsAutoCString spec; aURI->GetSpec(spec); @@ -11392,7 +11372,7 @@ nsDocShell::OnNewURI(nsIURI* aURI, nsIChannel* aChannel, nsISupports* aOwner, updateSHistory = false; updateGHistory = false; // XXX Why global history too? } - } // rootSH + } // Check if the url to be loaded is the same as the one already loaded. if (mCurrentURI) { @@ -11461,7 +11441,7 @@ nsDocShell::OnNewURI(nsIURI* aURI, nsIChannel* aChannel, nsISupports* aOwner, "We shouldn't be updating session history for forced" " reloads!"); - nsCOMPtr cacheChannel(do_QueryInterface(aChannel)); + nsCOMPtr cacheChannel(do_QueryInterface(aChannel)); nsCOMPtr cacheKey; // Get the Cache Key and store it in SH. if (cacheChannel) { @@ -11968,7 +11948,7 @@ nsDocShell::AddToSessionHistory(nsIURI* aURI, nsIChannel* aChannel, NS_PRECONDITION(aURI, "uri is null"); NS_PRECONDITION(!aChannel || !aOwner, "Shouldn't have both set"); -#if defined(PR_LOGGING) && defined(DEBUG) +#if defined(DEBUG) if (PR_LOG_TEST(gDocShellLog, PR_LOG_DEBUG)) { nsAutoCString spec; aURI->GetSpec(spec); @@ -12013,9 +11993,9 @@ nsDocShell::AddToSessionHistory(nsIURI* aURI, nsIChannel* aChannel, nsCOMPtr child; shContainer->GetChildAt(i, getter_AddRefs(child)); shContainer->RemoveChild(child); - } // for + } entry->AbandonBFCacheEntry(); - } // shContainer + } } // Create a new entry if necessary. @@ -12037,7 +12017,7 @@ nsDocShell::AddToSessionHistory(nsIURI* aURI, nsIChannel* aChannel, nsCOMPtr owner = aOwner; bool expired = false; bool discardLayoutState = false; - nsCOMPtr cacheChannel; + nsCOMPtr cacheChannel; if (aChannel) { cacheChannel = do_QueryInterface(aChannel); @@ -12381,7 +12361,8 @@ nsDocShell::WalkHistoryEntries(nsISHEntry* aRootEntry, if (aRootShell) { // Walk the children of aRootShell and see if one of them // has srcChild as a SHEntry. - nsTObserverArray::ForwardIterator iter(aRootShell->mChildList); + nsTObserverArray::ForwardIterator iter( + aRootShell->mChildList); while (iter.HasMore()) { nsDocShell* child = static_cast(iter.GetNext()); @@ -13154,10 +13135,6 @@ nsDocShell::SetLayoutHistoryState(nsILayoutHistoryState* aLayoutHistoryState) return NS_OK; } -//***************************************************************************** -//*** nsRefreshTimer: Object Management -//***************************************************************************** - nsRefreshTimer::nsRefreshTimer() : mDelay(0), mRepeat(false), mMetaRefresh(false) { @@ -13167,10 +13144,6 @@ nsRefreshTimer::~nsRefreshTimer() { } -//***************************************************************************** -// nsRefreshTimer::nsISupports -//***************************************************************************** - NS_IMPL_ADDREF(nsRefreshTimer) NS_IMPL_RELEASE(nsRefreshTimer) @@ -13179,9 +13152,6 @@ NS_INTERFACE_MAP_BEGIN(nsRefreshTimer) NS_INTERFACE_MAP_ENTRY(nsITimerCallback) NS_INTERFACE_MAP_END_THREADSAFE -///***************************************************************************** -// nsRefreshTimer::nsITimerCallback -//****************************************************************************** NS_IMETHODIMP nsRefreshTimer::Notify(nsITimer* aTimer) { @@ -13196,9 +13166,6 @@ nsRefreshTimer::Notify(nsITimer* aTimer) return NS_OK; } -//***************************************************************************** -// nsDocShell::InterfaceRequestorProxy -//***************************************************************************** nsDocShell::InterfaceRequestorProxy::InterfaceRequestorProxy( nsIInterfaceRequestor* aRequestor) { @@ -13237,8 +13204,9 @@ nsDocShell::SetBaseUrlForWyciwyg(nsIContentViewer* aContentViewer) nsCOMPtr baseURI; nsresult rv = NS_ERROR_NOT_AVAILABLE; - if (sURIFixup) + if (sURIFixup) { rv = sURIFixup->CreateExposableURI(mCurrentURI, getter_AddRefs(baseURI)); + } // Get the current document and set the base uri if (baseURI) { @@ -13284,6 +13252,7 @@ nsDocShell::GetAuthPrompt(uint32_t aPromptReason, const nsIID& aIID, //***************************************************************************** // nsDocShell::nsILoadContext //***************************************************************************** + NS_IMETHODIMP nsDocShell::GetAssociatedWindow(nsIDOMWindow** aWindow) { @@ -13533,8 +13502,6 @@ nsDocShell::SelectNone(void) return DoCommand("cmd_selectNone"); } -//---------------------------------------------------------------------- - // link handling class OnLinkClickEvent : public nsRunnable @@ -13594,8 +13561,6 @@ OnLinkClickEvent::OnLinkClickEvent(nsDocShell* aHandler, { } -//---------------------------------------- - NS_IMETHODIMP nsDocShell::OnLinkClick(nsIContent* aContent, nsIURI* aURI, @@ -14082,9 +14047,7 @@ nsDocShell::GetAppId(uint32_t* aAppId) NS_IMETHODIMP nsDocShell::GetAppManifestURL(nsAString& aAppManifestURL) { - uint32_t appId; - GetAppId(&appId); - + uint32_t appId = nsIDocShell::GetAppId(); if (appId != nsIScriptSecurityManager::NO_APP_ID && appId != nsIScriptSecurityManager::UNKNOWN_APP_ID) { nsCOMPtr appsService = @@ -14154,7 +14117,6 @@ nsDocShell::GetURLSearchParams() class JavascriptTimelineMarker : public TimelineMarker { public: - JavascriptTimelineMarker(nsDocShell* aDocShell, const char* aName, const char* aReason) : TimelineMarker(aDocShell, aName, TRACING_INTERVAL_START, @@ -14169,7 +14131,7 @@ public: }; void -nsDocShell::NotifyJSRunToCompletionStart(const char *aReason) +nsDocShell::NotifyJSRunToCompletionStart(const char* aReason) { bool timelineOn = nsIDocShell::GetRecordProfileTimelineMarkers(); @@ -14229,7 +14191,8 @@ nsDocShell::MaybeNotifyKeywordSearchLoading(const nsString& aProvider, } NS_IMETHODIMP -nsDocShell::ShouldPrepareForIntercept(nsIURI* aURI, bool aIsNavigate, bool* aShouldIntercept) +nsDocShell::ShouldPrepareForIntercept(nsIURI* aURI, bool aIsNavigate, + bool* aShouldIntercept) { *aShouldIntercept = false; if (mSandboxFlags) { @@ -14237,7 +14200,7 @@ nsDocShell::ShouldPrepareForIntercept(nsIURI* aURI, bool aIsNavigate, bool* aSho return NS_OK; } - nsCOMPtr swm = mozilla::services::GetServiceWorkerManager(); + nsCOMPtr swm = services::GetServiceWorkerManager(); if (!swm) { return NS_OK; } @@ -14257,7 +14220,7 @@ nsDocShell::ShouldPrepareForIntercept(nsIURI* aURI, bool aIsNavigate, bool* aSho NS_IMETHODIMP nsDocShell::ChannelIntercepted(nsIInterceptedChannel* aChannel) { - nsCOMPtr swm = mozilla::services::GetServiceWorkerManager(); + nsCOMPtr swm = services::GetServiceWorkerManager(); if (!swm) { aChannel->Cancel(); return NS_OK; diff --git a/docshell/base/nsDocShell.h b/docshell/base/nsDocShell.h index f1c8c27793..935f61d86a 100644 --- a/docshell/base/nsDocShell.h +++ b/docshell/base/nsDocShell.h @@ -89,9 +89,6 @@ class nsIURILoader; class nsIWebBrowserFind; class nsIWidget; -/* load commands were moved to nsIDocShell.h */ -/* load types were moved to nsDocShellLoadTypes.h */ - /* internally used ViewMode types */ enum ViewMode { @@ -99,10 +96,6 @@ enum ViewMode viewSource = 0x1 }; -//***************************************************************************** -//*** nsRefreshTimer -//***************************************************************************** - class nsRefreshTimer : public nsITimerCallback { public: @@ -131,10 +124,6 @@ enum eCharsetReloadState eCharsetReloadStopOrigional }; -//***************************************************************************** -//*** nsDocShell -//***************************************************************************** - class nsDocShell final : public nsDocLoader , public nsIDocShell_ESR38_2 @@ -160,7 +149,7 @@ class nsDocShell final public: MOZ_DECLARE_WEAKREFERENCE_TYPENAME(nsDocShell) - // Object Management + nsDocShell(); NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW @@ -189,7 +178,8 @@ public: NS_DECL_NSINETWORKINTERCEPTCONTROLLER NS_FORWARD_SAFE_NSIDOMSTORAGEMANAGER(TopSessionStorageManager()) - NS_IMETHOD Stop() override { + NS_IMETHOD Stop() override + { // Need this here because otherwise nsIWebNavigation::Stop // overrides the docloader's Stop() return nsDocLoader::Stop(); @@ -222,7 +212,7 @@ public: nsDocShellInfoLoadType ConvertLoadTypeToDocShellLoadInfo(uint32_t aLoadType); uint32_t ConvertDocShellLoadInfoToLoadType( - nsDocShellInfoLoadType aDocShellLoadType); + nsDocShellInfoLoadType aDocShellLoadType); // Don't use NS_DECL_NSILOADCONTEXT because some of nsILoadContext's methods // are shared with nsIDocShell (appID, etc.) and can't be declared twice. @@ -240,10 +230,10 @@ public: // Restores a cached presentation from history (mLSHE). // This method swaps out the content viewer and simulates loads for - // subframes. It then simulates the completion of the toplevel load. + // subframes. It then simulates the completion of the toplevel load. nsresult RestoreFromHistory(); - // Perform a URI load from a refresh timer. This is just like the + // Perform a URI load from a refresh timer. This is just like the // ForceRefreshURI method on nsIRefreshURI, but makes sure to take // the timer involved out of mRefreshURIList if it's there. // aTimer must not be null. @@ -273,8 +263,7 @@ public: // Add new profile timeline markers to this docShell. This will only add // markers if the docShell is currently recording profile timeline markers. // See nsIDocShell::recordProfileTimelineMarkers - void AddProfileTimelineMarker(const char* aName, - TracingMetadata aMetaData); + void AddProfileTimelineMarker(const char* aName, TracingMetadata aMetaData); void AddProfileTimelineMarker(mozilla::UniquePtr&& aMarker); // Global counter for how many docShells are currently recording profile @@ -287,13 +276,12 @@ public: bool aInPrivateBrowsing); protected: - // Object Management virtual ~nsDocShell(); virtual void DestroyChildren() override; // Content Viewer Management nsresult EnsureContentViewer(); - // aPrincipal can be passed in if the caller wants. If null is + // aPrincipal can be passed in if the caller wants. If null is // passed in, the about:blank principal will end up being used. nsresult CreateAboutBlankContentViewer(nsIPrincipal* aPrincipal, nsIURI* aBaseURI, @@ -311,16 +299,16 @@ protected: nsresult GetEldestPresContext(nsPresContext** aPresContext); - // Get the principal that we'll set on the channel if we're inheriting. If + // Get the principal that we'll set on the channel if we're inheriting. If // aConsiderCurrentDocument is true, we try to use the current document if - // at all possible. If that fails, we fall back on the parent document. + // at all possible. If that fails, we fall back on the parent document. // If that fails too, we force creation of a content viewer and use the - // resulting principal. If aConsiderCurrentDocument is false, we just look + // resulting principal. If aConsiderCurrentDocument is false, we just look // at the parent. nsIPrincipal* GetInheritedPrincipal(bool aConsiderCurrentDocument); - // Actually open a channel and perform a URI load. Note: whatever owner is - // passed to this function will be set on the channel. Callers who wish to + // Actually open a channel and perform a URI load. Note: whatever owner is + // passed to this function will be set on the channel. Callers who wish to // not have an owner on the channel should just pass null. // If aSrcdoc is not void, the load will be considered as a srcdoc load, // and the contents of aSrcdoc will be loaded instead of aURI. @@ -371,7 +359,7 @@ protected: // In this case it is the caller's responsibility to ensure // FireOnLocationChange is called. // In all other cases false is returned. - // Either aChannel or aOwner must be null. If aChannel is + // Either aChannel or aOwner must be null. If aChannel is // present, the owner should be gotten from it. // If OnNewURI calls AddToSessionHistory, it will pass its // aCloneSHChildren argument as aCloneChildren. @@ -386,10 +374,10 @@ protected: // Session History bool ShouldAddToSessionHistory(nsIURI* aURI); - // Either aChannel or aOwner must be null. If aChannel is + // Either aChannel or aOwner must be null. If aChannel is // present, the owner should be gotten from it. // If aCloneChildren is true, then our current session history's - // children will be cloned onto the new entry. This should be + // children will be cloned onto the new entry. This should be // used when we aren't actually changing the document while adding // the new session history entry. nsresult AddToSessionHistory(nsIURI* aURI, nsIChannel* aChannel, @@ -409,7 +397,7 @@ protected: // Clone a session history tree for subframe navigation. // The tree rooted at |aSrcEntry| will be cloned into |aDestEntry|, except // for the entry with id |aCloneID|, which will be replaced with - // |aReplaceEntry|. |aSrcShell| is a (possibly null) docshell which + // |aReplaceEntry|. |aSrcShell| is a (possibly null) docshell which // corresponds to |aSrcEntry| via its mLSHE or mOHE pointers, and will // have that pointer updated to point to the cloned history entry. // If aCloneChildren is true then the children of the entry with id @@ -440,7 +428,7 @@ protected: void SwapHistoryEntries(nsISHEntry* aOldEntry, nsISHEntry* aNewEntry); // Call this method to swap in a new history entry to m[OL]SHE, rather than - // setting it directly. This completes the navigation in all docshells + // setting it directly. This completes the navigation in all docshells // in the case of a subframe navigation. void SetHistoryEntry(nsCOMPtr* aPtr, nsISHEntry* aEntry); @@ -458,7 +446,7 @@ protected: void* aData); // For each child of aRootEntry, find the corresponding docshell which is - // a child of aRootShell, and call aCallback. The opaque pointer aData + // a child of aRootShell, and call aCallback. The opaque pointer aData // is passed to the callback. static nsresult WalkHistoryEntries(nsISHEntry* aRootEntry, nsDocShell* aRootShell, @@ -487,7 +475,7 @@ protected: * channel. * * This method first checks the channel's property bag to see if previous - * info has been saved. If not, it gives back the referrer of the channel. + * info has been saved. If not, it gives back the referrer of the channel. * * @param aChannel * The channel we are transitioning to @@ -516,7 +504,7 @@ protected: uint32_t aChannelRedirectFlags); /** - * Helper function for adding a URI visit using IHistory. If IHistory is + * Helper function for adding a URI visit using IHistory. If IHistory is * not available, the method tries nsIGlobalHistory2. * * The IHistory API maintains chains of visits, tracking both HTTP referrers @@ -524,7 +512,7 @@ protected: * the previous URI in the chain. * * Visits can be saved either during a redirect or when the request has - * reached its final destination. The previous URI in the visit may be + * reached its final destination. The previous URI in the visit may be * from another redirect or it may be the referrer. * * @pre aURI is not null. @@ -593,13 +581,13 @@ protected: nsresult aResult); // Sets the current document's current state object to the given SHEntry's - // state object. The current state object is eventually given to the page + // state object. The current state object is eventually given to the page // in the PopState event. nsresult SetDocCurrentStateObj(nsISHEntry* aShEntry); nsresult CheckLoadingPermissions(); - // Security checks to prevent frameset spoofing. See comments at + // Security checks to prevent frameset spoofing. See comments at // implementation sites. static bool CanAccessItem(nsIDocShellTreeItem* aTargetItem, nsIDocShellTreeItem* aAccessingItem, @@ -620,33 +608,33 @@ protected: // in session history. // mContentViewer points to the current content viewer associated with - // this docshell. When loading a new document, the content viewer is - // either destroyed or stored into a session history entry. To make sure + // this docshell. When loading a new document, the content viewer is + // either destroyed or stored into a session history entry. To make sure // that destruction happens in a controlled fashion, a given content viewer // is always owned in exactly one of these ways: // 1) The content viewer is active and owned by a docshell's // mContentViewer. // 2) The content viewer is still being displayed while we begin loading - // a new document. The content viewer is owned by the _new_ + // a new document. The content viewer is owned by the _new_ // content viewer's mPreviousViewer, and has a pointer to the - // nsISHEntry where it will eventually be stored. The content viewer + // nsISHEntry where it will eventually be stored. The content viewer // has been close()d by the docshell, which detaches the document from // the window object. - // 3) The content viewer is cached in session history. The nsISHEntry - // has the only owning reference to the content viewer. The viewer + // 3) The content viewer is cached in session history. The nsISHEntry + // has the only owning reference to the content viewer. The viewer // has released its nsISHEntry pointer to prevent circular ownership. // // When restoring a content viewer from session history, open() is called - // to reattach the document to the window object. The content viewer is + // to reattach the document to the window object. The content viewer is // then placed into mContentViewer and removed from the history entry. // (mContentViewer is put into session history as described above, if // applicable). // Determines whether we can safely cache the current mContentViewer in - // session history. This checks a number of factors such as cache policy, + // session history. This checks a number of factors such as cache policy, // pending requests, and unload handlers. // |aLoadType| should be the load type that will replace the current - // presentation. |aNewRequest| should be the request for the document to + // presentation. |aNewRequest| should be the request for the document to // be loaded in place of the current document, or null if such a request // has not been created yet. |aNewDocument| should be the document that will // replace the current document. @@ -672,7 +660,7 @@ protected: int32_t* aHeight); // Call this when a URI load is handed to us (via OnLinkClick or - // InternalLoad). This makes sure that we're not inside unload, or that if + // InternalLoad). This makes sure that we're not inside unload, or that if // we are it's still OK to load this URI. bool IsOKToLoadURI(nsIURI* aURI); @@ -690,7 +678,7 @@ protected: bool ShouldBlockLoadingForBackButton(); - // Convenience method for getting our parent docshell. Can return null + // Convenience method for getting our parent docshell. Can return null already_AddRefed GetParentDocshell(); // Check if we have an app redirect registered for the URI and redirect if @@ -798,7 +786,7 @@ protected: nsCOMPtr mLSHE; // Holds a weak pointer to a RestorePresentationEvent object if any that - // holds a weak pointer back to us. We use this pointer to possibly revoke + // holds a weak pointer back to us. We use this pointer to possibly revoke // the event whenever necessary. nsRevocableEventPtr mRestorePresentationEvent; @@ -811,9 +799,9 @@ protected: // Secure browser UI object nsCOMPtr mSecurityUI; - // The URI we're currently loading. This is only relevant during the - // firing of a pagehide/unload. The caller of FirePageHideNotification() - // is responsible for setting it and unsetting it. It may be null if the + // The URI we're currently loading. This is only relevant during the + // firing of a pagehide/unload. The caller of FirePageHideNotification() + // is responsible for setting it and unsetting it. It may be null if the // pagehide/unload is happening for some reason other than just loading a // new URI. nsCOMPtr mLoadingURI; @@ -834,11 +822,11 @@ protected: nsCOMPtr mMixedContentChannel; // WEAK REFERENCES BELOW HERE. - // Note these are intentionally not addrefd. Doing so will create a cycle. + // Note these are intentionally not addrefd. Doing so will create a cycle. // For that reasons don't use nsCOMPtr. nsIDocShellTreeOwner* mTreeOwner; // Weak Reference - mozilla::dom::EventTarget* mChromeEventHandler; //Weak Reference + mozilla::dom::EventTarget* mChromeEventHandler; // Weak Reference eCharsetReloadState mCharsetReloadState; @@ -852,7 +840,7 @@ protected: int32_t mMarginWidth; int32_t mMarginHeight; - // This can either be a content docshell or a chrome docshell. After + // This can either be a content docshell or a chrome docshell. After // Create() is called, the type is not expected to change. int32_t mItemType; @@ -920,7 +908,7 @@ protected: void RecomputeCanExecuteScripts(); // This boolean is set to true right before we fire pagehide and generally - // unset when we embed a new content viewer. While it's true no navigation + // unset when we embed a new content viewer. While it's true no navigation // is allowed in this docshell. bool mFiredUnloadEvent; @@ -967,7 +955,7 @@ protected: FrameType mFrameType; // We only expect mOwnOrContainingAppId to be something other than - // UNKNOWN_APP_ID if mFrameType != eFrameTypeRegular. For vanilla iframes + // UNKNOWN_APP_ID if mFrameType != eFrameTypeRegular. For vanilla iframes // inside an app, we'll retrieve the containing app-id by walking up the // docshell hierarchy. // diff --git a/docshell/base/nsDocShellEditorData.h b/docshell/base/nsDocShellEditorData.h index 53036b98e6..272190503c 100644 --- a/docshell/base/nsDocShellEditorData.h +++ b/docshell/base/nsDocShellEditorData.h @@ -58,7 +58,6 @@ protected: // Backup for the corresponding nsIHTMLDocument's editing state while // the editor is detached. nsIHTMLDocument::EditingState mDetachedEditingState; - }; #endif // nsDocShellEditorData_h__ diff --git a/docshell/base/nsDocShellEnumerator.h b/docshell/base/nsDocShellEnumerator.h index a299aa0f35..87de74f0f7 100644 --- a/docshell/base/nsDocShellEnumerator.h +++ b/docshell/base/nsDocShellEnumerator.h @@ -89,7 +89,6 @@ public: protected: virtual nsresult BuildArrayRecursive(nsIDocShellTreeItem* aItem, nsTArray& aItemArray); - }; class nsDocShellBackwardsEnumerator : public nsDocShellEnumerator diff --git a/docshell/base/nsDocShellLoadInfo.cpp b/docshell/base/nsDocShellLoadInfo.cpp index 84c294b3ed..1593e43b64 100644 --- a/docshell/base/nsDocShellLoadInfo.cpp +++ b/docshell/base/nsDocShellLoadInfo.cpp @@ -4,7 +4,6 @@ * 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/. */ -// Local Includes #include "nsDocShellLoadInfo.h" #include "nsISHEntry.h" #include "nsIInputStream.h" @@ -12,10 +11,6 @@ #include "nsIDocShell.h" #include "mozilla/net/ReferrerPolicy.h" -//***************************************************************************** -//*** nsDocShellLoadInfo: Object Management -//***************************************************************************** - nsDocShellLoadInfo::nsDocShellLoadInfo() : mInheritOwner(false) , mOwnerIsExplicit(false) @@ -31,10 +26,6 @@ nsDocShellLoadInfo::~nsDocShellLoadInfo() { } -//***************************************************************************** -// nsDocShellLoadInfo::nsISupports -//***************************************************************************** - NS_IMPL_ADDREF(nsDocShellLoadInfo) NS_IMPL_RELEASE(nsDocShellLoadInfo) @@ -44,10 +35,6 @@ NS_INTERFACE_MAP_BEGIN(nsDocShellLoadInfo) NS_INTERFACE_MAP_ENTRY(nsIDocShellLoadInfo) NS_INTERFACE_MAP_END -//***************************************************************************** -// nsDocShellLoadInfo::nsIDocShellLoadInfo -//***************************************************************************** - NS_IMETHODIMP nsDocShellLoadInfo::GetReferrer(nsIURI** aReferrer) { diff --git a/docshell/base/nsDocShellLoadTypes.h b/docshell/base/nsDocShellLoadTypes.h index 518df7d101..273dd87b0d 100644 --- a/docshell/base/nsDocShellLoadTypes.h +++ b/docshell/base/nsDocShellLoadTypes.h @@ -27,8 +27,8 @@ * above 0xffff (e.g. LOAD_FLAGS_BYPASS_CLASSIFIER), since MAKE_LOAD_TYPE would * just shift them out anyway. */ -#define EXTRA_LOAD_FLAGS (LOAD_FLAGS_FIRST_LOAD | \ - LOAD_FLAGS_ALLOW_POPUPS | \ +#define EXTRA_LOAD_FLAGS (LOAD_FLAGS_FIRST_LOAD | \ + LOAD_FLAGS_ALLOW_POPUPS | \ 0xffff0000) /* load types are legal combinations of load commands and flags @@ -65,7 +65,8 @@ enum LoadType * Docshell. Instead, Docshell triggers the load itself when a * consumer-triggered load failed. */ - LOAD_ERROR_PAGE = MAKE_LOAD_TYPE(nsIDocShell::LOAD_CMD_NORMAL, LOAD_FLAGS_ERROR_PAGE) + LOAD_ERROR_PAGE = MAKE_LOAD_TYPE(nsIDocShell::LOAD_CMD_NORMAL, + LOAD_FLAGS_ERROR_PAGE) // NOTE: Adding a new value? Remember to update IsValidLoadType! }; diff --git a/docshell/base/nsDocShellTransferableHooks.cpp b/docshell/base/nsDocShellTransferableHooks.cpp index 890bd05f6c..441ade1287 100644 --- a/docshell/base/nsDocShellTransferableHooks.cpp +++ b/docshell/base/nsDocShellTransferableHooks.cpp @@ -17,10 +17,6 @@ nsTransferableHookData::~nsTransferableHookData() { } -//***************************************************************************** -// nsIClipboardDragDropHookList -//***************************************************************************** - NS_IMPL_ISUPPORTS(nsTransferableHookData, nsIClipboardDragDropHookList) NS_IMETHODIMP diff --git a/docshell/base/nsDownloadHistory.cpp b/docshell/base/nsDownloadHistory.cpp index 4600560090..32513ef002 100644 --- a/docshell/base/nsDownloadHistory.cpp +++ b/docshell/base/nsDownloadHistory.cpp @@ -12,14 +12,8 @@ #include "nsIURI.h" #include "mozilla/Services.h" -//////////////////////////////////////////////////////////////////////////////// -//// nsDownloadHistory - NS_IMPL_ISUPPORTS(nsDownloadHistory, nsIDownloadHistory) -//////////////////////////////////////////////////////////////////////////////// -//// nsIDownloadHistory - NS_IMETHODIMP nsDownloadHistory::AddDownload(nsIURI* aSource, nsIURI* aReferrer, @@ -42,8 +36,7 @@ nsDownloadHistory::AddDownload(nsIURI* aSource, NS_ENSURE_SUCCESS(rv, rv); if (!visited) { - nsCOMPtr os = - mozilla::services::GetObserverService(); + nsCOMPtr os = mozilla::services::GetObserverService(); if (os) { os->NotifyObservers(aSource, NS_LINK_VISITED_EVENT_TOPIC, nullptr); } diff --git a/docshell/base/nsILinkHandler.h b/docshell/base/nsILinkHandler.h index 797b3fe134..7cdcd566df 100644 --- a/docshell/base/nsILinkHandler.h +++ b/docshell/base/nsILinkHandler.h @@ -14,7 +14,6 @@ class nsIDocShell; class nsIInputStream; class nsIRequest; -// Interface ID for nsILinkHandler #define NS_ILINKHANDLER_IID \ { 0xceb9aade, 0x43da, 0x4f1a, \ { 0xac, 0x8a, 0xc7, 0x09, 0xfb, 0x22, 0x46, 0x64 } } diff --git a/docshell/base/nsIWebShellServices.h b/docshell/base/nsIWebShellServices.h index 2781da289a..c67de0ff72 100644 --- a/docshell/base/nsIWebShellServices.h +++ b/docshell/base/nsIWebShellServices.h @@ -9,20 +9,16 @@ #include "nsISupports.h" #include "nsCharsetSource.h" -// Interface ID for nsIWebShellServices - /* 0c628af0-5638-4703-8f99-ed6134c9de18 */ #define NS_IWEB_SHELL_SERVICES_IID \ { 0x0c628af0, 0x5638, 0x4703, {0x8f, 0x99, 0xed, 0x61, 0x34, 0xc9, 0xde, 0x18} } -//---------------------------------------------------------------------- - class nsIWebShellServices : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWEB_SHELL_SERVICES_IID) - NS_IMETHOD ReloadDocument(const char* aCharset = nullptr , + NS_IMETHOD ReloadDocument(const char* aCharset = nullptr, int32_t aSource = kCharsetUninitialized) = 0; NS_IMETHOD StopDocumentLoad(void) = 0; }; diff --git a/docshell/base/nsWebNavigationInfo.h b/docshell/base/nsWebNavigationInfo.h index 430fb95aa8..2b54156f7e 100644 --- a/docshell/base/nsWebNavigationInfo.h +++ b/docshell/base/nsWebNavigationInfo.h @@ -14,7 +14,6 @@ class nsCString; -// Class ID for webnavigationinfo #define NS_WEBNAVIGATION_INFO_CID \ { 0xf30bc0a2, 0x958b, 0x4287,{0xbf, 0x62, 0xce, 0x38, 0xba, 0x0c, 0x81, 0x1e}} diff --git a/docshell/build/nsDocShellCID.h b/docshell/build/nsDocShellCID.h index 6049688f4d..35432ee1b5 100644 --- a/docshell/build/nsDocShellCID.h +++ b/docshell/build/nsDocShellCID.h @@ -7,8 +7,7 @@ #ifndef nsDocShellCID_h__ #define nsDocShellCID_h__ -#define NS_GLOBALHISTORY2_CONTRACTID \ - "@mozilla.org/browser/global-history;2" +#define NS_GLOBALHISTORY2_CONTRACTID "@mozilla.org/browser/global-history;2" /** * A contract for a service that will track download history. This can be @@ -17,16 +16,14 @@ * * @implements nsIDownloadHistory */ -#define NS_DOWNLOADHISTORY_CONTRACTID \ - "@mozilla.org/browser/download-history;1" +#define NS_DOWNLOADHISTORY_CONTRACTID "@mozilla.org/browser/download-history;1" /** * A contract that can be used to get a service that provides * meta-information about nsIWebNavigation objects' capabilities. * @implements nsIWebNavigationInfo */ -#define NS_WEBNAVIGATION_INFO_CONTRACTID \ - "@mozilla.org/webnavigation-info;1" +#define NS_WEBNAVIGATION_INFO_CONTRACTID "@mozilla.org/webnavigation-info;1" /** * Class and contract ID for the docshell. This is the container for a web @@ -34,9 +31,9 @@ * exact ones keep changing; if they stabilize somewhat that will get * documented. */ -#define NS_DOCSHELL_CID \ - { 0xf1eac762, 0x87e9, 0x11d3, \ - { 0xaf, 0x80, 0x00, 0xa0, 0x24, 0xff, 0xc0, 0x8c } } +#define NS_DOCSHELL_CID \ + { 0xf1eac762, 0x87e9, 0x11d3, \ + { 0xaf, 0x80, 0x00, 0xa0, 0x24, 0xff, 0xc0, 0x8c } } #define NS_DOCSHELL_CONTRACTID "@mozilla.org/docshell/html;1" /** @@ -51,7 +48,8 @@ * * @implements nsIExternalURLHandlerService */ -#define NS_EXTERNALURLHANDLERSERVICE_CONTRACTID "@mozilla.org/uriloader/external-url-handler-service;1" +#define NS_EXTERNALURLHANDLERSERVICE_CONTRACTID \ + "@mozilla.org/uriloader/external-url-handler-service;1" /** * An observer service topic that can be listened to to catch creation diff --git a/docshell/build/nsDocShellModule.cpp b/docshell/build/nsDocShellModule.cpp index 8e4dcc9488..ec39cea2f6 100644 --- a/docshell/build/nsDocShellModule.cpp +++ b/docshell/build/nsDocShellModule.cpp @@ -23,7 +23,7 @@ #include "nsLocalHandlerApp.h" #ifdef MOZ_ENABLE_DBUS #include "nsDBusHandlerApp.h" -#endif +#endif #if defined(MOZ_WIDGET_ANDROID) #include "nsExternalSharingAppService.h" #include "nsExternalURLHandlerService.h" @@ -81,7 +81,7 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsOfflineCacheUpdate) NS_GENERIC_FACTORY_CONSTRUCTOR(PlatformLocalHandlerApp_t) #ifdef MOZ_ENABLE_DBUS NS_GENERIC_FACTORY_CONSTRUCTOR(nsDBusHandlerApp) -#endif +#endif #if defined(MOZ_WIDGET_ANDROID) NS_GENERIC_FACTORY_CONSTRUCTOR(nsExternalSharingAppService) NS_GENERIC_FACTORY_CONSTRUCTOR(nsExternalURLHandlerService) @@ -120,7 +120,6 @@ NS_DEFINE_NAMED_CID(NS_SHISTORY_CID); NS_DEFINE_NAMED_CID(NS_SHISTORY_INTERNAL_CID); NS_DEFINE_NAMED_CID(NS_DOWNLOADHISTORY_CID); - const mozilla::Module::CIDEntry kDocShellCIDs[] = { { &kNS_DOCSHELL_CID, false, nullptr, nsDocShellConstructor }, { &kNS_DEFAULTURIFIXUP_CID, false, nullptr, nsDefaultURIFixupConstructor }, diff --git a/docshell/shistory/src/nsSHEntry.cpp b/docshell/shistory/src/nsSHEntry.cpp index c6a8fbbc8f..3ed77b41f9 100644 --- a/docshell/shistory/src/nsSHEntry.cpp +++ b/docshell/shistory/src/nsSHEntry.cpp @@ -3,7 +3,6 @@ * 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/. */ -// Local Includes #include "nsSHEntry.h" #include "nsIDocShellLoadInfo.h" #include "nsIDocShellTreeItem.h" @@ -22,13 +21,9 @@ namespace dom = mozilla::dom; static uint32_t gEntryID = 0; -//***************************************************************************** -//*** nsSHEntry: Object Management -//***************************************************************************** - - nsSHEntry::nsSHEntry() - : mLoadReplace(false) + : mShared(new nsSHEntryShared()) + , mLoadReplace(false) , mReferrerPolicy(mozilla::net::RP_Default) , mLoadType(0) , mID(gEntryID++) @@ -38,28 +33,27 @@ nsSHEntry::nsSHEntry() , mURIWasModified(false) , mIsSrcdocEntry(false) { - mShared = new nsSHEntryShared(); } -nsSHEntry::nsSHEntry(const nsSHEntry &other) - : mShared(other.mShared) - , mURI(other.mURI) - , mOriginalURI(other.mOriginalURI) - , mLoadReplace(other.mLoadReplace) - , mReferrerURI(other.mReferrerURI) - , mReferrerPolicy(other.mReferrerPolicy) - , mTitle(other.mTitle) - , mPostData(other.mPostData) +nsSHEntry::nsSHEntry(const nsSHEntry& aOther) + : mShared(aOther.mShared) + , mURI(aOther.mURI) + , mOriginalURI(aOther.mOriginalURI) + , mLoadReplace(aOther.mLoadReplace) + , mReferrerURI(aOther.mReferrerURI) + , mReferrerPolicy(aOther.mReferrerPolicy) + , mTitle(aOther.mTitle) + , mPostData(aOther.mPostData) , mLoadType(0) // XXX why not copy? - , mID(other.mID) + , mID(aOther.mID) , mScrollPositionX(0) // XXX why not copy? , mScrollPositionY(0) // XXX why not copy? - , mParent(other.mParent) - , mURIWasModified(other.mURIWasModified) - , mStateData(other.mStateData) - , mIsSrcdocEntry(other.mIsSrcdocEntry) - , mSrcdocData(other.mSrcdocData) - , mBaseURI(other.mBaseURI) + , mParent(aOther.mParent) + , mURIWasModified(aOther.mURIWasModified) + , mStateData(aOther.mStateData) + , mIsSrcdocEntry(aOther.mIsSrcdocEntry) + , mSrcdocData(aOther.mSrcdocData) + , mBaseURI(aOther.mBaseURI) { } @@ -78,113 +72,119 @@ nsSHEntry::~nsSHEntry() mChildren.EnumerateForwards(ClearParentPtr, nullptr); } -//***************************************************************************** -// nsSHEntry: nsISupports -//***************************************************************************** - NS_IMPL_ISUPPORTS(nsSHEntry, nsISHContainer, nsISHEntry_ESR38, nsISHEntry, nsISHEntryInternal) -//***************************************************************************** -// nsSHEntry: nsISHEntry -//***************************************************************************** - -NS_IMETHODIMP nsSHEntry::SetScrollPosition(int32_t x, int32_t y) +NS_IMETHODIMP +nsSHEntry::SetScrollPosition(int32_t aX, int32_t aY) { - mScrollPositionX = x; - mScrollPositionY = y; + mScrollPositionX = aX; + mScrollPositionY = aY; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetScrollPosition(int32_t *x, int32_t *y) +NS_IMETHODIMP +nsSHEntry::GetScrollPosition(int32_t *aX, int32_t *aY) { - *x = mScrollPositionX; - *y = mScrollPositionY; + *aX = mScrollPositionX; + *aY = mScrollPositionY; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetURIWasModified(bool* aOut) +NS_IMETHODIMP +nsSHEntry::GetURIWasModified(bool* aOut) { *aOut = mURIWasModified; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetURIWasModified(bool aIn) +NS_IMETHODIMP +nsSHEntry::SetURIWasModified(bool aIn) { mURIWasModified = aIn; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetURI(nsIURI** aURI) +NS_IMETHODIMP +nsSHEntry::GetURI(nsIURI** aURI) { *aURI = mURI; NS_IF_ADDREF(*aURI); return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetURI(nsIURI* aURI) +NS_IMETHODIMP +nsSHEntry::SetURI(nsIURI* aURI) { mURI = aURI; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetOriginalURI(nsIURI** aOriginalURI) +NS_IMETHODIMP +nsSHEntry::GetOriginalURI(nsIURI** aOriginalURI) { *aOriginalURI = mOriginalURI; NS_IF_ADDREF(*aOriginalURI); return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetOriginalURI(nsIURI* aOriginalURI) +NS_IMETHODIMP +nsSHEntry::SetOriginalURI(nsIURI* aOriginalURI) { mOriginalURI = aOriginalURI; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetLoadReplace(bool* aLoadReplace) +NS_IMETHODIMP +nsSHEntry::GetLoadReplace(bool* aLoadReplace) { *aLoadReplace = mLoadReplace; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetLoadReplace(bool aLoadReplace) +NS_IMETHODIMP +nsSHEntry::SetLoadReplace(bool aLoadReplace) { mLoadReplace = aLoadReplace; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetReferrerURI(nsIURI **aReferrerURI) +NS_IMETHODIMP +nsSHEntry::GetReferrerURI(nsIURI** aReferrerURI) { *aReferrerURI = mReferrerURI; NS_IF_ADDREF(*aReferrerURI); return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetReferrerURI(nsIURI *aReferrerURI) +NS_IMETHODIMP +nsSHEntry::SetReferrerURI(nsIURI* aReferrerURI) { mReferrerURI = aReferrerURI; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetReferrerPolicy(uint32_t *aReferrerPolicy) +NS_IMETHODIMP +nsSHEntry::GetReferrerPolicy(uint32_t* aReferrerPolicy) { *aReferrerPolicy = mReferrerPolicy; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetReferrerPolicy(uint32_t aReferrerPolicy) +NS_IMETHODIMP +nsSHEntry::SetReferrerPolicy(uint32_t aReferrerPolicy) { mReferrerPolicy = aReferrerPolicy; return NS_OK; } NS_IMETHODIMP -nsSHEntry::SetContentViewer(nsIContentViewer *aViewer) +nsSHEntry::SetContentViewer(nsIContentViewer* aViewer) { return mShared->SetContentViewer(aViewer); } NS_IMETHODIMP -nsSHEntry::GetContentViewer(nsIContentViewer **aResult) +nsSHEntry::GetContentViewer(nsIContentViewer** aResult) { *aResult = mShared->mContentViewer; NS_IF_ADDREF(*aResult); @@ -192,15 +192,15 @@ nsSHEntry::GetContentViewer(nsIContentViewer **aResult) } NS_IMETHODIMP -nsSHEntry::GetAnyContentViewer(nsISHEntry **aOwnerEntry, - nsIContentViewer **aResult) +nsSHEntry::GetAnyContentViewer(nsISHEntry** aOwnerEntry, + nsIContentViewer** aResult) { // Find a content viewer in the root node or any of its children, // assuming that there is only one content viewer total in any one // nsSHEntry tree GetContentViewer(aResult); if (*aResult) { -#ifdef DEBUG_PAGE_CACHE +#ifdef DEBUG_PAGE_CACHE printf("Found content viewer\n"); #endif *aOwnerEntry = this; @@ -231,124 +231,142 @@ nsSHEntry::SetSticky(bool aSticky) } NS_IMETHODIMP -nsSHEntry::GetSticky(bool *aSticky) +nsSHEntry::GetSticky(bool* aSticky) { *aSticky = mShared->mSticky; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetTitle(char16_t** aTitle) +NS_IMETHODIMP +nsSHEntry::GetTitle(char16_t** aTitle) { // Check for empty title... if (mTitle.IsEmpty() && mURI) { // Default title is the URL. nsAutoCString spec; - if (NS_SUCCEEDED(mURI->GetSpec(spec))) + if (NS_SUCCEEDED(mURI->GetSpec(spec))) { AppendUTF8toUTF16(spec, mTitle); + } } *aTitle = ToNewUnicode(mTitle); return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetTitle(const nsAString &aTitle) +NS_IMETHODIMP +nsSHEntry::SetTitle(const nsAString& aTitle) { mTitle = aTitle; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetPostData(nsIInputStream** aResult) +NS_IMETHODIMP +nsSHEntry::GetPostData(nsIInputStream** aResult) { *aResult = mPostData; NS_IF_ADDREF(*aResult); return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetPostData(nsIInputStream* aPostData) +NS_IMETHODIMP +nsSHEntry::SetPostData(nsIInputStream* aPostData) { mPostData = aPostData; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetLayoutHistoryState(nsILayoutHistoryState** aResult) +NS_IMETHODIMP +nsSHEntry::GetLayoutHistoryState(nsILayoutHistoryState** aResult) { *aResult = mShared->mLayoutHistoryState; NS_IF_ADDREF(*aResult); return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetLayoutHistoryState(nsILayoutHistoryState* aState) +NS_IMETHODIMP +nsSHEntry::SetLayoutHistoryState(nsILayoutHistoryState* aState) { mShared->mLayoutHistoryState = aState; if (mShared->mLayoutHistoryState) { - mShared->mLayoutHistoryState-> - SetScrollPositionOnly(!mShared->mSaveLayoutState); + mShared->mLayoutHistoryState->SetScrollPositionOnly( + !mShared->mSaveLayoutState); } return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetLoadType(uint32_t * aResult) +NS_IMETHODIMP +nsSHEntry::GetLoadType(uint32_t* aResult) { *aResult = mLoadType; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetLoadType(uint32_t aLoadType) +NS_IMETHODIMP +nsSHEntry::SetLoadType(uint32_t aLoadType) { mLoadType = aLoadType; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetID(uint32_t * aResult) +NS_IMETHODIMP +nsSHEntry::GetID(uint32_t* aResult) { *aResult = mID; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetID(uint32_t aID) +NS_IMETHODIMP +nsSHEntry::SetID(uint32_t aID) { mID = aID; return NS_OK; } -nsSHEntryShared* nsSHEntry::GetSharedState() +nsSHEntryShared* +nsSHEntry::GetSharedState() { return mShared; } -NS_IMETHODIMP nsSHEntry::GetIsSubFrame(bool * aFlag) +NS_IMETHODIMP +nsSHEntry::GetIsSubFrame(bool* aFlag) { *aFlag = mShared->mIsFrameNavigation; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetIsSubFrame(bool aFlag) +NS_IMETHODIMP +nsSHEntry::SetIsSubFrame(bool aFlag) { mShared->mIsFrameNavigation = aFlag; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetCacheKey(nsISupports** aResult) +NS_IMETHODIMP +nsSHEntry::GetCacheKey(nsISupports** aResult) { *aResult = mShared->mCacheKey; NS_IF_ADDREF(*aResult); return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetCacheKey(nsISupports* aCacheKey) +NS_IMETHODIMP +nsSHEntry::SetCacheKey(nsISupports* aCacheKey) { mShared->mCacheKey = aCacheKey; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetSaveLayoutStateFlag(bool * aFlag) +NS_IMETHODIMP +nsSHEntry::GetSaveLayoutStateFlag(bool* aFlag) { *aFlag = mShared->mSaveLayoutState; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetSaveLayoutStateFlag(bool aFlag) +NS_IMETHODIMP +nsSHEntry::SetSaveLayoutStateFlag(bool aFlag) { mShared->mSaveLayoutState = aFlag; if (mShared->mLayoutHistoryState) { @@ -358,44 +376,48 @@ NS_IMETHODIMP nsSHEntry::SetSaveLayoutStateFlag(bool aFlag) return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetExpirationStatus(bool * aFlag) +NS_IMETHODIMP +nsSHEntry::GetExpirationStatus(bool* aFlag) { *aFlag = mShared->mExpired; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetExpirationStatus(bool aFlag) +NS_IMETHODIMP +nsSHEntry::SetExpirationStatus(bool aFlag) { mShared->mExpired = aFlag; return NS_OK; } -NS_IMETHODIMP nsSHEntry::GetContentType(nsACString& aContentType) +NS_IMETHODIMP +nsSHEntry::GetContentType(nsACString& aContentType) { aContentType = mShared->mContentType; return NS_OK; } -NS_IMETHODIMP nsSHEntry::SetContentType(const nsACString& aContentType) +NS_IMETHODIMP +nsSHEntry::SetContentType(const nsACString& aContentType) { mShared->mContentType = aContentType; return NS_OK; } NS_IMETHODIMP -nsSHEntry::Create(nsIURI * aURI, const nsAString &aTitle, - nsIInputStream * aInputStream, - nsILayoutHistoryState * aLayoutHistoryState, - nsISupports * aCacheKey, const nsACString& aContentType, - nsISupports* aOwner, - uint64_t aDocShellID, bool aDynamicCreation) +nsSHEntry::Create(nsIURI* aURI, const nsAString& aTitle, + nsIInputStream* aInputStream, + nsILayoutHistoryState* aLayoutHistoryState, + nsISupports* aCacheKey, const nsACString& aContentType, + nsISupports* aOwner, uint64_t aDocShellID, + bool aDynamicCreation) { mURI = aURI; mTitle = aTitle; mPostData = aInputStream; // Set the LoadType by default to loadHistory during creation - mLoadType = (uint32_t) nsIDocShellLoadInfo::loadHistory; + mLoadType = (uint32_t)nsIDocShellLoadInfo::loadHistory; mShared->mCacheKey = aCacheKey; mShared->mContentType = aContentType; @@ -403,7 +425,7 @@ nsSHEntry::Create(nsIURI * aURI, const nsAString &aTitle, mShared->mDocShellID = aDocShellID; mShared->mDynamicallyCreated = aDynamicCreation; - // By default all entries are set false for subframe flag. + // By default all entries are set false for subframe flag. // nsDocShell::CloneAndReplace() which creates entries for // all subframe navigations, sets the flag to true. mShared->mIsFrameNavigation = false; @@ -412,7 +434,7 @@ nsSHEntry::Create(nsIURI * aURI, const nsAString &aTitle, mShared->mSaveLayoutState = true; mShared->mLayoutHistoryState = aLayoutHistoryState; - //By default the page is not expired + // By default the page is not expired mShared->mExpired = false; mIsSrcdocEntry = false; @@ -422,7 +444,7 @@ nsSHEntry::Create(nsIURI * aURI, const nsAString &aTitle, } NS_IMETHODIMP -nsSHEntry::Clone(nsISHEntry ** aResult) +nsSHEntry::Clone(nsISHEntry** aResult) { *aResult = new nsSHEntry(*this); NS_ADDREF(*aResult); @@ -430,7 +452,7 @@ nsSHEntry::Clone(nsISHEntry ** aResult) } NS_IMETHODIMP -nsSHEntry::GetParent(nsISHEntry ** aResult) +nsSHEntry::GetParent(nsISHEntry** aResult) { NS_ENSURE_ARG_POINTER(aResult); *aResult = mParent; @@ -439,7 +461,7 @@ nsSHEntry::GetParent(nsISHEntry ** aResult) } NS_IMETHODIMP -nsSHEntry::SetParent(nsISHEntry * aParent) +nsSHEntry::SetParent(nsISHEntry* aParent) { /* parent not Addrefed on purpose to avoid cyclic reference * Null parent is OK @@ -451,49 +473,49 @@ nsSHEntry::SetParent(nsISHEntry * aParent) } NS_IMETHODIMP -nsSHEntry::SetWindowState(nsISupports *aState) +nsSHEntry::SetWindowState(nsISupports* aState) { mShared->mWindowState = aState; return NS_OK; } NS_IMETHODIMP -nsSHEntry::GetWindowState(nsISupports **aState) +nsSHEntry::GetWindowState(nsISupports** aState) { NS_IF_ADDREF(*aState = mShared->mWindowState); return NS_OK; } NS_IMETHODIMP -nsSHEntry::SetViewerBounds(const nsIntRect &aBounds) +nsSHEntry::SetViewerBounds(const nsIntRect& aBounds) { mShared->mViewerBounds = aBounds; return NS_OK; } NS_IMETHODIMP -nsSHEntry::GetViewerBounds(nsIntRect &aBounds) +nsSHEntry::GetViewerBounds(nsIntRect& aBounds) { aBounds = mShared->mViewerBounds; return NS_OK; } NS_IMETHODIMP -nsSHEntry::GetOwner(nsISupports **aOwner) +nsSHEntry::GetOwner(nsISupports** aOwner) { NS_IF_ADDREF(*aOwner = mShared->mOwner); return NS_OK; } NS_IMETHODIMP -nsSHEntry::SetOwner(nsISupports *aOwner) +nsSHEntry::SetOwner(nsISupports* aOwner) { mShared->mOwner = aOwner; return NS_OK; } NS_IMETHODIMP -nsSHEntry::GetBFCacheEntry(nsIBFCacheEntry **aEntry) +nsSHEntry::GetBFCacheEntry(nsIBFCacheEntry** aEntry) { NS_ENSURE_ARG_POINTER(aEntry); NS_IF_ADDREF(*aEntry = mShared); @@ -501,18 +523,18 @@ nsSHEntry::GetBFCacheEntry(nsIBFCacheEntry **aEntry) } bool -nsSHEntry::HasBFCacheEntry(nsIBFCacheEntry *aEntry) +nsSHEntry::HasBFCacheEntry(nsIBFCacheEntry* aEntry) { return static_cast(mShared) == aEntry; } NS_IMETHODIMP -nsSHEntry::AdoptBFCacheEntry(nsISHEntry *aEntry) +nsSHEntry::AdoptBFCacheEntry(nsISHEntry* aEntry) { nsCOMPtr shEntry = do_QueryInterface(aEntry); NS_ENSURE_STATE(shEntry); - nsSHEntryShared *shared = shEntry->GetSharedState(); + nsSHEntryShared* shared = shEntry->GetSharedState(); NS_ENSURE_STATE(shared); mShared = shared; @@ -520,11 +542,11 @@ nsSHEntry::AdoptBFCacheEntry(nsISHEntry *aEntry) } NS_IMETHODIMP -nsSHEntry::SharesDocumentWith(nsISHEntry *aEntry, bool *aOut) +nsSHEntry::SharesDocumentWith(nsISHEntry* aEntry, bool* aOut) { NS_ENSURE_ARG_POINTER(aOut); - nsCOMPtr internal = do_QueryInterface(aEntry); + nsCOMPtr internal = do_QueryInterface(aEntry); NS_ENSURE_STATE(internal); *aOut = mShared == internal->GetSharedState(); @@ -546,14 +568,14 @@ nsSHEntry::GetIsSrcdocEntry(bool* aIsSrcdocEntry) } NS_IMETHODIMP -nsSHEntry::GetSrcdocData(nsAString &aSrcdocData) +nsSHEntry::GetSrcdocData(nsAString& aSrcdocData) { aSrcdocData = mSrcdocData; return NS_OK; } NS_IMETHODIMP -nsSHEntry::SetSrcdocData(const nsAString &aSrcdocData) +nsSHEntry::SetSrcdocData(const nsAString& aSrcdocData) { mSrcdocData = aSrcdocData; mIsSrcdocEntry = true; @@ -561,7 +583,7 @@ nsSHEntry::SetSrcdocData(const nsAString &aSrcdocData) } NS_IMETHODIMP -nsSHEntry::GetBaseURI(nsIURI **aBaseURI) +nsSHEntry::GetBaseURI(nsIURI** aBaseURI) { *aBaseURI = mBaseURI; NS_IF_ADDREF(*aBaseURI); @@ -569,25 +591,21 @@ nsSHEntry::GetBaseURI(nsIURI **aBaseURI) } NS_IMETHODIMP -nsSHEntry::SetBaseURI(nsIURI *aBaseURI) +nsSHEntry::SetBaseURI(nsIURI* aBaseURI) { mBaseURI = aBaseURI; return NS_OK; } -//***************************************************************************** -// nsSHEntry: nsISHContainer -//***************************************************************************** - -NS_IMETHODIMP -nsSHEntry::GetChildCount(int32_t * aCount) +NS_IMETHODIMP +nsSHEntry::GetChildCount(int32_t* aCount) { *aCount = mChildren.Count(); return NS_OK; } NS_IMETHODIMP -nsSHEntry::AddChild(nsISHEntry * aChild, int32_t aOffset) +nsSHEntry::AddChild(nsISHEntry* aChild, int32_t aOffset) { if (aChild) { NS_ENSURE_SUCCESS(aChild->SetParent(this), NS_ERROR_FAILURE); @@ -607,7 +625,7 @@ nsSHEntry::AddChild(nsISHEntry * aChild, int32_t aOffset) // // Assert that aOffset will not be so high as to grow us a lot. // - NS_ASSERTION(aOffset < (mChildren.Count()+1023), "Large frames array!\n"); + NS_ASSERTION(aOffset < (mChildren.Count() + 1023), "Large frames array!\n"); bool newChildIsDyn = false; if (aChild) { @@ -662,7 +680,7 @@ nsSHEntry::AddChild(nsISHEntry * aChild, int32_t aOffset) } } } - + if (dynEntry) { nsCOMArray tmp; tmp.SetCount(aOffset - dynEntryIndex + 1); @@ -670,7 +688,6 @@ nsSHEntry::AddChild(nsISHEntry * aChild, int32_t aOffset) NS_ASSERTION(mChildren[aOffset + 1] == dynEntry, "Whaat?"); } } - // Make sure there isn't anything at aOffset. if (aOffset < mChildren.Count()) { @@ -692,7 +709,7 @@ nsSHEntry::AddChild(nsISHEntry * aChild, int32_t aOffset) } NS_IMETHODIMP -nsSHEntry::RemoveChild(nsISHEntry * aChild) +nsSHEntry::RemoveChild(nsISHEntry* aChild) { NS_ENSURE_TRUE(aChild, NS_ERROR_FAILURE); bool childRemoved = false; @@ -720,7 +737,7 @@ nsSHEntry::RemoveChild(nsISHEntry * aChild) } NS_IMETHODIMP -nsSHEntry::GetChildAt(int32_t aIndex, nsISHEntry ** aResult) +nsSHEntry::GetChildAt(int32_t aIndex, nsISHEntry** aResult) { if (aIndex >= 0 && aIndex < mChildren.Count()) { *aResult = mChildren[aIndex]; @@ -755,7 +772,7 @@ nsSHEntry::ReplaceChild(nsISHEntry* aNewEntry) } NS_IMETHODIMP -nsSHEntry::AddChildShell(nsIDocShellTreeItem *aShell) +nsSHEntry::AddChildShell(nsIDocShellTreeItem* aShell) { NS_ASSERTION(aShell, "Null child shell added to history entry"); mShared->mChildShells.AppendObject(aShell); @@ -763,7 +780,7 @@ nsSHEntry::AddChildShell(nsIDocShellTreeItem *aShell) } NS_IMETHODIMP -nsSHEntry::ChildShellAt(int32_t aIndex, nsIDocShellTreeItem **aShell) +nsSHEntry::ChildShellAt(int32_t aIndex, nsIDocShellTreeItem** aShell) { NS_IF_ADDREF(*aShell = mShared->mChildShells.SafeObjectAt(aIndex)); return NS_OK; @@ -777,14 +794,14 @@ nsSHEntry::ClearChildShells() } NS_IMETHODIMP -nsSHEntry::GetRefreshURIList(nsISupportsArray **aList) +nsSHEntry::GetRefreshURIList(nsISupportsArray** aList) { NS_IF_ADDREF(*aList = mShared->mRefreshURIList); return NS_OK; } NS_IMETHODIMP -nsSHEntry::SetRefreshURIList(nsISupportsArray *aList) +nsSHEntry::SetRefreshURIList(nsISupportsArray* aList) { mShared->mRefreshURIList = aList; return NS_OK; @@ -832,7 +849,7 @@ nsSHEntry::HasDetachedEditor() } NS_IMETHODIMP -nsSHEntry::GetStateData(nsIStructuredCloneContainer **aContainer) +nsSHEntry::GetStateData(nsIStructuredCloneContainer** aContainer) { NS_ENSURE_ARG_POINTER(aContainer); NS_IF_ADDREF(*aContainer = mStateData); @@ -840,7 +857,7 @@ nsSHEntry::GetStateData(nsIStructuredCloneContainer **aContainer) } NS_IMETHODIMP -nsSHEntry::SetStateData(nsIStructuredCloneContainer *aContainer) +nsSHEntry::SetStateData(nsIStructuredCloneContainer* aContainer) { mStateData = aContainer; return NS_OK; @@ -883,9 +900,8 @@ nsSHEntry::SetDocshellID(uint64_t aID) return NS_OK; } - NS_IMETHODIMP -nsSHEntry::GetLastTouched(uint32_t *aLastTouched) +nsSHEntry::GetLastTouched(uint32_t* aLastTouched) { *aLastTouched = mShared->mLastTouched; return NS_OK; diff --git a/docshell/shistory/src/nsSHEntry.h b/docshell/shistory/src/nsSHEntry.h index 4b35bd0e14..b6286971a4 100644 --- a/docshell/shistory/src/nsSHEntry.h +++ b/docshell/shistory/src/nsSHEntry.h @@ -26,9 +26,9 @@ class nsSHEntry final : public nsISHEntry_ESR38, public nsISHContainer, public nsISHEntryInternal { -public: +public: nsSHEntry(); - nsSHEntry(const nsSHEntry &other); + nsSHEntry(const nsSHEntry& aOther); NS_DECL_ISUPPORTS NS_DECL_NSISHENTRY_ESR38 @@ -40,7 +40,7 @@ public: static nsresult Startup(); static void Shutdown(); - + private: ~nsSHEntry(); @@ -49,24 +49,24 @@ private: nsRefPtr mShared; // See nsSHEntry.idl for comments on these members. - nsCOMPtr mURI; - nsCOMPtr mOriginalURI; - bool mLoadReplace; - nsCOMPtr mReferrerURI; - uint32_t mReferrerPolicy; - nsString mTitle; + nsCOMPtr mURI; + nsCOMPtr mOriginalURI; + bool mLoadReplace; + nsCOMPtr mReferrerURI; + uint32_t mReferrerPolicy; + nsString mTitle; nsCOMPtr mPostData; - uint32_t mLoadType; - uint32_t mID; - int32_t mScrollPositionX; - int32_t mScrollPositionY; - nsISHEntry* mParent; - nsCOMArray mChildren; - bool mURIWasModified; + uint32_t mLoadType; + uint32_t mID; + int32_t mScrollPositionX; + int32_t mScrollPositionY; + nsISHEntry* mParent; + nsCOMArray mChildren; + bool mURIWasModified; nsCOMPtr mStateData; - bool mIsSrcdocEntry; - nsString mSrcdocData; - nsCOMPtr mBaseURI; + bool mIsSrcdocEntry; + nsString mSrcdocData; + nsCOMPtr mBaseURI; }; #endif /* nsSHEntry_h */ diff --git a/docshell/shistory/src/nsSHEntryShared.cpp b/docshell/shistory/src/nsSHEntryShared.cpp index 2c3a6fedbb..c4aba9293b 100644 --- a/docshell/shistory/src/nsSHEntryShared.cpp +++ b/docshell/shistory/src/nsSHEntryShared.cpp @@ -29,10 +29,11 @@ uint64_t gSHEntrySharedID = 0; #define CONTENT_VIEWER_TIMEOUT_SECONDS "browser.sessionhistory.contentViewerTimeout" // Default this to time out unused content viewers after 30 minutes -#define CONTENT_VIEWER_TIMEOUT_SECONDS_DEFAULT (30*60) +#define CONTENT_VIEWER_TIMEOUT_SECONDS_DEFAULT (30 * 60) typedef nsExpirationTracker HistoryTrackerBase; -class HistoryTracker final : public HistoryTrackerBase { +class HistoryTracker final : public HistoryTrackerBase +{ public: explicit HistoryTracker(uint32_t aTimeout) : HistoryTrackerBase(1000 * aTimeout / 2) @@ -40,13 +41,14 @@ public: } protected: - virtual void NotifyExpired(nsSHEntryShared *aObj) { + virtual void NotifyExpired(nsSHEntryShared* aObj) + { RemoveObject(aObj); aObj->Expire(); } }; -static HistoryTracker *gHistoryTracker = nullptr; +static HistoryTracker* gHistoryTracker = nullptr; void nsSHEntryShared::EnsureHistoryTracker() @@ -88,10 +90,9 @@ nsSHEntryShared::~nsSHEntryShared() if (gHistoryTracker) { // Check that we're not still on track to expire. We shouldn't be, because // we just removed ourselves! - nsExpirationTracker::Iterator - iterator(gHistoryTracker); + nsExpirationTracker::Iterator iterator(gHistoryTracker); - nsSHEntryShared *elem; + nsSHEntryShared* elem; while ((elem = iterator.Next()) != nullptr) { NS_ASSERTION(elem != this, "Found dead entry still in the tracker!"); } @@ -106,7 +107,7 @@ nsSHEntryShared::~nsSHEntryShared() NS_IMPL_ISUPPORTS(nsSHEntryShared, nsIBFCacheEntry, nsIMutationObserver) already_AddRefed -nsSHEntryShared::Duplicate(nsSHEntryShared *aEntry) +nsSHEntryShared::Duplicate(nsSHEntryShared* aEntry) { nsRefPtr newEntry = new nsSHEntryShared(); @@ -124,7 +125,8 @@ nsSHEntryShared::Duplicate(nsSHEntryShared *aEntry) return newEntry.forget(); } -void nsSHEntryShared::RemoveFromExpirationTracker() +void +nsSHEntryShared::RemoveFromExpirationTracker() { if (gHistoryTracker && GetExpirationState()->IsTracked()) { gHistoryTracker->RemoveObject(this); @@ -197,7 +199,7 @@ nsSHEntryShared::Expire() } nsresult -nsSHEntryShared::SetContentViewer(nsIContentViewer *aViewer) +nsSHEntryShared::SetContentViewer(nsIContentViewer* aViewer) { NS_PRECONDITION(!aViewer || !mContentViewer, "SHEntryShared already contains viewer"); @@ -229,8 +231,7 @@ nsSHEntryShared::SetContentViewer(nsIContentViewer *aViewer) nsresult nsSHEntryShared::RemoveFromBFCacheSync() { - NS_ASSERTION(mContentViewer && mDocument, - "we're not in the bfcache!"); + NS_ASSERTION(mContentViewer && mDocument, "we're not in the bfcache!"); nsCOMPtr viewer = mContentViewer; DropPresentationState(); @@ -249,9 +250,10 @@ class DestroyViewerEvent : public nsRunnable { public: DestroyViewerEvent(nsIContentViewer* aViewer, nsIDocument* aDocument) - : mViewer(aViewer), - mDocument(aDocument) - {} + : mViewer(aViewer) + , mDocument(aDocument) + { + } NS_IMETHOD Run() { @@ -268,14 +270,12 @@ public: nsresult nsSHEntryShared::RemoveFromBFCacheAsync() { - NS_ASSERTION(mContentViewer && mDocument, - "we're not in the bfcache!"); + NS_ASSERTION(mContentViewer && mDocument, "we're not in the bfcache!"); // Release the reference to the contentviewer asynchronously so that the // document doesn't get nuked mid-mutation. - nsCOMPtr evt = - new DestroyViewerEvent(mContentViewer, mDocument); + nsCOMPtr evt = new DestroyViewerEvent(mContentViewer, mDocument); nsresult rv = NS_DispatchToCurrentThread(evt); if (NS_FAILED(rv)) { NS_WARNING("failed to dispatch DestroyViewerEvent"); @@ -293,16 +293,12 @@ nsSHEntryShared::RemoveFromBFCacheAsync() } nsresult -nsSHEntryShared::GetID(uint64_t *aID) +nsSHEntryShared::GetID(uint64_t* aID) { *aID = mID; return NS_OK; } -//***************************************************************************** -// nsSHEntryShared: nsIMutationObserver -//***************************************************************************** - void nsSHEntryShared::NodeWillBeDestroyed(const nsINode* aNode) { @@ -372,6 +368,6 @@ nsSHEntryShared::ContentRemoved(nsIDocument* aDocument, } void -nsSHEntryShared::ParentChainChanged(nsIContent *aContent) +nsSHEntryShared::ParentChainChanged(nsIContent* aContent) { } diff --git a/docshell/shistory/src/nsSHEntryShared.h b/docshell/shistory/src/nsSHEntryShared.h index 6559fa5163..5b619201b0 100644 --- a/docshell/shistory/src/nsSHEntryShared.h +++ b/docshell/shistory/src/nsSHEntryShared.h @@ -30,64 +30,65 @@ class nsISupportsArray; // back/forward cache. // // nsSHEntryShared is the vehicle for this sharing. -class nsSHEntryShared final : public nsIBFCacheEntry, - public nsIMutationObserver +class nsSHEntryShared final + : public nsIBFCacheEntry + , public nsIMutationObserver { - public: - static void EnsureHistoryTracker(); - static void Shutdown(); +public: + static void EnsureHistoryTracker(); + static void Shutdown(); - nsSHEntryShared(); + nsSHEntryShared(); - NS_DECL_ISUPPORTS - NS_DECL_NSIMUTATIONOBSERVER - NS_DECL_NSIBFCACHEENTRY + NS_DECL_ISUPPORTS + NS_DECL_NSIMUTATIONOBSERVER + NS_DECL_NSIBFCACHEENTRY - private: - ~nsSHEntryShared(); +private: + ~nsSHEntryShared(); - friend class nsSHEntry; + friend class nsSHEntry; - friend class HistoryTracker; - friend class nsExpirationTracker; - nsExpirationState *GetExpirationState() { return &mExpirationState; } + friend class HistoryTracker; + friend class nsExpirationTracker; + nsExpirationState *GetExpirationState() { return &mExpirationState; } - static already_AddRefed Duplicate(nsSHEntryShared *aEntry); + static already_AddRefed Duplicate(nsSHEntryShared* aEntry); - void RemoveFromExpirationTracker(); - void Expire(); - nsresult SyncPresentationState(); - void DropPresentationState(); + void RemoveFromExpirationTracker(); + void Expire(); + nsresult SyncPresentationState(); + void DropPresentationState(); - nsresult SetContentViewer(nsIContentViewer *aViewer); + nsresult SetContentViewer(nsIContentViewer* aViewer); - // See nsISHEntry.idl for an explanation of these members. + // See nsISHEntry.idl for an explanation of these members. - // These members are copied by nsSHEntryShared::Duplicate(). If you add a - // member here, be sure to update the Duplicate() implementation. - uint64_t mDocShellID; - nsCOMArray mChildShells; - nsCOMPtr mOwner; - nsCString mContentType; - bool mIsFrameNavigation; - bool mSaveLayoutState; - bool mSticky; - bool mDynamicallyCreated; - nsCOMPtr mCacheKey; - uint32_t mLastTouched; + // These members are copied by nsSHEntryShared::Duplicate(). If you add a + // member here, be sure to update the Duplicate() implementation. + uint64_t mDocShellID; + nsCOMArray mChildShells; + nsCOMPtr mOwner; + nsCString mContentType; + bool mIsFrameNavigation; + bool mSaveLayoutState; + bool mSticky; + bool mDynamicallyCreated; + nsCOMPtr mCacheKey; + uint32_t mLastTouched; - // These members aren't copied by nsSHEntryShared::Duplicate() because - // they're specific to a particular content viewer. - uint64_t mID; - nsCOMPtr mContentViewer; - nsCOMPtr mDocument; - nsCOMPtr mLayoutHistoryState; - bool mExpired; - nsCOMPtr mWindowState; - nsIntRect mViewerBounds; - nsCOMPtr mRefreshURIList; - nsExpirationState mExpirationState; - nsAutoPtr mEditorData; + // These members aren't copied by nsSHEntryShared::Duplicate() because + // they're specific to a particular content viewer. + uint64_t mID; + nsCOMPtr mContentViewer; + nsCOMPtr mDocument; + nsCOMPtr mLayoutHistoryState; + bool mExpired; + nsCOMPtr mWindowState; + nsIntRect mViewerBounds; + nsCOMPtr mRefreshURIList; + nsExpirationState mExpirationState; + nsAutoPtr mEditorData; }; #endif diff --git a/docshell/shistory/src/nsSHTransaction.cpp b/docshell/shistory/src/nsSHTransaction.cpp index 1768a44efd..71c42c1415 100644 --- a/docshell/shistory/src/nsSHTransaction.cpp +++ b/docshell/shistory/src/nsSHTransaction.cpp @@ -4,80 +4,66 @@ * 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/. */ -// Local Includes #include "nsSHTransaction.h" #include "nsISHEntry.h" -//***************************************************************************** -//*** nsSHTransaction: Object Management -//***************************************************************************** - -nsSHTransaction::nsSHTransaction() : mPersist(true), mPrev(nullptr) +nsSHTransaction::nsSHTransaction() + : mPersist(true) + , mPrev(nullptr) { } - nsSHTransaction::~nsSHTransaction() { } -//***************************************************************************** -// nsSHTransaction: nsISupports -//***************************************************************************** - NS_IMPL_ADDREF(nsSHTransaction) NS_IMPL_RELEASE(nsSHTransaction) NS_INTERFACE_MAP_BEGIN(nsSHTransaction) - NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISHTransaction) - NS_INTERFACE_MAP_ENTRY(nsISHTransaction) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISHTransaction) + NS_INTERFACE_MAP_ENTRY(nsISHTransaction) NS_INTERFACE_MAP_END -//***************************************************************************** -// nsSHTransaction: nsISHTransaction -//***************************************************************************** - NS_IMETHODIMP nsSHTransaction::Create(nsISHEntry* aSHEntry, nsISHTransaction* aPrev) { - SetSHEntry(aSHEntry); - if(aPrev) - aPrev->SetNext(this); + SetSHEntry(aSHEntry); + if (aPrev) { + aPrev->SetNext(this); + } - SetPrev(aPrev); - return NS_OK; + SetPrev(aPrev); + return NS_OK; } NS_IMETHODIMP -nsSHTransaction::GetSHEntry(nsISHEntry ** aResult) +nsSHTransaction::GetSHEntry(nsISHEntry** aResult) { - NS_ENSURE_ARG_POINTER(aResult); - *aResult = mSHEntry; - NS_IF_ADDREF(*aResult); - return NS_OK; + NS_ENSURE_ARG_POINTER(aResult); + *aResult = mSHEntry; + NS_IF_ADDREF(*aResult); + return NS_OK; } - NS_IMETHODIMP -nsSHTransaction::SetSHEntry(nsISHEntry * aSHEntry) +nsSHTransaction::SetSHEntry(nsISHEntry* aSHEntry) { - mSHEntry = aSHEntry; - return NS_OK; + mSHEntry = aSHEntry; + return NS_OK; } - NS_IMETHODIMP -nsSHTransaction::GetNext(nsISHTransaction * * aResult) +nsSHTransaction::GetNext(nsISHTransaction** aResult) { - NS_ENSURE_ARG_POINTER(aResult); - *aResult = mNext; - NS_IF_ADDREF(*aResult); - return NS_OK; + NS_ENSURE_ARG_POINTER(aResult); + *aResult = mNext; + NS_IF_ADDREF(*aResult); + return NS_OK; } - NS_IMETHODIMP -nsSHTransaction::SetNext(nsISHTransaction * aNext) +nsSHTransaction::SetNext(nsISHTransaction* aNext) { if (aNext) { NS_ENSURE_SUCCESS(aNext->SetPrev(this), NS_ERROR_FAILURE); @@ -88,34 +74,34 @@ nsSHTransaction::SetNext(nsISHTransaction * aNext) } NS_IMETHODIMP -nsSHTransaction::SetPrev(nsISHTransaction * aPrev) +nsSHTransaction::SetPrev(nsISHTransaction* aPrev) { - /* This is weak reference to parent. Do not Addref it */ - mPrev = aPrev; - return NS_OK; + /* This is weak reference to parent. Do not Addref it */ + mPrev = aPrev; + return NS_OK; } nsresult -nsSHTransaction::GetPrev(nsISHTransaction ** aResult) +nsSHTransaction::GetPrev(nsISHTransaction** aResult) { - NS_ENSURE_ARG_POINTER(aResult); - *aResult = mPrev; - NS_IF_ADDREF(*aResult); - return NS_OK; + NS_ENSURE_ARG_POINTER(aResult); + *aResult = mPrev; + NS_IF_ADDREF(*aResult); + return NS_OK; } NS_IMETHODIMP nsSHTransaction::SetPersist(bool aPersist) { - mPersist = aPersist; - return NS_OK; + mPersist = aPersist; + return NS_OK; } NS_IMETHODIMP nsSHTransaction::GetPersist(bool* aPersist) { - NS_ENSURE_ARG_POINTER(aPersist); + NS_ENSURE_ARG_POINTER(aPersist); - *aPersist = mPersist; - return NS_OK; + *aPersist = mPersist; + return NS_OK; } diff --git a/docshell/shistory/src/nsSHTransaction.h b/docshell/shistory/src/nsSHTransaction.h index 8c7ba2afd5..c4c7d0763b 100644 --- a/docshell/shistory/src/nsSHTransaction.h +++ b/docshell/shistory/src/nsSHTransaction.h @@ -15,25 +15,23 @@ class nsISHEntry; -class nsSHTransaction: public nsISHTransaction +class nsSHTransaction : public nsISHTransaction { public: - NS_DECL_ISUPPORTS - NS_DECL_NSISHTRANSACTION + NS_DECL_ISUPPORTS + NS_DECL_NSISHTRANSACTION - nsSHTransaction(); + nsSHTransaction(); protected: - virtual ~nsSHTransaction(); - + virtual ~nsSHTransaction(); protected: - bool mPersist; + bool mPersist; - nsISHTransaction * mPrev; // Weak Reference - nsCOMPtr mNext; - nsCOMPtr mSHEntry; + nsISHTransaction* mPrev; // Weak Reference + nsCOMPtr mNext; + nsCOMPtr mSHEntry; }; - -#endif /* nsSHTransaction_h */ +#endif /* nsSHTransaction_h */ diff --git a/docshell/shistory/src/nsSHistory.cpp b/docshell/shistory/src/nsSHistory.cpp index b5a77eb2f8..ecbdecc331 100644 --- a/docshell/shistory/src/nsSHistory.cpp +++ b/docshell/shistory/src/nsSHistory.cpp @@ -4,7 +4,6 @@ * 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/. */ -// Local Includes #include "nsSHistory.h" #include @@ -47,9 +46,9 @@ static const char* kObservedPrefs[] = { nullptr }; -static int32_t gHistoryMaxSize = 50; +static int32_t gHistoryMaxSize = 50; // Max viewers allowed per SHistory objects -static const int32_t gHistoryMaxViewers = 3; +static const int32_t gHistoryMaxViewers = 3; // List of all SHistory objects, used for content viewer cache eviction static PRCList gSHistoryList; // Max viewers allowed total, across all SHistory objects - negative default @@ -60,14 +59,13 @@ int32_t nsSHistory::sHistoryMaxTotalViewers = -1; // entries were touched, so that we can evict older entries first. static uint32_t gTouchCounter = 0; -#ifdef PR_LOGGING - static PRLogModuleInfo* GetSHistoryLog() { - static PRLogModuleInfo *sLog; - if (!sLog) + static PRLogModuleInfo* sLog; + if (!sLog) { sLog = PR_NewLogModule("nsSHistory"); + } return sLog; } #define LOG(format) PR_LOG(GetSHistoryLog(), PR_LOG_DEBUG, format) @@ -105,14 +103,6 @@ GetSHistoryLog() } \ PR_END_MACRO -#else // !PR_LOGGING - -#define LOG(format) -#define LOG_SPEC(format, uri) -#define LOG_SHENTRY_SPEC(format, shentry) - -#endif // PR_LOGGING - // Iterates over all registered session history listeners. #define ITERATE_LISTENERS(body) \ PR_BEGIN_MACRO \ @@ -155,20 +145,16 @@ GetSHistoryLog() } \ PR_END_MACRO -enum HistCmd{ +enum HistCmd +{ HIST_CMD_BACK, HIST_CMD_FORWARD, HIST_CMD_GOTOINDEX, HIST_CMD_RELOAD -} ; - -//***************************************************************************** -//*** nsSHistoryObserver -//***************************************************************************** +}; class nsSHistoryObserver final : public nsIObserver { - public: NS_DECL_ISUPPORTS NS_DECL_NSIOBSERVER @@ -184,8 +170,8 @@ StaticRefPtr gObserver; NS_IMPL_ISUPPORTS(nsSHistoryObserver, nsIObserver) NS_IMETHODIMP -nsSHistoryObserver::Observe(nsISupports *aSubject, const char *aTopic, - const char16_t *aData) +nsSHistoryObserver::Observe(nsISupports* aSubject, const char* aTopic, + const char16_t* aData) { if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) { nsSHistory::UpdatePrefs(); @@ -201,7 +187,7 @@ nsSHistoryObserver::Observe(nsISupports *aSubject, const char *aTopic, namespace { already_AddRefed -GetContentViewerForTransaction(nsISHTransaction *aTrans) +GetContentViewerForTransaction(nsISHTransaction* aTrans) { nsCOMPtr entry; aTrans->GetSHEntry(getter_AddRefs(entry)); @@ -217,7 +203,7 @@ GetContentViewerForTransaction(nsISHTransaction *aTrans) } void -EvictContentViewerForTransaction(nsISHTransaction *aTrans) +EvictContentViewerForTransaction(nsISHTransaction* aTrans) { nsCOMPtr entry; aTrans->GetSHEntry(getter_AddRefs(entry)); @@ -226,12 +212,12 @@ EvictContentViewerForTransaction(nsISHTransaction *aTrans) entry->GetAnyContentViewer(getter_AddRefs(ownerEntry), getter_AddRefs(viewer)); if (viewer) { - NS_ASSERTION(ownerEntry, - "Content viewer exists but its SHEntry is null"); + NS_ASSERTION(ownerEntry, "Content viewer exists but its SHEntry is null"); LOG_SHENTRY_SPEC(("Evicting content viewer 0x%p for " "owning SHEntry 0x%p at %s.", - viewer.get(), ownerEntry.get(), _spec), ownerEntry); + viewer.get(), ownerEntry.get(), _spec), + ownerEntry); // Drop the presentation state before destroying the viewer, so that // document teardown is able to correctly persist the state. @@ -243,41 +229,31 @@ EvictContentViewerForTransaction(nsISHTransaction *aTrans) } // anonymous namespace -//***************************************************************************** -//*** nsSHistory: Object Management -//***************************************************************************** - -nsSHistory::nsSHistory() : mListRoot(nullptr), mIndex(-1), mLength(0), mRequestedIndex(-1) +nsSHistory::nsSHistory() + : mIndex(-1) + , mLength(0) + , mRequestedIndex(-1) { // Add this new SHistory object to the list PR_APPEND_LINK(this, &gSHistoryList); } - nsSHistory::~nsSHistory() { // Remove this SHistory object from the list PR_REMOVE_LINK(this); } -//***************************************************************************** -// nsSHistory: nsISupports -//***************************************************************************** - NS_IMPL_ADDREF(nsSHistory) NS_IMPL_RELEASE(nsSHistory) NS_INTERFACE_MAP_BEGIN(nsSHistory) - NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISHistory) - NS_INTERFACE_MAP_ENTRY(nsISHistory) - NS_INTERFACE_MAP_ENTRY(nsIWebNavigation) - NS_INTERFACE_MAP_ENTRY(nsISHistoryInternal) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISHistory) + NS_INTERFACE_MAP_ENTRY(nsISHistory) + NS_INTERFACE_MAP_ENTRY(nsIWebNavigation) + NS_INTERFACE_MAP_ENTRY(nsISHistoryInternal) NS_INTERFACE_MAP_END -//***************************************************************************** -// nsSHistory: nsISHistory -//***************************************************************************** - // static uint32_t nsSHistory::CalcMaxTotalViewers() @@ -301,14 +277,16 @@ nsSHistory::CalcMaxTotalViewers() // 4096 Mb 8 uint64_t bytes = PR_GetPhysicalMemorySize(); - if (bytes == 0) + if (bytes == 0) { return 0; + } // Conversion from unsigned int64_t to double doesn't work on all platforms. // We need to truncate the value at INT64_MAX to make sure we don't // overflow. - if (bytes > INT64_MAX) + if (bytes > INT64_MAX) { bytes = INT64_MAX; + } double kBytesD = (double)(bytes >> 10); @@ -316,10 +294,10 @@ nsSHistory::CalcMaxTotalViewers() // except that we divide the final memory calculation by 4, since // we assume each ContentViewer takes on average 4MB uint32_t viewers = 0; - double x = std::log(kBytesD)/std::log(2.0) - 14; + double x = std::log(kBytesD) / std::log(2.0) - 14; if (x > 0) { - viewers = (uint32_t)(x * x - x + 2.001); // add .001 for rounding - viewers /= 4; + viewers = (uint32_t)(x * x - x + 2.001); // add .001 for rounding + viewers /= 4; } // Cap it off at 8 max @@ -356,7 +334,7 @@ nsSHistory::Startup() if (gHistoryMaxSize < defaultHistoryMaxSize) { gHistoryMaxSize = defaultHistoryMaxSize; } - + // Allow the user to override the max total number of cached viewers, // but keep the per SHistory cached viewer limit constant if (!gObserver) { @@ -368,8 +346,7 @@ nsSHistory::Startup() if (obsSvc) { // Observe empty-cache notifications so tahat clearing the disk/memory // cache will also evict all content viewers. - obsSvc->AddObserver(gObserver, - "cacheservice:empty-cache", false); + obsSvc->AddObserver(gObserver, "cacheservice:empty-cache", false); // Same for memory-pressure notifications obsSvc->AddObserver(gObserver, "memory-pressure", false); @@ -397,34 +374,36 @@ nsSHistory::Shutdown() } } -/* Add an entry to the History list at mIndex and +/* Add an entry to the History list at mIndex and * increment the index to point to the new entry */ NS_IMETHODIMP -nsSHistory::AddEntry(nsISHEntry * aSHEntry, bool aPersist) +nsSHistory::AddEntry(nsISHEntry* aSHEntry, bool aPersist) { NS_ENSURE_ARG(aSHEntry); nsCOMPtr currentTxn; - if(mListRoot) + if (mListRoot) { GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn)); + } bool currentPersist = true; - if(currentTxn) + if (currentTxn) { currentTxn->GetPersist(¤tPersist); + } int32_t currentIndex = mIndex; - if(!currentPersist) - { + if (!currentPersist) { NOTIFY_LISTENERS(OnHistoryReplaceEntry, (currentIndex)); - NS_ENSURE_SUCCESS(currentTxn->SetSHEntry(aSHEntry),NS_ERROR_FAILURE); + NS_ENSURE_SUCCESS(currentTxn->SetSHEntry(aSHEntry), NS_ERROR_FAILURE); currentTxn->SetPersist(aPersist); return NS_OK; } - nsCOMPtr txn(do_CreateInstance(NS_SHTRANSACTION_CONTRACTID)); + nsCOMPtr txn( + do_CreateInstance(NS_SHTRANSACTION_CONTRACTID)); NS_ENSURE_TRUE(txn, NS_ERROR_FAILURE); nsCOMPtr uri; @@ -437,31 +416,33 @@ nsSHistory::AddEntry(nsISHEntry * aSHEntry, bool aPersist) GetTransactionAtIndex(mIndex, getter_AddRefs(currentTxn)); } - // Set the ShEntry and parent for the transaction. setting the + // Set the ShEntry and parent for the transaction. setting the // parent will properly set the parent child relationship txn->SetPersist(aPersist); NS_ENSURE_SUCCESS(txn->Create(aSHEntry, currentTxn), NS_ERROR_FAILURE); - + // A little tricky math here... Basically when adding an object regardless of // what the length was before, it should always be set back to the current and // lop off the forward. mLength = (++mIndex + 1); // If this is the very first transaction, initialize the list - if(!mListRoot) + if (!mListRoot) { mListRoot = txn; + } // Purge History list if it is too long - if ((gHistoryMaxSize >= 0) && (mLength > gHistoryMaxSize)) - PurgeHistory(mLength-gHistoryMaxSize); - + if (gHistoryMaxSize >= 0 && mLength > gHistoryMaxSize) { + PurgeHistory(mLength - gHistoryMaxSize); + } + RemoveDynEntries(mIndex - 1, mIndex); return NS_OK; } /* Get size of the history list */ NS_IMETHODIMP -nsSHistory::GetCount(int32_t * aResult) +nsSHistory::GetCount(int32_t* aResult) { NS_ENSURE_ARG_POINTER(aResult); *aResult = mLength; @@ -470,7 +451,7 @@ nsSHistory::GetCount(int32_t * aResult) /* Get index of the history list */ NS_IMETHODIMP -nsSHistory::GetIndex(int32_t * aResult) +nsSHistory::GetIndex(int32_t* aResult) { NS_PRECONDITION(aResult, "null out param?"); *aResult = mIndex; @@ -479,7 +460,7 @@ nsSHistory::GetIndex(int32_t * aResult) /* Get the requestedIndex */ NS_IMETHODIMP -nsSHistory::GetRequestedIndex(int32_t * aResult) +nsSHistory::GetRequestedIndex(int32_t* aResult) { NS_PRECONDITION(aResult, "null out param?"); *aResult = mRequestedIndex; @@ -488,7 +469,8 @@ nsSHistory::GetRequestedIndex(int32_t * aResult) /* Get the entry at a given index */ NS_IMETHODIMP -nsSHistory::GetEntryAtIndex(int32_t aIndex, bool aModifyIndex, nsISHEntry** aResult) +nsSHistory::GetEntryAtIndex(int32_t aIndex, bool aModifyIndex, + nsISHEntry** aResult) { nsresult rv; nsCOMPtr txn; @@ -496,45 +478,47 @@ nsSHistory::GetEntryAtIndex(int32_t aIndex, bool aModifyIndex, nsISHEntry** aRes /* GetTransactionAtIndex ensures aResult is valid and validates aIndex */ rv = GetTransactionAtIndex(aIndex, getter_AddRefs(txn)); if (NS_SUCCEEDED(rv) && txn) { - //Get the Entry from the transaction + // Get the Entry from the transaction rv = txn->GetSHEntry(aResult); if (NS_SUCCEEDED(rv) && (*aResult)) { // Set mIndex to the requested index, if asked to do so.. if (aModifyIndex) { mIndex = aIndex; } - } //entry - } //Transaction + } + } return rv; } /* Get the transaction at a given index */ NS_IMETHODIMP -nsSHistory::GetTransactionAtIndex(int32_t aIndex, nsISHTransaction ** aResult) +nsSHistory::GetTransactionAtIndex(int32_t aIndex, nsISHTransaction** aResult) { nsresult rv; NS_ENSURE_ARG_POINTER(aResult); - if ((mLength <= 0) || (aIndex < 0) || (aIndex >= mLength)) + if (mLength <= 0 || aIndex < 0 || aIndex >= mLength) { return NS_ERROR_FAILURE; + } - if (!mListRoot) + if (!mListRoot) { return NS_ERROR_FAILURE; + } - if (aIndex == 0) - { + if (aIndex == 0) { *aResult = mListRoot; NS_ADDREF(*aResult); return NS_OK; - } - int32_t cnt=0; - nsCOMPtr tempPtr; + } + int32_t cnt = 0; + nsCOMPtr tempPtr; rv = GetRootTransaction(getter_AddRefs(tempPtr)); - if (NS_FAILED(rv) || !tempPtr) + if (NS_FAILED(rv) || !tempPtr) { return NS_ERROR_FAILURE; + } - while(1) { + while (true) { nsCOMPtr ptr; rv = tempPtr->GetNext(getter_AddRefs(ptr)); if (NS_SUCCEEDED(rv) && ptr) { @@ -542,23 +526,22 @@ nsSHistory::GetTransactionAtIndex(int32_t aIndex, nsISHTransaction ** aResult) if (cnt == aIndex) { ptr.forget(aResult); break; - } - else { + } else { tempPtr = ptr; continue; } - } //NS_SUCCEEDED - else + } else { return NS_ERROR_FAILURE; - } // while - + } + } + return NS_OK; } - /* Get the index of a given entry */ NS_IMETHODIMP -nsSHistory::GetIndexOfEntry(nsISHEntry* aSHEntry, int32_t* aResult) { +nsSHistory::GetIndexOfEntry(nsISHEntry* aSHEntry, int32_t* aResult) +{ NS_ENSURE_ARG(aSHEntry); NS_ENSURE_ARG_POINTER(aResult); *aResult = -1; @@ -598,31 +581,32 @@ nsSHistory::GetIndexOfEntry(nsISHEntry* aSHEntry, int32_t* aResult) { return NS_OK; } - #ifdef DEBUG nsresult nsSHistory::PrintHistory() { - - nsCOMPtr txn; + nsCOMPtr txn; int32_t index = 0; nsresult rv; - if (!mListRoot) + if (!mListRoot) { return NS_ERROR_FAILURE; + } txn = mListRoot; - + while (1) { - if (!txn) + if (!txn) { break; - nsCOMPtr entry; + } + nsCOMPtr entry; rv = txn->GetSHEntry(getter_AddRefs(entry)); - if (NS_FAILED(rv) && !entry) + if (NS_FAILED(rv) && !entry) { return NS_ERROR_FAILURE; + } nsCOMPtr layoutHistoryState; - nsCOMPtr uri; + nsCOMPtr uri; nsXPIDLString title; entry->GetLayoutHistoryState(getter_AddRefs(layoutHistoryState)); @@ -631,8 +615,9 @@ nsSHistory::PrintHistory() #if 0 nsAutoCString url; - if (uri) - uri->GetSpec(url); + if (uri) { + uri->GetSpec(url); + } printf("**** SH Transaction #%d, Entry = %x\n", index, entry.get()); printf("\t\t URL = %s\n", url.get()); @@ -647,28 +632,27 @@ nsSHistory::PrintHistory() txn = next; index++; continue; - } - else + } else { break; + } } return NS_OK; } #endif - NS_IMETHODIMP -nsSHistory::GetRootTransaction(nsISHTransaction ** aResult) +nsSHistory::GetRootTransaction(nsISHTransaction** aResult) { NS_ENSURE_ARG_POINTER(aResult); - *aResult=mListRoot; + *aResult = mListRoot; NS_IF_ADDREF(*aResult); return NS_OK; } /* Get the max size of the history list */ NS_IMETHODIMP -nsSHistory::GetMaxLength(int32_t * aResult) +nsSHistory::GetMaxLength(int32_t* aResult) { NS_ENSURE_ARG_POINTER(aResult); *aResult = gHistoryMaxSize; @@ -679,23 +663,26 @@ nsSHistory::GetMaxLength(int32_t * aResult) NS_IMETHODIMP nsSHistory::SetMaxLength(int32_t aMaxSize) { - if (aMaxSize < 0) + if (aMaxSize < 0) { return NS_ERROR_ILLEGAL_VALUE; + } gHistoryMaxSize = aMaxSize; - if (mLength > aMaxSize) - PurgeHistory(mLength-aMaxSize); + if (mLength > aMaxSize) { + PurgeHistory(mLength - aMaxSize); + } return NS_OK; } NS_IMETHODIMP nsSHistory::PurgeHistory(int32_t aEntries) { - if (mLength <= 0 || aEntries <= 0) + if (mLength <= 0 || aEntries <= 0) { return NS_ERROR_FAILURE; + } aEntries = std::min(aEntries, mLength); - + bool purgeHistory = true; NOTIFY_LISTENERS_CANCELABLE(OnHistoryPurge, purgeHistory, (aEntries, &purgeHistory)); @@ -716,7 +703,7 @@ nsSHistory::PurgeHistory(int32_t aEntries) if (mListRoot) { mListRoot->SetPrev(nullptr); } - cnt++; + cnt++; } mLength -= cnt; mIndex -= cnt; @@ -727,57 +714,58 @@ nsSHistory::PurgeHistory(int32_t aEntries) mIndex = -1; } - if (mRootDocShell) + if (mRootDocShell) { mRootDocShell->HistoryPurged(cnt); + } return NS_OK; } - NS_IMETHODIMP -nsSHistory::AddSHistoryListener(nsISHistoryListener * aListener) +nsSHistory::AddSHistoryListener(nsISHistoryListener* aListener) { NS_ENSURE_ARG_POINTER(aListener); // Check if the listener supports Weak Reference. This is a must. - // This listener functionality is used by embedders and we want to + // This listener functionality is used by embedders and we want to // have the right ownership with who ever listens to SHistory nsWeakPtr listener = do_GetWeakReference(aListener); - if (!listener) return NS_ERROR_FAILURE; + if (!listener) { + return NS_ERROR_FAILURE; + } return mListeners.AppendElementUnlessExists(listener) ? NS_OK : NS_ERROR_OUT_OF_MEMORY; } - NS_IMETHODIMP -nsSHistory::RemoveSHistoryListener(nsISHistoryListener * aListener) +nsSHistory::RemoveSHistoryListener(nsISHistoryListener* aListener) { // Make sure the listener that wants to be removed is the - // one we have in store. + // one we have in store. nsWeakPtr listener = do_GetWeakReference(aListener); mListeners.RemoveElement(listener); return NS_OK; } - /* Replace an entry in the History list at a particular index. * Do not update index or count. */ NS_IMETHODIMP -nsSHistory::ReplaceEntry(int32_t aIndex, nsISHEntry * aReplaceEntry) +nsSHistory::ReplaceEntry(int32_t aIndex, nsISHEntry* aReplaceEntry) { NS_ENSURE_ARG(aReplaceEntry); nsresult rv; nsCOMPtr currentTxn; - if (!mListRoot) // Session History is not initialised. + if (!mListRoot) { + // Session History is not initialised. return NS_ERROR_FAILURE; + } rv = GetTransactionAtIndex(aIndex, getter_AddRefs(currentTxn)); - if(currentTxn) - { + if (currentTxn) { NOTIFY_LISTENERS(OnHistoryReplaceEntry, (aIndex)); // Set the replacement entry in the transaction @@ -815,35 +803,30 @@ nsSHistory::EvictAllContentViewers() while (trans) { EvictContentViewerForTransaction(trans); - nsISHTransaction *temp = trans; + nsISHTransaction* temp = trans; temp->GetNext(getter_AddRefs(trans)); } return NS_OK; } - - -//***************************************************************************** -// nsSHistory: nsIWebNavigation -//***************************************************************************** - NS_IMETHODIMP -nsSHistory::GetCanGoBack(bool * aCanGoBack) +nsSHistory::GetCanGoBack(bool* aCanGoBack) { NS_ENSURE_ARG_POINTER(aCanGoBack); *aCanGoBack = false; int32_t index = -1; NS_ENSURE_SUCCESS(GetIndex(&index), NS_ERROR_FAILURE); - if(index > 0) - *aCanGoBack = true; + if (index > 0) { + *aCanGoBack = true; + } return NS_OK; } NS_IMETHODIMP -nsSHistory::GetCanGoForward(bool * aCanGoForward) +nsSHistory::GetCanGoForward(bool* aCanGoForward) { NS_ENSURE_ARG_POINTER(aCanGoForward); *aCanGoForward = false; @@ -854,8 +837,9 @@ nsSHistory::GetCanGoForward(bool * aCanGoForward) NS_ENSURE_SUCCESS(GetIndex(&index), NS_ERROR_FAILURE); NS_ENSURE_SUCCESS(GetCount(&count), NS_ERROR_FAILURE); - if((index >= 0) && (index < (count - 1))) + if (index >= 0 && index < (count - 1)) { *aCanGoForward = true; + } return NS_OK; } @@ -866,50 +850,41 @@ nsSHistory::GoBack() bool canGoBack = false; GetCanGoBack(&canGoBack); - if (!canGoBack) // Can't go back + if (!canGoBack) { return NS_ERROR_UNEXPECTED; - return LoadEntry(mIndex-1, nsIDocShellLoadInfo::loadHistory, HIST_CMD_BACK); + } + return LoadEntry(mIndex - 1, nsIDocShellLoadInfo::loadHistory, HIST_CMD_BACK); } - NS_IMETHODIMP nsSHistory::GoForward() { bool canGoForward = false; GetCanGoForward(&canGoForward); - if (!canGoForward) // Can't go forward + if (!canGoForward) { return NS_ERROR_UNEXPECTED; - return LoadEntry(mIndex+1, nsIDocShellLoadInfo::loadHistory, HIST_CMD_FORWARD); + } + return LoadEntry(mIndex + 1, nsIDocShellLoadInfo::loadHistory, + HIST_CMD_FORWARD); } NS_IMETHODIMP nsSHistory::Reload(uint32_t aReloadFlags) { nsDocShellInfoLoadType loadType; - if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY && - aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE) - { + if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY && + aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE) { loadType = nsIDocShellLoadInfo::loadReloadBypassProxyAndCache; - } - else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY) - { + } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_PROXY) { loadType = nsIDocShellLoadInfo::loadReloadBypassProxy; - } - else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE) - { + } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE) { loadType = nsIDocShellLoadInfo::loadReloadBypassCache; - } - else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_CHARSET_CHANGE) - { + } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_CHARSET_CHANGE) { loadType = nsIDocShellLoadInfo::loadReloadCharsetChange; - } - else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_ALLOW_MIXED_CONTENT) - { + } else if (aReloadFlags & nsIWebNavigation::LOAD_FLAGS_ALLOW_MIXED_CONTENT) { loadType = nsIDocShellLoadInfo::loadReloadMixedContent; - } - else - { + } else { loadType = nsIDocShellLoadInfo::loadReloadNormal; } @@ -922,8 +897,9 @@ nsSHistory::Reload(uint32_t aReloadFlags) GetCurrentURI(getter_AddRefs(currentURI)); NOTIFY_LISTENERS_CANCELABLE(OnHistoryReload, canNavigate, (currentURI, aReloadFlags, &canNavigate)); - if (!canNavigate) + if (!canNavigate) { return NS_OK; + } return LoadEntry(mIndex, loadType, HIST_CMD_RELOAD); } @@ -937,8 +913,9 @@ nsSHistory::ReloadCurrentEntry() GetCurrentURI(getter_AddRefs(currentURI)); NOTIFY_LISTENERS_CANCELABLE(OnHistoryGotoIndex, canNavigate, (mIndex, currentURI, &canNavigate)); - if (!canNavigate) + if (!canNavigate) { return NS_OK; + } return LoadEntry(mIndex, nsIDocShellLoadInfo::loadHistory, HIST_CMD_RELOAD); } @@ -992,7 +969,7 @@ nsSHistory::EvictOutOfRangeWindowContentViewers(int32_t aIndex) LOG(("EvictOutOfRangeWindowContentViewers(index=%d), " "mLength=%d. Safe range [%d, %d]", - aIndex, mLength, startSafeIndex, endSafeIndex)); + aIndex, mLength, startSafeIndex, endSafeIndex)); // The content viewers in range aIndex -/+ gHistoryMaxViewers will not be // evicted. Collect a set of them so we don't accidentally evict one of them @@ -1003,7 +980,7 @@ nsSHistory::EvictOutOfRangeWindowContentViewers(int32_t aIndex) for (int32_t i = startSafeIndex; trans && i <= endSafeIndex; i++) { nsCOMPtr viewer = GetContentViewerForTransaction(trans); safeViewers.AppendObject(viewer); - nsISHTransaction *temp = trans; + nsISHTransaction* temp = trans; temp->GetNext(getter_AddRefs(trans)); } @@ -1015,7 +992,7 @@ nsSHistory::EvictOutOfRangeWindowContentViewers(int32_t aIndex) EvictContentViewerForTransaction(trans); } - nsISHTransaction *temp = trans; + nsISHTransaction* temp = trans; temp->GetNext(getter_AddRefs(trans)); } } @@ -1025,7 +1002,7 @@ namespace { class TransactionAndDistance { public: - TransactionAndDistance(nsISHTransaction *aTrans, uint32_t aDist) + TransactionAndDistance(nsISHTransaction* aTrans, uint32_t aDist) : mTransaction(aTrans) , mDistance(aDist) { @@ -1044,7 +1021,7 @@ public: } } - bool operator<(const TransactionAndDistance &aOther) const + bool operator<(const TransactionAndDistance& aOther) const { // Compare distances first, and fall back to last-accessed times. if (aOther.mDistance != this->mDistance) { @@ -1054,7 +1031,7 @@ public: return this->mLastTouched < aOther.mLastTouched; } - bool operator==(const TransactionAndDistance &aOther) const + bool operator==(const TransactionAndDistance& aOther) const { // This is a little silly; we need == so the default comaprator can be // instantiated, but this function is never actually called when we sort @@ -1071,7 +1048,7 @@ public: } // anonymous namespace -//static +// static void nsSHistory::GloballyEvictContentViewers() { @@ -1105,7 +1082,7 @@ nsSHistory::GloballyEvictContentViewers() // int32_t startIndex = std::max(0, shist->mIndex - gHistoryMaxViewers); int32_t endIndex = std::min(shist->mLength - 1, - shist->mIndex + gHistoryMaxViewers); + shist->mIndex + gHistoryMaxViewers); nsCOMPtr trans; shist->GetTransactionAtIndex(startIndex, getter_AddRefs(trans)); for (int32_t i = startIndex; trans && i <= endIndex; i++) { @@ -1119,23 +1096,25 @@ nsSHistory::GloballyEvictContentViewers() // distance from the SHistory's index and continue. bool found = false; for (uint32_t j = 0; j < shTransactions.Length(); j++) { - TransactionAndDistance &container = shTransactions[j]; + TransactionAndDistance& container = shTransactions[j]; if (container.mViewer == contentViewer) { - container.mDistance = std::min(container.mDistance, DeprecatedAbs(i - shist->mIndex)); + container.mDistance = std::min(container.mDistance, + DeprecatedAbs(i - shist->mIndex)); found = true; break; } } - // If we didn't find a TransactionAndDistance for this content viewer, make a new - // one. + // If we didn't find a TransactionAndDistance for this content viewer, + // make a new one. if (!found) { - TransactionAndDistance container(trans, DeprecatedAbs(i - shist->mIndex)); + TransactionAndDistance container(trans, + DeprecatedAbs(i - shist->mIndex)); shTransactions.AppendElement(container); } } - nsISHTransaction *temp = trans; + nsISHTransaction* temp = trans; temp->GetNext(getter_AddRefs(trans)); } @@ -1157,20 +1136,17 @@ nsSHistory::GloballyEvictContentViewers() // so let's not worry about it.) transactions.Sort(); - for (int32_t i = transactions.Length() - 1; - i >= sHistoryMaxTotalViewers; --i) { - + for (int32_t i = transactions.Length() - 1; i >= sHistoryMaxTotalViewers; + --i) { EvictContentViewerForTransaction(transactions[i].mTransaction); - } } nsresult -nsSHistory::EvictExpiredContentViewerForEntry(nsIBFCacheEntry *aEntry) +nsSHistory::EvictExpiredContentViewerForEntry(nsIBFCacheEntry* aEntry) { int32_t startIndex = std::max(0, mIndex - gHistoryMaxViewers); - int32_t endIndex = std::min(mLength - 1, - mIndex + gHistoryMaxViewers); + int32_t endIndex = std::min(mLength - 1, mIndex + gHistoryMaxViewers); nsCOMPtr trans; GetTransactionAtIndex(startIndex, getter_AddRefs(trans)); @@ -1184,12 +1160,13 @@ nsSHistory::EvictExpiredContentViewerForEntry(nsIBFCacheEntry *aEntry) break; } - nsISHTransaction *temp = trans; + nsISHTransaction* temp = trans; temp->GetNext(getter_AddRefs(trans)); } - if (i > endIndex) + if (i > endIndex) { return NS_OK; - + } + if (i == mIndex) { NS_WARNING("How did the current SHEntry expire?"); return NS_OK; @@ -1205,7 +1182,7 @@ nsSHistory::EvictExpiredContentViewerForEntry(nsIBFCacheEntry *aEntry) // objects for each viewer to be evicted. However, this method is called // infrequently -- only when the disk or memory cache is cleared. -//static +// static void nsSHistory::GloballyEvictAllContentViewers() { @@ -1215,9 +1192,10 @@ nsSHistory::GloballyEvictAllContentViewers() sHistoryMaxTotalViewers = maxViewers; } -void GetDynamicChildren(nsISHContainer* aContainer, - nsTArray& aDocshellIDs, - bool aOnlyTopLevelDynamic) +void +GetDynamicChildren(nsISHContainer* aContainer, + nsTArray& aDocshellIDs, + bool aOnlyTopLevelDynamic) { int32_t count = 0; aContainer->GetChildCount(&count); @@ -1277,8 +1255,9 @@ RemoveFromSessionHistoryContainer(nsISHContainer* aContainer, return didRemove; } -bool RemoveChildEntries(nsISHistory* aHistory, int32_t aIndex, - nsTArray& aEntryIDs) +bool +RemoveChildEntries(nsISHistory* aHistory, int32_t aIndex, + nsTArray& aEntryIDs) { nsCOMPtr rootHE; aHistory->GetEntryAtIndex(aIndex, false, getter_AddRefs(rootHE)); @@ -1286,7 +1265,8 @@ bool RemoveChildEntries(nsISHistory* aHistory, int32_t aIndex, return root ? RemoveFromSessionHistoryContainer(root, aEntryIDs) : false; } -bool IsSameTree(nsISHEntry* aEntry1, nsISHEntry* aEntry2) +bool +IsSameTree(nsISHEntry* aEntry1, nsISHEntry* aEntry2) { if (!aEntry1 && !aEntry2) { return true; @@ -1316,7 +1296,7 @@ bool IsSameTree(nsISHEntry* aEntry1, nsISHEntry* aEntry2) return false; } } - + return true; } @@ -1391,11 +1371,13 @@ NS_IMETHODIMP_(void) nsSHistory::RemoveEntries(nsTArray& aIDs, int32_t aStartIndex) { int32_t index = aStartIndex; - while(index >= 0 && RemoveChildEntries(this, --index, aIDs)); + while (index >= 0 && RemoveChildEntries(this, --index, aIDs)) { + } int32_t minIndex = index; index = aStartIndex; - while(index >= 0 && RemoveChildEntries(this, index++, aIDs)); - + while (index >= 0 && RemoveChildEntries(this, index++, aIDs)) { + } + // We need to remove duplicate nsSHEntry trees. bool didRemove = false; while (index > minIndex) { @@ -1447,7 +1429,7 @@ nsSHistory::RemoveDynEntries(int32_t aOldIndex, int32_t aNewIndex) NS_IMETHODIMP nsSHistory::UpdateIndex() { - // Update the actual index with the right value. + // Update the actual index with the right value. if (mIndex != mRequestedIndex && mRequestedIndex != -1) { RemoveDynEntries(mIndex, mRequestedIndex); mIndex = mRequestedIndex; @@ -1460,11 +1442,10 @@ nsSHistory::UpdateIndex() NS_IMETHODIMP nsSHistory::Stop(uint32_t aStopFlags) { - //Not implemented + // Not implemented return NS_OK; } - NS_IMETHODIMP nsSHistory::GetDocument(nsIDOMDocument** aDocument) { @@ -1472,7 +1453,6 @@ nsSHistory::GetDocument(nsIDOMDocument** aDocument) return NS_OK; } - NS_IMETHODIMP nsSHistory::GetCurrentURI(nsIURI** aResultURI) { @@ -1481,12 +1461,13 @@ nsSHistory::GetCurrentURI(nsIURI** aResultURI) nsCOMPtr currentEntry; rv = GetEntryAtIndex(mIndex, false, getter_AddRefs(currentEntry)); - if (NS_FAILED(rv) && !currentEntry) return rv; + if (NS_FAILED(rv) && !currentEntry) { + return rv; + } rv = currentEntry->GetURI(aResultURI); return rv; } - NS_IMETHODIMP nsSHistory::GetReferringURI(nsIURI** aURI) { @@ -1495,7 +1476,6 @@ nsSHistory::GetReferringURI(nsIURI** aURI) return NS_OK; } - NS_IMETHODIMP nsSHistory::SetSessionHistory(nsISHistory* aSessionHistory) { @@ -1503,7 +1483,6 @@ nsSHistory::SetSessionHistory(nsISHistory* aSessionHistory) return NS_OK; } - NS_IMETHODIMP nsSHistory::GetSessionHistory(nsISHistory** aSessionHistory) { @@ -1536,11 +1515,13 @@ nsSHistory::LoadURI(const char16_t* aURI, NS_IMETHODIMP nsSHistory::GotoIndex(int32_t aIndex) { - return LoadEntry(aIndex, nsIDocShellLoadInfo::loadHistory, HIST_CMD_GOTOINDEX); + return LoadEntry(aIndex, nsIDocShellLoadInfo::loadHistory, + HIST_CMD_GOTOINDEX); } nsresult -nsSHistory::LoadNextPossibleEntry(int32_t aNewIndex, long aLoadType, uint32_t aHistCmd) +nsSHistory::LoadNextPossibleEntry(int32_t aNewIndex, long aLoadType, + uint32_t aHistCmd) { mRequestedIndex = -1; if (aNewIndex < mIndex) { @@ -1597,42 +1578,42 @@ nsSHistory::LoadEntry(int32_t aIndex, long aLoadType, uint32_t aHistCmd) } if (!canNavigate) { - // If the listener asked us not to proceed with - // the operation, simply return. + // If the listener asked us not to proceed with + // the operation, simply return. mRequestedIndex = -1; return NS_OK; // XXX Maybe I can return some other error code? } nsCOMPtr nexturi; - int32_t pCount=0, nCount=0; + int32_t pCount = 0; + int32_t nCount = 0; nsCOMPtr prevAsContainer(do_QueryInterface(prevEntry)); nsCOMPtr nextAsContainer(do_QueryInterface(nextEntry)); if (prevAsContainer && nextAsContainer) { prevAsContainer->GetChildCount(&pCount); nextAsContainer->GetChildCount(&nCount); } - + nsCOMPtr loadInfo; if (mRequestedIndex == mIndex) { - // Possibly a reload case + // Possibly a reload case docShell = mRootDocShell; - } - else { + } else { // Going back or forward. - if ((pCount > 0) && (nCount > 0)) { - /* THis is a subframe navigation. Go find + if (pCount > 0 && nCount > 0) { + /* THis is a subframe navigation. Go find * the docshell in which load should happen */ bool frameFound = false; - nsresult rv = CompareFrames(prevEntry, nextEntry, mRootDocShell, aLoadType, &frameFound); + nsresult rv = CompareFrames(prevEntry, nextEntry, mRootDocShell, + aLoadType, &frameFound); if (!frameFound) { // We did not successfully find the subframe in which // the new url was to be loaded. Go further in the history. return LoadNextPossibleEntry(aIndex, aLoadType, aHistCmd); } return rv; - } // (pCount >0) - else { + } else { // Loading top level page. uint32_t prevID = 0; uint32_t nextID = 0; @@ -1659,10 +1640,13 @@ nsSHistory::LoadEntry(int32_t aIndex, long aLoadType, uint32_t aHistCmd) } nsresult -nsSHistory::CompareFrames(nsISHEntry * aPrevEntry, nsISHEntry * aNextEntry, nsIDocShell * aParent, long aLoadType, bool * aIsFrameFound) +nsSHistory::CompareFrames(nsISHEntry* aPrevEntry, nsISHEntry* aNextEntry, + nsIDocShell* aParent, long aLoadType, + bool* aIsFrameFound) { - if (!aPrevEntry || !aNextEntry || !aParent) + if (!aPrevEntry || !aNextEntry || !aParent) { return NS_ERROR_FAILURE; + } // We should be comparing only entries which were created for the // same docshell. This is here to just prevent anything strange happening. @@ -1677,27 +1661,29 @@ nsSHistory::CompareFrames(nsISHEntry * aPrevEntry, nsISHEntry * aNextEntry, nsID aPrevEntry->GetID(&prevID); aNextEntry->GetID(&nextID); - + // Check the IDs to verify if the pages are different. if (prevID != nextID) { - if (aIsFrameFound) + if (aIsFrameFound) { *aIsFrameFound = true; + } // Set the Subframe flag of the entry to indicate that - // it is subframe navigation + // it is subframe navigation aNextEntry->SetIsSubFrame(true); InitiateLoad(aNextEntry, aParent, aLoadType); return NS_OK; } - /* The root entries are the same, so compare any child frames */ - int32_t pcnt=0, ncnt=0, dsCount=0; - nsCOMPtr prevContainer(do_QueryInterface(aPrevEntry)); - nsCOMPtr nextContainer(do_QueryInterface(aNextEntry)); + // The root entries are the same, so compare any child frames + int32_t pcnt = 0; + int32_t ncnt = 0; + int32_t dsCount = 0; + nsCOMPtr prevContainer(do_QueryInterface(aPrevEntry)); + nsCOMPtr nextContainer(do_QueryInterface(aNextEntry)); - if (!aParent) - return NS_ERROR_FAILURE; - if (!prevContainer || !nextContainer) + if (!aParent || !prevContainer || !nextContainer) { return NS_ERROR_FAILURE; + } prevContainer->GetChildCount(&pcnt); nextContainer->GetChildCount(&ncnt); @@ -1761,13 +1747,13 @@ nsSHistory::CompareFrames(nsISHEntry * aPrevEntry, nsISHEntry * aNextEntry, nsID // This will either load a new page to shell or some subshell or // do nothing. CompareFrames(pChild, nChild, dsChild, aLoadType, aIsFrameFound); - } + } return result; } - -nsresult -nsSHistory::InitiateLoad(nsISHEntry * aFrameEntry, nsIDocShell * aFrameDS, long aLoadType) +nsresult +nsSHistory::InitiateLoad(nsISHEntry* aFrameEntry, nsIDocShell* aFrameDS, + long aLoadType) { NS_ENSURE_STATE(aFrameDS && aFrameEntry); @@ -1777,8 +1763,8 @@ nsSHistory::InitiateLoad(nsISHEntry * aFrameEntry, nsIDocShell * aFrameDS, long * This will be passed on to child subframes later in nsDocShell, * so that proper loadType is maintained through out a frameset */ - aFrameEntry->SetLoadType(aLoadType); - aFrameDS->CreateLoadInfo (getter_AddRefs(loadInfo)); + aFrameEntry->SetLoadType(aLoadType); + aFrameDS->CreateLoadInfo(getter_AddRefs(loadInfo)); loadInfo->SetLoadType(aLoadType); loadInfo->SetSHEntry(aFrameEntry); @@ -1799,12 +1785,13 @@ nsSHistory::InitiateLoad(nsISHEntry * aFrameEntry, nsIDocShell * aFrameDS, long nsCOMPtr nextURI; aFrameEntry->GetURI(getter_AddRefs(nextURI)); // Time to initiate a document load - return aFrameDS->LoadURI(nextURI, loadInfo, nsIWebNavigation::LOAD_FLAGS_NONE, false); + return aFrameDS->LoadURI(nextURI, loadInfo, + nsIWebNavigation::LOAD_FLAGS_NONE, false); } NS_IMETHODIMP -nsSHistory::SetRootDocShell(nsIDocShell * aDocShell) +nsSHistory::SetRootDocShell(nsIDocShell* aDocShell) { mRootDocShell = aDocShell; return NS_OK; @@ -1819,12 +1806,7 @@ nsSHistory::GetSHistoryEnumerator(nsISimpleEnumerator** aEnumerator) return NS_OK; } - -//***************************************************************************** -//*** nsSHEnumerator: Object Management -//***************************************************************************** - -nsSHEnumerator::nsSHEnumerator(nsSHistory * aSHistory):mIndex(-1) +nsSHEnumerator::nsSHEnumerator(nsSHistory* aSHistory) : mIndex(-1) { mSHistory = aSHistory; } @@ -1837,32 +1819,32 @@ nsSHEnumerator::~nsSHEnumerator() NS_IMPL_ISUPPORTS(nsSHEnumerator, nsISimpleEnumerator) NS_IMETHODIMP -nsSHEnumerator::HasMoreElements(bool * aReturn) +nsSHEnumerator::HasMoreElements(bool* aReturn) { int32_t cnt; *aReturn = false; mSHistory->GetCount(&cnt); - if (mIndex >= -1 && mIndex < (cnt-1) ) { + if (mIndex >= -1 && mIndex < (cnt - 1)) { *aReturn = true; } return NS_OK; } - -NS_IMETHODIMP -nsSHEnumerator::GetNext(nsISupports **aItem) +NS_IMETHODIMP +nsSHEnumerator::GetNext(nsISupports** aItem) { NS_ENSURE_ARG_POINTER(aItem); - int32_t cnt= 0; + int32_t cnt = 0; - nsresult result = NS_ERROR_FAILURE; + nsresult result = NS_ERROR_FAILURE; mSHistory->GetCount(&cnt); - if (mIndex < (cnt-1)) { + if (mIndex < (cnt - 1)) { mIndex++; nsCOMPtr hEntry; result = mSHistory->GetEntryAtIndex(mIndex, false, getter_AddRefs(hEntry)); - if (hEntry) + if (hEntry) { result = CallQueryInterface(hEntry, aItem); + } } return result; } diff --git a/docshell/shistory/src/nsSHistory.h b/docshell/shistory/src/nsSHistory.h index 36af8855f6..245e1ebc91 100644 --- a/docshell/shistory/src/nsSHistory.h +++ b/docshell/shistory/src/nsSHistory.h @@ -7,10 +7,7 @@ #ifndef nsSHistory_h #define nsSHistory_h -// Helper Classes #include "nsCOMPtr.h" - -//Interfaces Needed #include "nsISHistory.h" #include "nsISHistoryInternal.h" #include "nsIWebNavigation.h" @@ -18,7 +15,6 @@ #include "nsTObserverArray.h" #include "nsWeakPtr.h" -// Needed to maintain global list of all SHistory objects #include "prclist.h" class nsIDocShell; @@ -34,7 +30,6 @@ class nsSHistory final : public PRCList, { public: nsSHistory(); - NS_DECL_ISUPPORTS NS_DECL_NSISHISTORY NS_DECL_NSISHISTORYINTERNAL @@ -56,15 +51,18 @@ protected: friend class nsSHEnumerator; friend class nsSHistoryObserver; - // Could become part of nsIWebNavigation - NS_IMETHOD GetTransactionAtIndex(int32_t aIndex, nsISHTransaction ** aResult); - nsresult CompareFrames(nsISHEntry * prevEntry, nsISHEntry * nextEntry, nsIDocShell * rootDocShell, long aLoadType, bool * aIsFrameFound); - nsresult InitiateLoad(nsISHEntry * aFrameEntry, nsIDocShell * aFrameDS, long aLoadType); + // Could become part of nsIWebNavigation + NS_IMETHOD GetTransactionAtIndex(int32_t aIndex, nsISHTransaction** aResult); + nsresult CompareFrames(nsISHEntry* aPrevEntry, nsISHEntry* aNextEntry, + nsIDocShell* aRootDocShell, long aLoadType, + bool* aIsFrameFound); + nsresult InitiateLoad(nsISHEntry* aFrameEntry, nsIDocShell* aFrameDS, + long aLoadType); - NS_IMETHOD LoadEntry(int32_t aIndex, long aLoadType, uint32_t histCmd); + NS_IMETHOD LoadEntry(int32_t aIndex, long aLoadType, uint32_t aHistCmd); #ifdef DEBUG - nsresult PrintHistory(); + nsresult PrintHistory(); #endif // Evict content viewers in this window which don't lie in the "safe" range @@ -79,7 +77,9 @@ protected: void RemoveDynEntries(int32_t aOldIndex, int32_t aNewIndex); - nsresult LoadNextPossibleEntry(int32_t aNewIndex, long aLoadType, uint32_t aHistCmd); + nsresult LoadNextPossibleEntry(int32_t aNewIndex, long aLoadType, + uint32_t aHistCmd); + protected: // aIndex is the index of the transaction which may be removed. // If aKeepNext is true, aIndex is compared to aIndex + 1, @@ -93,29 +93,27 @@ protected: // Session History listeners nsAutoTObserverArray mListeners; // Weak reference. Do not refcount this. - nsIDocShell * mRootDocShell; + nsIDocShell* mRootDocShell; // Max viewers allowed total, across all SHistory objects - static int32_t sHistoryMaxTotalViewers; + static int32_t sHistoryMaxTotalViewers; }; -//***************************************************************************** -//*** nsSHEnumerator: Object Management -//***************************************************************************** + class nsSHEnumerator : public nsISimpleEnumerator { public: - NS_DECL_ISUPPORTS NS_DECL_NSISIMPLEENUMERATOR - explicit nsSHEnumerator(nsSHistory * aHistory); - + explicit nsSHEnumerator(nsSHistory* aHistory); + protected: friend class nsSHistory; virtual ~nsSHEnumerator(); + private: - int32_t mIndex; - nsSHistory * mSHistory; + int32_t mIndex; + nsSHistory* mSHistory; }; -#endif /* nsSHistory */ +#endif /* nsSHistory */ diff --git a/dom/base/nsDocument.cpp b/dom/base/nsDocument.cpp index d7a8a391bc..b05fcbf89e 100644 --- a/dom/base/nsDocument.cpp +++ b/dom/base/nsDocument.cpp @@ -2638,15 +2638,8 @@ nsDocument::StartDocumentLoad(const char* aCommand, nsIChannel* aChannel, PR_LogPrint("DOCUMENT %p StartDocumentLoad %s", this, spec.get()); } -#ifdef DEBUG - { - uint32_t appId; - nsresult rv = NodePrincipal()->GetAppId(&appId); - NS_ENSURE_SUCCESS(rv, rv); - MOZ_ASSERT(appId != nsIScriptSecurityManager::UNKNOWN_APP_ID, - "Document should never have UNKNOWN_APP_ID"); - } -#endif + MOZ_ASSERT(NodePrincipal()->GetAppId() != nsIScriptSecurityManager::UNKNOWN_APP_ID, + "Document should never have UNKNOWN_APP_ID"); MOZ_ASSERT(GetReadyStateEnum() == nsIDocument::READYSTATE_UNINITIALIZED, "Bad readyState"); @@ -2853,16 +2846,14 @@ nsDocument::InitCSP(nsIChannel* aChannel) if (appStatus != nsIPrincipal::APP_STATUS_NOT_INSTALLED) { nsCOMPtr appsService = do_GetService(APPS_SERVICE_CONTRACTID); if (appsService) { - uint32_t appId = 0; - if (NS_SUCCEEDED(principal->GetAppId(&appId))) { - appsService->GetManifestCSPByLocalId(appId, appManifestCSP); - if (!appManifestCSP.IsEmpty()) { - applyAppManifestCSP = true; - } - appsService->GetDefaultCSPByLocalId(appId, appDefaultCSP); - if (!appDefaultCSP.IsEmpty()) { - applyAppDefaultCSP = true; - } + uint32_t appId = principal->GetAppId(); + appsService->GetManifestCSPByLocalId(appId, appManifestCSP); + if (!appManifestCSP.IsEmpty()) { + applyAppManifestCSP = true; + } + appsService->GetDefaultCSPByLocalId(appId, appDefaultCSP); + if (!appDefaultCSP.IsEmpty()) { + applyAppDefaultCSP = true; } } } diff --git a/dom/base/nsGlobalWindow.cpp b/dom/base/nsGlobalWindow.cpp index e655c580ec..e429379583 100644 --- a/dom/base/nsGlobalWindow.cpp +++ b/dom/base/nsGlobalWindow.cpp @@ -8461,13 +8461,8 @@ nsGlobalWindow::PostMessageMoz(JSContext* aCx, JS::Handle aMessage, nsCOMPtr principal = nsContentUtils::SubjectPrincipal(); MOZ_ASSERT(principal); - uint32_t appId; - if (NS_WARN_IF(NS_FAILED(principal->GetAppId(&appId)))) - return; - - bool isInBrowser; - if (NS_WARN_IF(NS_FAILED(principal->GetIsInBrowserElement(&isInBrowser)))) - return; + uint32_t appId = principal->GetAppId(); + bool isInBrowser = principal->GetIsInBrowserElement(); // Create a nsIPrincipal inheriting the app/browser attributes from the // caller. diff --git a/dom/storage/DOMStorageManager.cpp b/dom/storage/DOMStorageManager.cpp index c80cdda8de..7fed58ac77 100644 --- a/dom/storage/DOMStorageManager.cpp +++ b/dom/storage/DOMStorageManager.cpp @@ -166,19 +166,9 @@ CreateScopeKey(nsIPrincipal* aPrincipal, key.Append(nsPrintfCString(":%d", port)); } - bool unknownAppId; - rv = aPrincipal->GetUnknownAppId(&unknownAppId); - NS_ENSURE_SUCCESS(rv, rv); - - if (!unknownAppId) { - uint32_t appId; - rv = aPrincipal->GetAppId(&appId); - NS_ENSURE_SUCCESS(rv, rv); - - bool isInBrowserElement; - rv = aPrincipal->GetIsInBrowserElement(&isInBrowserElement); - NS_ENSURE_SUCCESS(rv, rv); - + if (!aPrincipal->GetUnknownAppId()) { + uint32_t appId = aPrincipal->GetAppId(); + bool isInBrowserElement = aPrincipal->GetIsInBrowserElement(); if (appId == nsIScriptSecurityManager::NO_APP_ID && !isInBrowserElement) { aKey.Assign(key); return NS_OK; @@ -221,19 +211,9 @@ CreateQuotaDBKey(nsIPrincipal* aPrincipal, CreateReversedDomain(eTLDplusOne, subdomainsDBKey); - bool unknownAppId; - rv = aPrincipal->GetUnknownAppId(&unknownAppId); - NS_ENSURE_SUCCESS(rv, rv); - - if (!unknownAppId) { - uint32_t appId; - rv = aPrincipal->GetAppId(&appId); - NS_ENSURE_SUCCESS(rv, rv); - - bool isInBrowserElement; - rv = aPrincipal->GetIsInBrowserElement(&isInBrowserElement); - NS_ENSURE_SUCCESS(rv, rv); - + if (!aPrincipal->GetUnknownAppId()) { + uint32_t appId = aPrincipal->GetAppId(); + bool isInBrowserElement = aPrincipal->GetIsInBrowserElement(); if (appId == nsIScriptSecurityManager::NO_APP_ID && !isInBrowserElement) { aKey.Assign(subdomainsDBKey); return NS_OK; diff --git a/embedding/components/webbrowserpersist/nsWebBrowserPersist.cpp b/embedding/components/webbrowserpersist/nsWebBrowserPersist.cpp index c8627eada4..bd6c02acf2 100644 --- a/embedding/components/webbrowserpersist/nsWebBrowserPersist.cpp +++ b/embedding/components/webbrowserpersist/nsWebBrowserPersist.cpp @@ -19,7 +19,7 @@ #include "nsIHttpChannelInternal.h" #include "nsIEncodedChannel.h" #include "nsIUploadChannel.h" -#include "nsICachingChannel.h" +#include "nsICacheInfoChannel.h" #include "nsIFileChannel.h" #include "nsEscape.h" #include "nsUnicharUtils.h" @@ -1276,7 +1276,7 @@ nsresult nsWebBrowserPersist::SaveURIInternal( } // Cache key - nsCOMPtr cacheChannel(do_QueryInterface(httpChannel)); + nsCOMPtr cacheChannel(do_QueryInterface(httpChannel)); if (cacheChannel && cacheKey) { cacheChannel->SetCacheKey(cacheKey); diff --git a/js/public/CallArgs.h b/js/public/CallArgs.h index e600442500..ff92f668ed 100644 --- a/js/public/CallArgs.h +++ b/js/public/CallArgs.h @@ -285,6 +285,7 @@ class MOZ_STACK_CLASS CallArgsBase : { protected: unsigned argc_; + bool constructing_; public: /* Returns the number of arguments. */ @@ -314,13 +315,18 @@ class MOZ_STACK_CLASS CallArgsBase : return i < argc_ && !this->argv_[i].isUndefined(); } + MutableHandleValue newTarget() const { + MOZ_ASSERT(constructing_); + return MutableHandleValue::fromMarkedLocation(&this->argv_[argc_]); + } + public: // These methods are publicly exposed, but we're less sure of the interface // here than we'd like (because they're hackish and drop assertions). Try // to avoid using these if you can. Value* array() const { return this->argv_; } - Value* end() const { return this->argv_ + argc_; } + Value* end() const { return this->argv_ + argc_ + constructing_; } }; } // namespace detail @@ -329,13 +335,14 @@ class MOZ_STACK_CLASS CallArgs : public detail::CallArgsBasegetOp() == JSOP_NEW || pn->getOp() == JSOP_SPREADNEW; + /* * Emit code for each argument in order, then emit the JSOP_*CALL or * JSOP_NEW bytecode with a two-byte immediate telling how many args @@ -6405,9 +6407,20 @@ BytecodeEmitter::emitCallOrNew(ParseNode* pn) if (!emitTree(pn3)) return false; } + + if (isNewOp) { + // Repush the callee as new.target + if (!emitDupAt(this->stackDepth - 1 - (argc + 1))) + return false; + } } else { if (!emitArray(pn2->pn_next, argc, JSOP_SPREADCALLARRAY)) return false; + + if (isNewOp) { + if (!emitDupAt(this->stackDepth - 1 - 2)) + return false; + } } emittingForInit = oldEmittingForInit; diff --git a/js/src/jit-test/tests/basic/newTargetRectifier.js b/js/src/jit-test/tests/basic/newTargetRectifier.js new file mode 100644 index 0000000000..78716869fb --- /dev/null +++ b/js/src/jit-test/tests/basic/newTargetRectifier.js @@ -0,0 +1,12 @@ +function testBailoutNewTarget() { + function Inner(ex, forceRectifier) { + bailout(); + assertEq(new.target, ex); + } + + for (let i = 0; i < 1100; i++) + new Inner(Inner); +} + +for (let i = 0; i < 15; i++) + testBailoutNewTarget(); diff --git a/js/src/jit-test/tests/debug/Frame-newTargetOverflow-01.js b/js/src/jit-test/tests/debug/Frame-newTargetOverflow-01.js new file mode 100644 index 0000000000..2a413404c1 --- /dev/null +++ b/js/src/jit-test/tests/debug/Frame-newTargetOverflow-01.js @@ -0,0 +1,37 @@ +// Test that Ion frames are invalidated by turning on Debugger. Invalidation +// is unobservable, but we know that Ion scripts cannot handle Debugger +// handlers, so we test for the handlers being called. + +load(libdir + "jitopts.js"); + +if (!jitTogglesMatch(Opts_Ion2NoOffthreadCompilation)) + quit(); + +withJitOptions(Opts_Ion2NoOffthreadCompilation, function () { + var g = newGlobal(); + var dbg = new Debugger; + + g.toggle = function toggle(d) { + if (d) { + dbg.addDebuggee(g); + + var frame = dbg.getNewestFrame(); + assertEq(frame.implementation, "ion"); + assertEq(frame.constructing, true); + + // overflow args are read from the parent's frame + // ensure we have the right offset to read from those. + assertEq(frame.arguments[1], 15); + } + }; + + g.eval("" + function f(d) { new g(d, 15); }); + + g.eval("" + function g(d) { toggle(d); }); + + g.eval("(" + function test() { + for (var i = 0; i < 5; i++) + f(false); + f(true); + } + ")();"); +}); diff --git a/js/src/jit-test/tests/proxy/testDirectProxyConstruct1.js b/js/src/jit-test/tests/proxy/testDirectProxyConstruct1.js index 31e2ead520..6117d8b6cb 100644 --- a/js/src/jit-test/tests/proxy/testDirectProxyConstruct1.js +++ b/js/src/jit-test/tests/proxy/testDirectProxyConstruct1.js @@ -1,9 +1,11 @@ // Forward to the target if the trap is undefined +var p; var target = function (x, y) { + assertEq(new.target, p); this.foo = x + y; } -for (let p of [new Proxy(target, {}), Proxy.revocable(target, {}).proxy]) { +for (p of [new Proxy(target, {}), Proxy.revocable(target, {}).proxy]) { var obj = new p(2, 3); assertEq(obj.foo, 5); assertEq(Object.getPrototypeOf(obj), target.prototype); diff --git a/js/src/jit-test/tests/proxy/testDirectProxyConstruct2.js b/js/src/jit-test/tests/proxy/testDirectProxyConstruct2.js index 4677ae264f..7f2421bd67 100644 --- a/js/src/jit-test/tests/proxy/testDirectProxyConstruct2.js +++ b/js/src/jit-test/tests/proxy/testDirectProxyConstruct2.js @@ -5,15 +5,17 @@ load(libdir + "asserts.js"); * * Hooks that don't return an object must throw. */ +var p; var target = function () {}; var handler = { - construct: function (target1, args) { + construct: function (target1, args, newTarget) { assertEq(this, handler); assertEq(target1, target); assertEq(args.length, 2); assertEq(args[0], 2); assertEq(args[1], 3); + assertEq(newTarget, p); } } -for (let p of [new Proxy(target, handler), Proxy.revocable(target, handler).proxy]) +for (p of [new Proxy(target, handler), Proxy.revocable(target, handler).proxy]) assertThrowsInstanceOf(function () {new p(2, 3)}, TypeError); diff --git a/js/src/jit/BaselineBailouts.cpp b/js/src/jit/BaselineBailouts.cpp index e71ed56b3c..25da3f6121 100644 --- a/js/src/jit/BaselineBailouts.cpp +++ b/js/src/jit/BaselineBailouts.cpp @@ -978,6 +978,8 @@ InitFromBailout(JSContext* cx, HandleScript caller, jsbytecode* callerPC, BailoutKindString(bailoutKind)); #endif + bool pushedNewTarget = op == JSOP_NEW; + // If this was the last inline frame, or we are bailing out to a catch or // finally block in this frame, then unpacking is almost done. if (!iter.moreFrames() || catchingException) { @@ -1034,11 +1036,14 @@ InitFromBailout(JSContext* cx, HandleScript caller, jsbytecode* callerPC, builder.writeValue(UndefinedValue(), "CallOp FillerThis"); for (uint32_t i = 0; i < numCallArgs; i++) builder.writeValue(UndefinedValue(), "CallOp FillerArg"); + if (pushedNewTarget) + builder.writeValue(UndefinedValue(), "CallOp FillerNewTarget"); - frameSize += (numCallArgs + 2) * sizeof(Value); + frameSize += (numCallArgs + 2 + pushedNewTarget) * sizeof(Value); blFrame->setFrameSize(frameSize); JitSpew(JitSpew_BaselineBailouts, " Adjusted framesize += %d: %d", - (int) ((numCallArgs + 2) * sizeof(Value)), (int) frameSize); + (int) ((numCallArgs + 2 + pushedNewTarget) * sizeof(Value)), + (int) frameSize); } // Set the resume address to the return point from the IC, and set @@ -1230,12 +1235,13 @@ InitFromBailout(JSContext* cx, HandleScript caller, jsbytecode* callerPC, } // Align the stack based on the number of arguments. - size_t afterFrameSize = (actualArgc + 1) * sizeof(Value) + JitFrameLayout::Size(); + size_t afterFrameSize = (actualArgc + 1 + pushedNewTarget) * sizeof(Value) + + JitFrameLayout::Size(); if (!builder.maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) return false; - MOZ_ASSERT(actualArgc + 2 <= exprStackSlots); - for (unsigned i = 0; i < actualArgc + 1; i++) { + MOZ_ASSERT(actualArgc + 2 + pushedNewTarget <= exprStackSlots); + for (unsigned i = 0; i < actualArgc + 1 + pushedNewTarget; i++) { size_t argSlot = (script->nfixed() + exprStackSlots) - (i + 1); if (!builder.writeValue(*blFrame->valueSlot(argSlot), "ArgVal")) return false; @@ -1262,7 +1268,7 @@ InitFromBailout(JSContext* cx, HandleScript caller, jsbytecode* callerPC, // So get the callee from the specially saved vector. callee = savedCallerArgs[0]; } else { - uint32_t calleeStackSlot = exprStackSlots - uint32_t(actualArgc + 2); + uint32_t calleeStackSlot = exprStackSlots - uint32_t(actualArgc + 2 + pushedNewTarget); size_t calleeOffset = (builder.framePushed() - endOfBaselineJSFrameStack) + ((exprStackSlots - (calleeStackSlot + 1)) * sizeof(Value)); callee = *builder.valuePointerAtStackOffset(calleeOffset); @@ -1333,10 +1339,18 @@ InitFromBailout(JSContext* cx, HandleScript caller, jsbytecode* callerPC, #endif // Align the stack based on the number of arguments. - size_t afterFrameSize = (calleeFun->nargs() + 1) * sizeof(Value) + RectifierFrameLayout::Size(); + size_t afterFrameSize = (calleeFun->nargs() + 1 + pushedNewTarget) * sizeof(Value) + + RectifierFrameLayout::Size(); if (!builder.maybeWritePadding(JitStackAlignment, afterFrameSize, "Padding")) return false; + // Copy new.target, if necessary. + if (pushedNewTarget) { + size_t newTargetOffset = (builder.framePushed() - endOfBaselineStubArgs) + + (actualArgc + 1) * sizeof(Value); + builder.writeValue(*builder.valuePointerAtStackOffset(newTargetOffset), "CopiedNewTarget"); + } + // Push undefined for missing arguments. for (unsigned i = 0; i < (calleeFun->nargs() - actualArgc); i++) { if (!builder.writeValue(UndefinedValue(), "FillerVal")) diff --git a/js/src/jit/BaselineCompiler.cpp b/js/src/jit/BaselineCompiler.cpp index 74fe268d32..84a332e0df 100644 --- a/js/src/jit/BaselineCompiler.cpp +++ b/js/src/jit/BaselineCompiler.cpp @@ -2728,19 +2728,20 @@ BaselineCompiler::emitCall() { MOZ_ASSERT(IsCallPC(pc)); + bool construct = JSOp(*pc) == JSOP_NEW; uint32_t argc = GET_ARGC(pc); frame.syncStack(0); masm.move32(Imm32(argc), R0.scratchReg()); // Call IC - ICCall_Fallback::Compiler stubCompiler(cx, /* isConstructing = */ JSOp(*pc) == JSOP_NEW, + ICCall_Fallback::Compiler stubCompiler(cx, /* isConstructing = */ construct, /* isSpread = */ false); if (!emitOpIC(stubCompiler.getStub(&stubSpace_))) return false; // Update FrameInfo. - frame.popn(argc + 2); + frame.popn(2 + argc + construct); frame.push(R0); return true; } @@ -2760,7 +2761,8 @@ BaselineCompiler::emitSpreadCall() return false; // Update FrameInfo. - frame.popn(3); + bool construct = JSOp(*pc) == JSOP_SPREADNEW; + frame.popn(3 + construct); frame.push(R0); return true; } diff --git a/js/src/jit/BaselineFrame.cpp b/js/src/jit/BaselineFrame.cpp index 5969e0e1fb..d42de65d37 100644 --- a/js/src/jit/BaselineFrame.cpp +++ b/js/src/jit/BaselineFrame.cpp @@ -37,7 +37,7 @@ BaselineFrame::trace(JSTracer* trc, JitFrameIterator& frameIterator) // Mark actual and formal args. if (isNonEvalFunctionFrame()) { unsigned numArgs = js::Max(numActualArgs(), numFormalArgs()); - TraceRootRange(trc, numArgs, argv(), "baseline-args"); + TraceRootRange(trc, numArgs + isConstructing(), argv(), "baseline-args"); } // Mark scope chain, if it exists. diff --git a/js/src/jit/BaselineIC.cpp b/js/src/jit/BaselineIC.cpp index 9bb631ddff..b52fa177ce 100644 --- a/js/src/jit/BaselineIC.cpp +++ b/js/src/jit/BaselineIC.cpp @@ -10194,6 +10194,7 @@ TryAttachCallStub(JSContext* cx, ICCall_Fallback* stub, HandleScript script, jsb if (fun->native() == intrinsic_IsSuspendedStarGenerator) { // This intrinsic only appears in self-hosted code. + MOZ_ASSERT(op != JSOP_NEW); MOZ_ASSERT(argc == 1); JitSpew(JitSpew_BaselineIC, " Generating Call_IsSuspendedStarGenerator stub"); @@ -10265,6 +10266,10 @@ TryAttachStringSplit(JSContext* cx, ICCall_Fallback* stub, HandleScript script, RootedValue thisv(cx, vp[1]); Value* args = vp + 2; + // String.prototype.split will not yield a constructable. + if (JSOp(*pc) == JSOP_NEW) + return true; + if (!IsOptimizableCallStringSplit(callee, thisv, argc, args)) return true; @@ -10310,15 +10315,16 @@ DoCallFallback(JSContext* cx, BaselineFrame* frame, ICCall_Fallback* stub_, uint // This fallback stub may trigger debug mode toggling. DebugModeOSRVolatileStub stub(frame, stub_); - // Ensure vp array is rooted - we may GC in here. - AutoArrayRooter vpRoot(cx, argc + 2, vp); - RootedScript script(cx, frame->script()); jsbytecode* pc = stub->icEntry()->pc(script); JSOp op = JSOp(*pc); FallbackICSpew(cx, stub, "Call(%s)", js_CodeName[op]); MOZ_ASSERT(argc == GET_ARGC(pc)); + bool constructing = (op == JSOP_NEW); + + // Ensure vp array is rooted - we may GC in here. + AutoArrayRooter vpRoot(cx, argc + 2 + constructing, vp); RootedValue callee(cx, vp[0]); RootedValue thisv(cx, vp[1]); @@ -10332,8 +10338,6 @@ DoCallFallback(JSContext* cx, BaselineFrame* frame, ICCall_Fallback* stub_, uint return false; } - // Compute construcing and useNewGroup flags. - bool constructing = (op == JSOP_NEW); bool createSingleton = ObjectGroup::useSingletonForNewObject(cx, script, pc); // Try attaching a call stub. @@ -10345,7 +10349,7 @@ DoCallFallback(JSContext* cx, BaselineFrame* frame, ICCall_Fallback* stub_, uint } if (op == JSOP_NEW) { - if (!InvokeConstructor(cx, callee, argc, args, res)) + if (!InvokeConstructor(cx, callee, argc, args, true, res)) return false; } else if ((op == JSOP_EVAL || op == JSOP_STRICTEVAL) && frame->scopeChain()->global().valueIsEval(callee)) @@ -10394,19 +10398,19 @@ DoSpreadCallFallback(JSContext* cx, BaselineFrame* frame, ICCall_Fallback* stub_ // This fallback stub may trigger debug mode toggling. DebugModeOSRVolatileStub stub(frame, stub_); - // Ensure vp array is rooted - we may GC in here. - AutoArrayRooter vpRoot(cx, 3, vp); - RootedScript script(cx, frame->script()); jsbytecode* pc = stub->icEntry()->pc(script); JSOp op = JSOp(*pc); + bool constructing = (op == JSOP_SPREADNEW); FallbackICSpew(cx, stub, "SpreadCall(%s)", js_CodeName[op]); + // Ensure vp array is rooted - we may GC in here. + AutoArrayRooter vpRoot(cx, 3 + constructing, vp); + RootedValue callee(cx, vp[0]); RootedValue thisv(cx, vp[1]); RootedValue arr(cx, vp[2]); - - bool constructing = (op == JSOP_SPREADNEW); + RootedValue newTarget(cx, constructing ? vp[3] : NullValue()); // Try attaching a call stub. bool handled = false; @@ -10417,7 +10421,7 @@ DoSpreadCallFallback(JSContext* cx, BaselineFrame* frame, ICCall_Fallback* stub_ return false; } - if (!SpreadCallOperation(cx, script, pc, thisv, callee, arr, res)) + if (!SpreadCallOperation(cx, script, pc, thisv, callee, arr, newTarget, res)) return false; // Check if debug mode toggling made the stub invalid. @@ -10439,14 +10443,26 @@ DoSpreadCallFallback(JSContext* cx, BaselineFrame* frame, ICCall_Fallback* stub_ void ICCallStubCompiler::pushCallArguments(MacroAssembler& masm, AllocatableGeneralRegisterSet regs, - Register argcReg, bool isJitCall) + Register argcReg, bool isJitCall, bool isConstructing) { MOZ_ASSERT(!regs.has(argcReg)); - // Push the callee and |this| too. + // Account for new.target Register count = regs.takeAny(); + masm.mov(argcReg, count); - masm.add32(Imm32(2), count); + + // If we are setting up for a jitcall, we have to align the stack taking + // into account the args and newTarget. We could also count callee and |this|, + // but it's a waste of stack space. Because we want to keep argcReg unchanged, + // just account for newTarget initially, and add the other 2 after assuring + // allignment. + if (isJitCall) { + if (isConstructing) + masm.add32(Imm32(1), count); + } else { + masm.add32(Imm32(2 + isConstructing), count); + } // argPtr initially points to the last argument. Register argPtr = regs.takeAny(); @@ -10458,8 +10474,12 @@ ICCallStubCompiler::pushCallArguments(MacroAssembler& masm, AllocatableGeneralRe // Align the stack such that the JitFrameLayout is aligned on the // JitStackAlignment. - if (isJitCall) - masm.alignJitStackBasedOnNArgs(argcReg); + if (isJitCall) { + masm.alignJitStackBasedOnNArgs(count); + + // Account for callee and |this|, skipped earlier + masm.add32(Imm32(2), count); + } // Push all values, starting at the last one. Label loop, done; @@ -10476,9 +10496,10 @@ ICCallStubCompiler::pushCallArguments(MacroAssembler& masm, AllocatableGeneralRe } void -ICCallStubCompiler::guardSpreadCall(MacroAssembler& masm, Register argcReg, Label* failure) +ICCallStubCompiler::guardSpreadCall(MacroAssembler& masm, Register argcReg, Label* failure, + bool isConstructing) { - masm.unboxObject(Address(BaselineStackReg, ICStackValueOffset), argcReg); + masm.unboxObject(Address(BaselineStackReg, isConstructing * sizeof(Value) + ICStackValueOffset), argcReg); masm.loadPtr(Address(argcReg, NativeObject::offsetOfElements()), argcReg); masm.load32(Address(argcReg, ObjectElements::offsetOfLength()), argcReg); @@ -10493,23 +10514,41 @@ ICCallStubCompiler::guardSpreadCall(MacroAssembler& masm, Register argcReg, Labe void ICCallStubCompiler::pushSpreadCallArguments(MacroAssembler& masm, AllocatableGeneralRegisterSet regs, - Register argcReg, bool isJitCall) + Register argcReg, bool isJitCall, + bool isConstructing) { - // Push arguments + // Pull the array off the stack before aligning. Register startReg = regs.takeAny(); - Register endReg = regs.takeAny(); - masm.unboxObject(Address(BaselineStackReg, STUB_FRAME_SIZE), startReg); + masm.unboxObject(Address(BaselineStackReg, (isConstructing * sizeof(Value)) + STUB_FRAME_SIZE), startReg); masm.loadPtr(Address(startReg, NativeObject::offsetOfElements()), startReg); + + // Align the stack such that the JitFrameLayout is aligned on the + // JitStackAlignment. + if (isJitCall) { + Register alignReg = argcReg; + if (isConstructing) { + alignReg = regs.takeAny(); + masm.mov(argcReg, alignReg); + masm.addPtr(Imm32(1), alignReg); + } + masm.alignJitStackBasedOnNArgs(alignReg); + if (isConstructing) { + MOZ_ASSERT(alignReg != argcReg); + regs.add(alignReg); + } + } + + // Push newTarget, if necessary + if (isConstructing) + masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE)); + + // Push arguments: set up endReg to point to &array[argc] + Register endReg = regs.takeAny(); masm.mov(argcReg, endReg); static_assert(sizeof(Value) == 8, "Value must be 8 bytes"); masm.lshiftPtr(Imm32(3), endReg); masm.addPtr(startReg, endReg); - // Align the stack such that the JitFrameLayout is aligned on the - // JitStackAlignment. - if (isJitCall) - masm.alignJitStackBasedOnNArgs(argcReg); - // Copying pre-decrements endReg by 8 until startReg is reached Label copyDone; Label copyStart; @@ -10524,8 +10563,8 @@ ICCallStubCompiler::pushSpreadCallArguments(MacroAssembler& masm, regs.add(endReg); // Push the callee and |this|. - masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE + 1 * sizeof(Value))); - masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE + 2 * sizeof(Value))); + masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE + (1 + isConstructing) * sizeof(Value))); + masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE + (2 + isConstructing) * sizeof(Value))); } // (see Bug 1149377 comment 31) MSVC 2013 PGO miss-compiles branchTestObjClass @@ -10736,9 +10775,20 @@ ICCall_Fallback::Compiler::generateStubCode(MacroAssembler& masm) // Use BaselineFrameReg instead of BaselineStackReg, because // BaselineFrameReg and BaselineStackReg hold the same value just after // calling enterStubFrame. - masm.pushValue(Address(BaselineFrameReg, 0 * sizeof(Value) + STUB_FRAME_SIZE)); // array - masm.pushValue(Address(BaselineFrameReg, 1 * sizeof(Value) + STUB_FRAME_SIZE)); // this - masm.pushValue(Address(BaselineFrameReg, 2 * sizeof(Value) + STUB_FRAME_SIZE)); // callee + + // newTarget + if (isConstructing_) + masm.pushValue(Address(BaselineFrameReg, STUB_FRAME_SIZE)); + + // array + uint32_t valueOffset = isConstructing_; + masm.pushValue(Address(BaselineFrameReg, valueOffset++ * sizeof(Value) + STUB_FRAME_SIZE)); + + // this + masm.pushValue(Address(BaselineFrameReg, valueOffset++ * sizeof(Value) + STUB_FRAME_SIZE)); + + // callee + masm.pushValue(Address(BaselineFrameReg, valueOffset++ * sizeof(Value) + STUB_FRAME_SIZE)); masm.push(BaselineStackReg); masm.push(BaselineStubReg); @@ -10759,7 +10809,7 @@ ICCall_Fallback::Compiler::generateStubCode(MacroAssembler& masm) regs.take(R0.scratchReg()); // argc. - pushCallArguments(masm, regs, R0.scratchReg(), /* isJitCall = */ false); + pushCallArguments(masm, regs, R0.scratchReg(), /* isJitCall = */ false, isConstructing_); masm.push(BaselineStackReg); masm.push(R0.scratchReg()); @@ -10844,14 +10894,17 @@ ICCallScriptedCompiler::generateStubCode(MacroAssembler& masm) regs.takeUnchecked(BaselineTailCallReg); if (isSpread_) - guardSpreadCall(masm, argcReg, &failure); + guardSpreadCall(masm, argcReg, &failure, isConstructing_); - // Load the callee in R1. - // Stack Layout: [ ..., CalleeVal, ThisVal, Arg0Val, ..., ArgNVal, +ICStackValueOffset+ ] + // Load the callee in R1, accounting for newTarget, if necessary + // Stack Layout: [ ..., CalleeVal, ThisVal, Arg0Val, ..., ArgNVal, [newTarget] +ICStackValueOffset+ ] if (isSpread_) { - masm.loadValue(Address(BaselineStackReg, 2 * sizeof(Value) + ICStackValueOffset), R1); + unsigned skipToCallee = (2 + isConstructing_) * sizeof(Value); + masm.loadValue(Address(BaselineStackReg, skipToCallee + ICStackValueOffset), R1); } else { - BaseValueIndex calleeSlot(BaselineStackReg, argcReg, ICStackValueOffset + sizeof(Value)); + // Account for newTarget, if necessary + unsigned nonArgsSkip = (1 + isConstructing_) * sizeof(Value); + BaseValueIndex calleeSlot(BaselineStackReg, argcReg, ICStackValueOffset + nonArgsSkip); masm.loadValue(calleeSlot, R1); } regs.take(R1); @@ -10911,13 +10964,13 @@ ICCallScriptedCompiler::generateStubCode(MacroAssembler& masm) masm.push(argcReg); // Stack now looks like: - // [..., Callee, ThisV, Arg0V, ..., ArgNV, StubFrameHeader, ArgC ] + // [..., Callee, ThisV, Arg0V, ..., ArgNV, NewTarget, StubFrameHeader, ArgC ] if (isSpread_) { masm.loadValue(Address(BaselineStackReg, - 2 * sizeof(Value) + STUB_FRAME_SIZE + sizeof(size_t)), R1); + 3 * sizeof(Value) + STUB_FRAME_SIZE + sizeof(size_t)), R1); } else { BaseValueIndex calleeSlot2(BaselineStackReg, argcReg, - sizeof(Value) + STUB_FRAME_SIZE + sizeof(size_t)); + 2 * sizeof(Value) + STUB_FRAME_SIZE + sizeof(size_t)); masm.loadValue(calleeSlot2, R1); } masm.push(masm.extractObject(R1, ExtractTemp0)); @@ -10945,11 +10998,11 @@ ICCallScriptedCompiler::generateStubCode(MacroAssembler& masm) // Save "this" value back into pushed arguments on stack. R0 can be clobbered after that. // Stack now looks like: - // [..., Callee, ThisV, Arg0V, ..., ArgNV, StubFrameHeader ] + // [..., Callee, ThisV, Arg0V, ..., ArgNV, [NewTarget], StubFrameHeader ] if (isSpread_) { - masm.storeValue(R0, Address(BaselineStackReg, sizeof(Value) + STUB_FRAME_SIZE)); + masm.storeValue(R0, Address(BaselineStackReg, (1 + isConstructing_) * sizeof(Value) + STUB_FRAME_SIZE)); } else { - BaseValueIndex thisSlot(BaselineStackReg, argcReg, STUB_FRAME_SIZE); + BaseValueIndex thisSlot(BaselineStackReg, argcReg, STUB_FRAME_SIZE + isConstructing_ * sizeof(Value)); masm.storeValue(R0, thisSlot); } @@ -10963,9 +11016,12 @@ ICCallScriptedCompiler::generateStubCode(MacroAssembler& masm) // Just need to load the script now. if (isSpread_) { - masm.loadValue(Address(BaselineStackReg, 2 * sizeof(Value) + STUB_FRAME_SIZE), R0); + unsigned skipForCallee = (2 + isConstructing_) * sizeof(Value); + masm.loadValue(Address(BaselineStackReg, skipForCallee + STUB_FRAME_SIZE), R0); } else { - BaseValueIndex calleeSlot3(BaselineStackReg, argcReg, sizeof(Value) + STUB_FRAME_SIZE); + // Account for newTarget, if necessary + unsigned nonArgsSkip = (1 + isConstructing_) * sizeof(Value); + BaseValueIndex calleeSlot3(BaselineStackReg, argcReg, nonArgsSkip + STUB_FRAME_SIZE); masm.loadValue(calleeSlot3, R0); } callee = masm.extractObject(R0, ExtractTemp0); @@ -10991,9 +11047,9 @@ ICCallScriptedCompiler::generateStubCode(MacroAssembler& masm) // right-to-left so duplicate them on the stack in reverse order. // |this| and callee are pushed last. if (isSpread_) - pushSpreadCallArguments(masm, regs, argcReg, /* isJitCall = */ true); + pushSpreadCallArguments(masm, regs, argcReg, /* isJitCall = */ true, isConstructing_); else - pushCallArguments(masm, regs, argcReg, /* isJitCall = */ true); + pushCallArguments(masm, regs, argcReg, /* isJitCall = */ true, isConstructing_); // The callee is on top of the stack. Pop and unbox it. ValueOperand val = regs.takeAnyValue(); @@ -11065,8 +11121,10 @@ ICCallScriptedCompiler::generateStubCode(MacroAssembler& masm) // Current stack: [ ThisVal, ARGVALS..., ...STUB FRAME..., <-- BaselineFrameReg // Padding?, ARGVALS..., ThisVal, ActualArgc, Callee, Descriptor ] // - // &ThisVal = BaselineFrameReg + argc * sizeof(Value) + STUB_FRAME_SIZE - BaseValueIndex thisSlotAddr(BaselineFrameReg, argcReg, STUB_FRAME_SIZE); + // &ThisVal = BaselineFrameReg + argc * sizeof(Value) + STUB_FRAME_SIZE + sizeof(Value) + // This last sizeof(Value) accounts for the newTarget on the end of the arguments vector + // which is not reflected in actualArgc + BaseValueIndex thisSlotAddr(BaselineFrameReg, argcReg, STUB_FRAME_SIZE + sizeof(Value)); masm.loadValue(thisSlotAddr, JSReturnOperand); #ifdef DEBUG masm.branchTestObject(Assembler::Equal, JSReturnOperand, &skipThisReplace); @@ -11238,13 +11296,14 @@ ICCall_Native::Compiler::generateStubCode(MacroAssembler& masm) regs.takeUnchecked(BaselineTailCallReg); if (isSpread_) - guardSpreadCall(masm, argcReg, &failure); + guardSpreadCall(masm, argcReg, &failure, isConstructing_); // Load the callee in R1. if (isSpread_) { masm.loadValue(Address(BaselineStackReg, ICStackValueOffset + 2 * sizeof(Value)), R1); } else { - BaseValueIndex calleeSlot(BaselineStackReg, argcReg, ICStackValueOffset + sizeof(Value)); + unsigned nonArgsSlots = (1 + isConstructing_) * sizeof(Value); + BaseValueIndex calleeSlot(BaselineStackReg, argcReg, ICStackValueOffset + nonArgsSlots); masm.loadValue(calleeSlot, R1); } regs.take(R1); @@ -11267,9 +11326,9 @@ ICCall_Native::Compiler::generateStubCode(MacroAssembler& masm) // right-to-left so duplicate them on the stack in reverse order. // |this| and callee are pushed last. if (isSpread_) - pushSpreadCallArguments(masm, regs, argcReg, /* isJitCall = */ false); + pushSpreadCallArguments(masm, regs, argcReg, /* isJitCall = */ false, isConstructing_); else - pushCallArguments(masm, regs, argcReg, /* isJitCall = */ false); + pushCallArguments(masm, regs, argcReg, /* isJitCall = */ false, isConstructing_); if (isConstructing_) { // Stack looks like: [ ..., Arg0Val, ThisVal, CalleeVal ] @@ -11342,7 +11401,8 @@ ICCall_ClassHook::Compiler::generateStubCode(MacroAssembler& masm) regs.takeUnchecked(BaselineTailCallReg); // Load the callee in R1. - BaseValueIndex calleeSlot(BaselineStackReg, argcReg, ICStackValueOffset + sizeof(Value)); + unsigned nonArgSlots = (1 + isConstructing_) * sizeof(Value); + BaseValueIndex calleeSlot(BaselineStackReg, argcReg, ICStackValueOffset + nonArgSlots); masm.loadValue(calleeSlot, R1); regs.take(R1); @@ -11364,7 +11424,7 @@ ICCall_ClassHook::Compiler::generateStubCode(MacroAssembler& masm) enterStubFrame(masm, regs.getAny()); regs.add(scratch); - pushCallArguments(masm, regs, argcReg, /* isJitCall = */ false); + pushCallArguments(masm, regs, argcReg, /* isJitCall = */ false, isConstructing_); regs.take(scratch); if (isConstructing_) { diff --git a/js/src/jit/BaselineIC.h b/js/src/jit/BaselineIC.h index 63a92286bc..47dccc6d75 100644 --- a/js/src/jit/BaselineIC.h +++ b/js/src/jit/BaselineIC.h @@ -5509,10 +5509,11 @@ class ICCallStubCompiler : public ICStubCompiler }; void pushCallArguments(MacroAssembler& masm, AllocatableGeneralRegisterSet regs, - Register argcReg, bool isJitCall); + Register argcReg, bool isJitCall, bool isConstructing = false); void pushSpreadCallArguments(MacroAssembler& masm, AllocatableGeneralRegisterSet regs, - Register argcReg, bool isJitCall); - void guardSpreadCall(MacroAssembler& masm, Register argcReg, Label* failure); + Register argcReg, bool isJitCall, bool isConstructing); + void guardSpreadCall(MacroAssembler& masm, Register argcReg, Label* failure, + bool isConstructing); Register guardFunApply(MacroAssembler& masm, AllocatableGeneralRegisterSet regs, Register argcReg, bool checkNative, FunApplyThing applyThing, Label* failure); diff --git a/js/src/jit/CodeGenerator.cpp b/js/src/jit/CodeGenerator.cpp index cb31bbbd15..9ad8da7177 100644 --- a/js/src/jit/CodeGenerator.cpp +++ b/js/src/jit/CodeGenerator.cpp @@ -2932,12 +2932,12 @@ CodeGenerator::visitCallGetIntrinsicValue(LCallGetIntrinsicValue* lir) callVM(GetIntrinsicValueInfo, lir); } -typedef bool (*InvokeFunctionFn)(JSContext*, HandleObject, uint32_t, Value*, Value*); +typedef bool (*InvokeFunctionFn)(JSContext*, HandleObject, bool, uint32_t, Value*, MutableHandleValue); static const VMFunction InvokeFunctionInfo = FunctionInfo(InvokeFunction); void CodeGenerator::emitCallInvokeFunction(LInstruction* call, Register calleereg, - uint32_t argc, uint32_t unusedStack) + bool constructing, uint32_t argc, uint32_t unusedStack) { // Nestle %esp up to the argument vector. // Each path must account for framePushed_ separately, for callVM to be valid. @@ -2945,6 +2945,7 @@ CodeGenerator::emitCallInvokeFunction(LInstruction* call, Register calleereg, pushArg(masm.getStackPointer()); // argv. pushArg(Imm32(argc)); // argc. + pushArg(Imm32(constructing)); // constructing. pushArg(calleereg); // JSFunction*. callVM(InvokeFunctionInfo, call); @@ -2999,7 +3000,8 @@ CodeGenerator::visitCallGeneric(LCallGeneric* call) // Check whether the provided arguments satisfy target argc. // We cannot have lowered to LCallGeneric with a known target. Assert that we didn't // add any undefineds in IonBuilder. NB: MCall::numStackArgs includes |this|. - MOZ_ASSERT(call->numActualArgs() == call->mir()->numStackArgs() - 1); + DebugOnly numNonArgsOnStack = 1 + call->isConstructing(); + MOZ_ASSERT(call->numActualArgs() == call->mir()->numStackArgs() - numNonArgsOnStack); masm.load16ZeroExtend(Address(calleereg, JSFunction::offsetOfNargs()), nargsreg); masm.branch32(Assembler::Above, nargsreg, Imm32(call->numActualArgs()), &thunk); masm.jump(&makeCall); @@ -3026,7 +3028,8 @@ CodeGenerator::visitCallGeneric(LCallGeneric* call) // Handle uncompiled or native functions. masm.bind(&invoke); - emitCallInvokeFunction(call, calleereg, call->numActualArgs(), unusedStack); + emitCallInvokeFunction(call, calleereg, call->isConstructing(), call->numActualArgs(), + unusedStack); masm.bind(&end); @@ -3040,19 +3043,40 @@ CodeGenerator::visitCallGeneric(LCallGeneric* call) } } +typedef bool (*InvokeFunctionShuffleFn)(JSContext*, HandleObject, uint32_t, uint32_t, Value*, + MutableHandleValue); +static const VMFunction InvokeFunctionShuffleInfo = + FunctionInfo(InvokeFunctionShuffleNewTarget); +void +CodeGenerator::emitCallInvokeFunctionShuffleNewTarget(LCallKnown* call, Register calleeReg, + uint32_t numFormals, uint32_t unusedStack) +{ + masm.freeStack(unusedStack); + + pushArg(masm.getStackPointer()); + pushArg(Imm32(numFormals)); + pushArg(Imm32(call->numActualArgs())); + pushArg(calleeReg); + + callVM(InvokeFunctionShuffleInfo, call); + + masm.reserveStack(unusedStack); +} + void CodeGenerator::visitCallKnown(LCallKnown* call) { Register calleereg = ToRegister(call->getFunction()); Register objreg = ToRegister(call->getTempObject()); uint32_t unusedStack = StackOffsetOfPassedArg(call->argslot()); - DebugOnly target = call->getSingleTarget(); + JSFunction* target = call->getSingleTarget(); Label end, uncompiled; // Native single targets are handled by LCallNative. MOZ_ASSERT(!target->isNative()); // Missing arguments must have been explicitly appended by the IonBuilder. - MOZ_ASSERT(target->nargs() <= call->mir()->numStackArgs() - 1); + DebugOnly numNonArgsOnStack = 1 + call->isConstructing(); + MOZ_ASSERT(target->nargs() <= call->mir()->numStackArgs() - numNonArgsOnStack); MOZ_ASSERT_IF(call->mir()->isConstructing(), target->isConstructor()); @@ -3092,7 +3116,10 @@ CodeGenerator::visitCallKnown(LCallKnown* call) // Handle uncompiled functions. masm.bind(&uncompiled); - emitCallInvokeFunction(call, calleereg, call->numActualArgs(), unusedStack); + if (call->isConstructing() && target->nargs() > call->numActualArgs()) + emitCallInvokeFunctionShuffleNewTarget(call, calleereg, target->nargs(), unusedStack); + else + emitCallInvokeFunction(call, calleereg, call->isConstructing(), call->numActualArgs(), unusedStack); masm.bind(&end); @@ -3118,6 +3145,7 @@ CodeGenerator::emitCallInvokeFunction(LApplyArgsGeneric* apply, Register extraSt pushArg(objreg); // argv. pushArg(ToRegister(apply->getArgc())); // argc. + pushArg(Imm32(false)); // isConstrucing. pushArg(ToRegister(apply->getFunction())); // JSFunction*. // This specialization og callVM restore the extraStackSize after the call. @@ -4775,39 +4803,24 @@ CodeGenerator::visitCreateThisWithProto(LCreateThisWithProto* lir) callVM(CreateThisWithProtoInfo, lir); } -typedef JSObject* (*NewGCObjectFn)(JSContext* cx, gc::AllocKind allocKind, - gc::InitialHeap initialHeap, size_t ndynamic, - const js::Class *clasp); -static const VMFunction NewGCObjectInfo = - FunctionInfo(js::jit::NewGCObject); - void CodeGenerator::visitCreateThisWithTemplate(LCreateThisWithTemplate* lir) { JSObject* templateObject = lir->mir()->templateObject(); - gc::AllocKind allocKind = templateObject->asTenured().getAllocKind(); - gc::InitialHeap initialHeap = lir->mir()->initialHeap(); - const js::Class *clasp = templateObject->getClass(); - size_t ndynamic = 0; - if (templateObject->isNative()) - ndynamic = templateObject->as().numDynamicSlots(); Register objReg = ToRegister(lir->output()); Register tempReg = ToRegister(lir->temp()); - OutOfLineCode *ool = oolCallVM(NewGCObjectInfo, lir, - (ArgList(), Imm32(int32_t(allocKind)), Imm32(initialHeap), - Imm32(ndynamic), ImmPtr(clasp)), + OutOfLineCode* ool = oolCallVM(NewInitObjectWithTemplateInfo, lir, + (ArgList(), ImmGCPtr(templateObject)), StoreRegisterTo(objReg)); // Allocate. If the FreeList is empty, call to VM, which may GC. - masm.newGCThing(objReg, tempReg, templateObject, lir->mir()->initialHeap(), ool->entry()); - - // Initialize based on the templateObject. - masm.bind(ool->rejoin()); - bool initContents = !templateObject->is() || - ShouldInitFixedSlots(lir, &templateObject->as()); - masm.initGCThing(objReg, tempReg, templateObject, initContents); + ShouldInitFixedSlots(lir, &templateObject->as()); + masm.createGCObject(objReg, tempReg, templateObject, lir->mir()->initialHeap(), ool->entry(), + initContents); + + masm.bind(ool->rejoin()); } typedef JSObject* (*NewIonArgumentsObjectFn)(JSContext* cx, JitFrameLayout* frame, HandleObject); @@ -5562,7 +5575,7 @@ CodeGenerator::visitIsNullOrLikeUndefinedAndBranchV(LIsNullOrLikeUndefinedAndBra } void -CodeGenerator::visitIsNullOrLikeUndefinedT(LIsNullOrLikeUndefinedT * lir) +CodeGenerator::visitIsNullOrLikeUndefinedT(LIsNullOrLikeUndefinedT* lir) { MOZ_ASSERT(lir->mir()->compareType() == MCompare::Compare_Undefined || lir->mir()->compareType() == MCompare::Compare_Null); diff --git a/js/src/jit/CodeGenerator.h b/js/src/jit/CodeGenerator.h index 81ff8336c7..4c1b5670b0 100644 --- a/js/src/jit/CodeGenerator.h +++ b/js/src/jit/CodeGenerator.h @@ -130,8 +130,13 @@ class CodeGenerator : public CodeGeneratorSpecific void visitOutOfLineCallPostWriteBarrier(OutOfLineCallPostWriteBarrier* ool); void visitCallNative(LCallNative* call); void emitCallInvokeFunction(LInstruction* call, Register callereg, - uint32_t argc, uint32_t unusedStack); + bool isConstructing, uint32_t argc, + uint32_t unusedStack); void visitCallGeneric(LCallGeneric* call); + void emitCallInvokeFunctionShuffleNewTarget(LCallKnown *call, + Register calleeReg, + uint32_t numFormals, + uint32_t unusedStack); void visitCallKnown(LCallKnown* call); void emitCallInvokeFunction(LApplyArgsGeneric* apply, Register extraStackSize); void emitPushArguments(LApplyArgsGeneric* apply, Register extraStackSpace); diff --git a/js/src/jit/Ion.cpp b/js/src/jit/Ion.cpp index 0adcd32bc1..66e762de4e 100644 --- a/js/src/jit/Ion.cpp +++ b/js/src/jit/Ion.cpp @@ -2547,7 +2547,8 @@ jit::SetEnterJitData(JSContext* cx, EnterJitData& data, RunState& state, AutoVal data.maxArgv = args.base() + 1; } else { MOZ_ASSERT(vals.empty()); - if (!vals.reserve(Max(args.length() + 1, numFormals + 1))) + unsigned numPushedArgs = Max(args.length(), numFormals); + if (!vals.reserve(numPushedArgs + 1 + data.constructing)) return false; // Append |this| and any provided arguments. @@ -2558,7 +2559,10 @@ jit::SetEnterJitData(JSContext* cx, EnterJitData& data, RunState& state, AutoVal while (vals.length() < numFormals + 1) vals.infallibleAppend(UndefinedValue()); - MOZ_ASSERT(vals.length() >= numFormals + 1); + if (data.constructing) + vals.infallibleAppend(args.newTarget()); + + MOZ_ASSERT(vals.length() >= numFormals + 1 + data.constructing); data.maxArgv = vals.begin(); } } else { diff --git a/js/src/jit/IonBuilder.cpp b/js/src/jit/IonBuilder.cpp index bebbb695cf..5af44c52fd 100644 --- a/js/src/jit/IonBuilder.cpp +++ b/js/src/jit/IonBuilder.cpp @@ -5284,6 +5284,8 @@ IonBuilder::inlineCallsite(const ObjectVector& targets, CallInfo& callInfo) if (target->isSingleton()) { // Replace the function with an MConstant. MConstant* constFun = constant(ObjectValue(*target)); + if (callInfo.constructing() && callInfo.getNewTarget() == callInfo.fun()) + callInfo.setNewTarget(constFun); callInfo.setFun(constFun); } @@ -6156,7 +6158,7 @@ IonBuilder::jsop_call(uint32_t argc, bool constructing) } } - int calleeDepth = -((int)argc + 2); + int calleeDepth = -((int)argc + 2 + constructing); // Acquire known call target if existent. ObjectVector targets(alloc()); @@ -6299,11 +6301,14 @@ IonBuilder::makeCallHelper(JSFunction* target, CallInfo& callInfo) } } - MCall* call = MCall::New(alloc(), target, targetArgs + 1, callInfo.argc(), - callInfo.constructing(), isDOMCall); + MCall* call = MCall::New(alloc(), target, targetArgs + 1 + callInfo.constructing(), + callInfo.argc(), callInfo.constructing(), isDOMCall); if (!call) return nullptr; + if (callInfo.constructing()) + call->addArg(targetArgs + 1, callInfo.getNewTarget()); + // Explicitly pad any missing arguments with |undefined|. // This permits skipping the argumentsRectifier. for (int i = targetArgs; i > (int)callInfo.argc(); i--) { @@ -9446,7 +9451,7 @@ IonBuilder::jsop_rest() } // We know the exact number of arguments the callee pushed. - unsigned numActuals = inlineCallInfo_->argv().length(); + unsigned numActuals = inlineCallInfo_->argc(); unsigned numFormals = info().nargs() - 1; unsigned numRest = numActuals > numFormals ? numActuals - numFormals : 0; diff --git a/js/src/jit/IonBuilder.h b/js/src/jit/IonBuilder.h index 2612f8d172..ea59d1fcf1 100644 --- a/js/src/jit/IonBuilder.h +++ b/js/src/jit/IonBuilder.h @@ -1233,6 +1233,7 @@ class CallInfo { MDefinition* fun_; MDefinition* thisArg_; + MDefinition* newTargetArg_; MDefinitionVector args_; bool constructing_; @@ -1242,6 +1243,7 @@ class CallInfo CallInfo(TempAllocator& alloc, bool constructing) : fun_(nullptr), thisArg_(nullptr), + newTargetArg_(nullptr), args_(alloc), constructing_(constructing), setter_(false) @@ -1253,6 +1255,9 @@ class CallInfo fun_ = callInfo.fun(); thisArg_ = callInfo.thisArg(); + if (constructing()) + newTargetArg_ = callInfo.getNewTarget(); + if (!args_.appendAll(callInfo.argv())) return false; @@ -1265,6 +1270,10 @@ class CallInfo // Get the arguments in the right order if (!args_.reserve(argc)) return false; + + if (constructing()) + setNewTarget(current->pop()); + for (int32_t i = argc; i > 0; i--) args_.infallibleAppend(current->peek(-i)); current->popn(argc); @@ -1286,13 +1295,16 @@ class CallInfo for (uint32_t i = 0; i < argc(); i++) current->push(getArg(i)); + + if (constructing()) + current->push(getNewTarget()); } uint32_t argc() const { return args_.length(); } uint32_t numFormals() const { - return argc() + 2; + return argc() + 2 + constructing(); } bool setArgs(const MDefinitionVector& args) { @@ -1331,6 +1343,15 @@ class CallInfo return constructing_; } + void setNewTarget(MDefinition* newTarget) { + MOZ_ASSERT(constructing()); + newTargetArg_ = newTarget; + } + MDefinition* getNewTarget() const { + MOZ_ASSERT(newTargetArg_); + return newTargetArg_; + } + bool isSetter() const { return setter_; } @@ -1350,6 +1371,8 @@ class CallInfo void setImplicitlyUsedUnchecked() { fun_->setImplicitlyUsedUnchecked(); thisArg_->setImplicitlyUsedUnchecked(); + if (newTargetArg_) + newTargetArg_->setImplicitlyUsedUnchecked(); for (uint32_t i = 0; i < argc(); i++) getArg(i)->setImplicitlyUsedUnchecked(); } diff --git a/js/src/jit/JitFrameIterator.h b/js/src/jit/JitFrameIterator.h index 307c448e07..bf618fb09d 100644 --- a/js/src/jit/JitFrameIterator.h +++ b/js/src/jit/JitFrameIterator.h @@ -734,13 +734,14 @@ class InlineFrameIterator InlineFrameIterator it(cx, this); ++it; unsigned argsObjAdj = it.script()->argumentsHasVarBinding() ? 1 : 0; + bool hasNewTarget = isConstructing(); SnapshotIterator parent_s(it.snapshotIterator()); // Skip over all slots until we get to the last slots // (= arguments slots of callee) the +3 is for [this], [returnvalue], // [scopechain], and maybe +1 for [argsObj] - MOZ_ASSERT(parent_s.numAllocations() >= nactual + 3 + argsObjAdj); - unsigned skip = parent_s.numAllocations() - nactual - 3 - argsObjAdj; + MOZ_ASSERT(parent_s.numAllocations() >= nactual + 3 + argsObjAdj + hasNewTarget); + unsigned skip = parent_s.numAllocations() - nactual - 3 - argsObjAdj - hasNewTarget; for (unsigned j = 0; j < skip; j++) parent_s.skip(); diff --git a/js/src/jit/JitFrames.cpp b/js/src/jit/JitFrames.cpp index 7ff7b596c9..6b7228cd8a 100644 --- a/js/src/jit/JitFrames.cpp +++ b/js/src/jit/JitFrames.cpp @@ -1018,8 +1018,9 @@ MarkThisAndArguments(JSTracer* trc, JitFrameLayout* layout) // Trace |this|. TraceRoot(trc, argv, "ion-thisv"); - // Trace actual arguments beyond the formals. Note + 1 for thisv. - for (size_t i = nformals + 1; i < nargs + 1; i++) + // Trace actual arguments and newTarget beyond the formals. Note + 1 for thisv. + bool constructing = CalleeTokenIsConstructing(layout->calleeToken()); + for (size_t i = nformals + 1; i < nargs + 1 + constructing; i++) TraceRoot(trc, &argv[i], "ion-argv"); } @@ -2431,7 +2432,8 @@ InlineFrameIterator::findNextFrame() MOZ_CRASH("Couldn't deduce the number of arguments of an ionmonkey frame"); // Skip over non-argument slots, as well as |this|. - unsigned skipCount = (si_.numAllocations() - 1) - numActualArgs_ - 1; + bool skipNewTarget = JSOp(*pc_) == JSOP_NEW; + unsigned skipCount = (si_.numAllocations() - 1) - numActualArgs_ - 1 - skipNewTarget; for (unsigned j = 0; j < skipCount; j++) si_.skip(); diff --git a/js/src/jit/LIR-Common.h b/js/src/jit/LIR-Common.h index 06e4f8eb1c..ec89495e78 100644 --- a/js/src/jit/LIR-Common.h +++ b/js/src/jit/LIR-Common.h @@ -1534,6 +1534,10 @@ class LJSCallInstructionHelper : public LCallInstructionHelpernumActualArgs(); } + + bool isConstructing() const { + return mir()->isConstructing(); + } }; // Generates a polymorphic callsite, wherein the function being called is diff --git a/js/src/jit/MCallOptimize.cpp b/js/src/jit/MCallOptimize.cpp index c8e9b5c300..33c22e4441 100644 --- a/js/src/jit/MCallOptimize.cpp +++ b/js/src/jit/MCallOptimize.cpp @@ -2698,9 +2698,11 @@ IonBuilder::inlineBoundFunction(CallInfo& nativeCallInfo, JSFunction* target) // Don't optimize if we're constructing and the callee is not a // constructor, so that CallKnown does not have to handle this case // (it should always throw). - if (nativeCallInfo.constructing() && !scriptedTarget->isConstructor()) { + if (nativeCallInfo.constructing() && !scriptedTarget->isConstructor()) + return InliningStatus_NotInlined; + + if (nativeCallInfo.constructing() && nativeCallInfo.getNewTarget() != nativeCallInfo.fun()) return InliningStatus_NotInlined; - } if (gc::IsInsideNursery(scriptedTarget)) return InliningStatus_NotInlined; @@ -2739,6 +2741,11 @@ IonBuilder::inlineBoundFunction(CallInfo& nativeCallInfo, JSFunction* target) for (size_t i = 0; i < nativeCallInfo.argc(); i++) callInfo.argv().infallibleAppend(nativeCallInfo.getArg(i)); + // We only inline when it was not a super-call, so just set the newTarget + // to be the target function, per spec. + if (nativeCallInfo.constructing()) + callInfo.setNewTarget(callInfo.fun()); + if (!makeCall(scriptedTarget, callInfo)) return InliningStatus_Error; diff --git a/js/src/jit/MacroAssembler.cpp b/js/src/jit/MacroAssembler.cpp index 3ab52e590a..9707b841c1 100644 --- a/js/src/jit/MacroAssembler.cpp +++ b/js/src/jit/MacroAssembler.cpp @@ -67,7 +67,7 @@ class TypeWrapper { } /* anonymous namespace */ template void -MacroAssembler::guardTypeSet(const Source& address, const Set *types, BarrierKind kind, +MacroAssembler::guardTypeSet(const Source& address, const Set* types, BarrierKind kind, Register scratch, Label* miss) { MOZ_ASSERT(kind == BarrierKind::TypeTagOnly || kind == BarrierKind::TypeSet); @@ -149,7 +149,7 @@ MacroAssembler::guardTypeSet(const Source& address, const Set *types, BarrierKin } void -MacroAssembler::guardTypeSetMightBeIncomplete(Register obj, Register scratch, Label *label) +MacroAssembler::guardTypeSetMightBeIncomplete(Register obj, Register scratch, Label* label) { // Type set guards might miss when an object's group changes. In this case // either its properties will become unknown, or it will change to a native @@ -165,7 +165,7 @@ MacroAssembler::guardTypeSetMightBeIncomplete(Register obj, Register scratch, La } template void -MacroAssembler::guardObjectType(Register obj, const Set *types, +MacroAssembler::guardObjectType(Register obj, const Set* types, Register scratch, Label* miss) { MOZ_ASSERT(!types->unknown()); @@ -280,7 +280,7 @@ template void MacroAssembler::guardType(const ValueOperand& value, TypeSet::Type template static void -StoreToTypedFloatArray(MacroAssembler &masm, int arrayType, const S &value, const T &dest, +StoreToTypedFloatArray(MacroAssembler& masm, int arrayType, const S& value, const T& dest, unsigned numElems) { switch (arrayType) { @@ -335,21 +335,21 @@ StoreToTypedFloatArray(MacroAssembler &masm, int arrayType, const S &value, cons void MacroAssembler::storeToTypedFloatArray(Scalar::Type arrayType, FloatRegister value, - const BaseIndex &dest, unsigned numElems) + const BaseIndex& dest, unsigned numElems) { StoreToTypedFloatArray(*this, arrayType, value, dest, numElems); } void MacroAssembler::storeToTypedFloatArray(Scalar::Type arrayType, FloatRegister value, - const Address &dest, unsigned numElems) + const Address& dest, unsigned numElems) { StoreToTypedFloatArray(*this, arrayType, value, dest, numElems); } template void -MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const T &src, AnyRegister dest, Register temp, - Label *fail, bool canonicalizeDoubles, unsigned numElems) +MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const T& src, AnyRegister dest, Register temp, + Label* fail, bool canonicalizeDoubles, unsigned numElems) { switch (arrayType) { case Scalar::Int8: @@ -429,11 +429,11 @@ MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const T &src, AnyRegi } } -template void MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const Address &src, AnyRegister dest, - Register temp, Label *fail, bool canonicalizeDoubles, +template void MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const Address& src, AnyRegister dest, + Register temp, Label* fail, bool canonicalizeDoubles, unsigned numElems); -template void MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const BaseIndex &src, AnyRegister dest, - Register temp, Label *fail, bool canonicalizeDoubles, +template void MacroAssembler::loadFromTypedArray(Scalar::Type arrayType, const BaseIndex& src, AnyRegister dest, + Register temp, Label* fail, bool canonicalizeDoubles, unsigned numElems); template @@ -979,7 +979,7 @@ MacroAssembler::shouldNurseryAllocate(gc::AllocKind allocKind, gc::InitialHeap i // this fills in the slots_ pointer. void MacroAssembler::nurseryAllocate(Register result, Register temp, gc::AllocKind allocKind, - size_t nDynamicSlots, gc::InitialHeap initialHeap, Label *fail) + size_t nDynamicSlots, gc::InitialHeap initialHeap, Label* fail) { MOZ_ASSERT(IsNurseryAllocable(allocKind)); MOZ_ASSERT(initialHeap != gc::TenuredHeap); @@ -995,7 +995,7 @@ MacroAssembler::nurseryAllocate(Register result, Register temp, gc::AllocKind al // No explicit check for nursery.isEnabled() is needed, as the comparison // with the nursery's end will always fail in such cases. - const Nursery &nursery = GetJitContext()->runtime->gcNursery(); + const Nursery& nursery = GetJitContext()->runtime->gcNursery(); int thingSize = int(gc::Arena::thingSize(allocKind)); int totalSize = thingSize + nDynamicSlots * sizeof(HeapSlot); loadPtr(AbsoluteAddress(nursery.addressOfPosition()), result); @@ -1011,7 +1011,7 @@ MacroAssembler::nurseryAllocate(Register result, Register temp, gc::AllocKind al // Inlined version of FreeList::allocate. This does not fill in slots_. void -MacroAssembler::freeListAllocate(Register result, Register temp, gc::AllocKind allocKind, Label *fail) +MacroAssembler::freeListAllocate(Register result, Register temp, gc::AllocKind allocKind, Label* fail) { CompileZone* zone = GetJitContext()->compartment->zone(); int thingSize = int(gc::Arena::thingSize(allocKind)); @@ -1076,7 +1076,7 @@ MacroAssembler::callFreeStub(Register slots) // Inlined equivalent of gc::AllocateObject, without failure case handling. void MacroAssembler::allocateObject(Register result, Register temp, gc::AllocKind allocKind, - uint32_t nDynamicSlots, gc::InitialHeap initialHeap, Label *fail) + uint32_t nDynamicSlots, gc::InitialHeap initialHeap, Label* fail) { MOZ_ASSERT(gc::IsObjectAllocKind(allocKind)); @@ -1110,21 +1110,8 @@ MacroAssembler::allocateObject(Register result, Register temp, gc::AllocKind all } void -MacroAssembler::newGCThing(Register result, Register temp, JSObject *templateObj, - gc::InitialHeap initialHeap, Label *fail) -{ - gc::AllocKind allocKind = templateObj->asTenured().getAllocKind(); - MOZ_ASSERT(gc::IsObjectAllocKind(allocKind)); - - size_t ndynamic = 0; - if (templateObj->isNative()) - ndynamic = templateObj->as().numDynamicSlots(); - allocateObject(result, temp, allocKind, ndynamic, initialHeap, fail); -} - -void -MacroAssembler::createGCObject(Register obj, Register temp, JSObject *templateObj, - gc::InitialHeap initialHeap, Label *fail, bool initContents, +MacroAssembler::createGCObject(Register obj, Register temp, JSObject* templateObj, + gc::InitialHeap initialHeap, Label* fail, bool initContents, bool convertDoubleElements) { gc::AllocKind allocKind = templateObj->asTenured().getAllocKind(); @@ -1157,13 +1144,13 @@ MacroAssembler::allocateNonObject(Register result, Register temp, gc::AllocKind } void -MacroAssembler::newGCString(Register result, Register temp, Label *fail) +MacroAssembler::newGCString(Register result, Register temp, Label* fail) { allocateNonObject(result, temp, js::gc::AllocKind::STRING, fail); } void -MacroAssembler::newGCFatInlineString(Register result, Register temp, Label *fail) +MacroAssembler::newGCFatInlineString(Register result, Register temp, Label* fail) { allocateNonObject(result, temp, js::gc::AllocKind::FAT_INLINE_STRING, fail); } @@ -1241,7 +1228,7 @@ FindStartOfUndefinedAndUninitializedSlots(NativeObject* templateObj, uint32_t ns } void -MacroAssembler::initGCSlots(Register obj, Register temp, NativeObject *templateObj, +MacroAssembler::initGCSlots(Register obj, Register temp, NativeObject* templateObj, bool initContents) { // Slots of non-array objects are required to be initialized. @@ -1302,20 +1289,20 @@ MacroAssembler::initGCSlots(Register obj, Register temp, NativeObject *templateO } void -MacroAssembler::initGCThing(Register obj, Register temp, JSObject *templateObj, +MacroAssembler::initGCThing(Register obj, Register temp, JSObject* templateObj, bool initContents, bool convertDoubleElements) { // Fast initialization of an empty object returned by allocateObject(). storePtr(ImmGCPtr(templateObj->group()), Address(obj, JSObject::offsetOfGroup())); - if (Shape *shape = templateObj->maybeShape()) + if (Shape* shape = templateObj->maybeShape()) storePtr(ImmGCPtr(shape), Address(obj, JSObject::offsetOfShape())); MOZ_ASSERT_IF(convertDoubleElements, templateObj->is()); if (templateObj->isNative()) { - NativeObject *ntemplate = &templateObj->as(); + NativeObject* ntemplate = &templateObj->as(); MOZ_ASSERT_IF(!ntemplate->denseElementsAreCopyOnWrite(), !ntemplate->hasDynamicElements()); // If the object has dynamic slots, the slots member has already been @@ -1324,7 +1311,7 @@ MacroAssembler::initGCThing(Register obj, Register temp, JSObject *templateObj, storePtr(ImmPtr(nullptr), Address(obj, NativeObject::offsetOfSlots())); if (ntemplate->denseElementsAreCopyOnWrite()) { - storePtr(ImmPtr((const Value *) ntemplate->getDenseElements()), + storePtr(ImmPtr((const Value*) ntemplate->getDenseElements()), Address(obj, NativeObject::offsetOfElements())); } else if (ntemplate->is()) { int elementsOffset = NativeObject::offsetOfFixedElements(); @@ -1403,9 +1390,9 @@ MacroAssembler::initGCThing(Register obj, Register temp, JSObject *templateObj, } void -MacroAssembler::initUnboxedObjectContents(Register object, UnboxedPlainObject *templateObject) +MacroAssembler::initUnboxedObjectContents(Register object, UnboxedPlainObject* templateObject) { - const UnboxedLayout &layout = templateObject->layout(); + const UnboxedLayout& layout = templateObject->layout(); // Initialize reference fields of the object, per UnboxedPlainObject::create. if (const int32_t *list = layout.traceList()) { @@ -1711,7 +1698,7 @@ MacroAssembler::assumeUnreachable(const char* output) setupUnalignedABICall(1, temp); movePtr(ImmPtr(output), temp); passABIArg(temp); - callWithABI(JS_FUNC_TO_DATA_PTR(void *, AssumeUnreachable_)); + callWithABI(JS_FUNC_TO_DATA_PTR(void*, AssumeUnreachable_)); PopRegsInMask(save); } @@ -1754,7 +1741,7 @@ MacroAssembler::printf(const char *output) setupUnalignedABICall(1, temp); movePtr(ImmPtr(output), temp); passABIArg(temp); - callWithABI(JS_FUNC_TO_DATA_PTR(void *, Printf0_)); + callWithABI(JS_FUNC_TO_DATA_PTR(void*, Printf0_)); PopRegsInMask(save); } @@ -1804,7 +1791,7 @@ MacroAssembler::tracelogStartId(Register logger, uint32_t textId, bool force) passABIArg(logger); move32(Imm32(textId), temp); passABIArg(temp); - callWithABI(JS_FUNC_TO_DATA_PTR(void *, TraceLogStartEventPrivate)); + callWithABI(JS_FUNC_TO_DATA_PTR(void*, TraceLogStartEventPrivate)); PopRegsInMask(save); } @@ -1823,7 +1810,7 @@ MacroAssembler::tracelogStartId(Register logger, Register textId) setupUnalignedABICall(2, temp); passABIArg(logger); passABIArg(textId); - callWithABI(JS_FUNC_TO_DATA_PTR(void *, TraceLogStartEventPrivate)); + callWithABI(JS_FUNC_TO_DATA_PTR(void*, TraceLogStartEventPrivate)); PopRegsInMask(save); } @@ -1831,7 +1818,7 @@ MacroAssembler::tracelogStartId(Register logger, Register textId) void MacroAssembler::tracelogStartEvent(Register logger, Register event) { - void (&TraceLogFunc)(TraceLoggerThread *, const TraceLoggerEvent &) = TraceLogStartEvent; + void (&TraceLogFunc)(TraceLoggerThread*, const TraceLoggerEvent &) = TraceLogStartEvent; AllocatableRegisterSet regs(RegisterSet::Volatile()); LiveRegisterSet save(regs.asLiveSet()); @@ -1844,7 +1831,7 @@ MacroAssembler::tracelogStartEvent(Register logger, Register event) setupUnalignedABICall(2, temp); passABIArg(logger); passABIArg(event); - callWithABI(JS_FUNC_TO_DATA_PTR(void *, TraceLogFunc)); + callWithABI(JS_FUNC_TO_DATA_PTR(void*, TraceLogFunc)); PopRegsInMask(save); } @@ -1867,7 +1854,7 @@ MacroAssembler::tracelogStopId(Register logger, uint32_t textId, bool force) move32(Imm32(textId), temp); passABIArg(temp); - callWithABI(JS_FUNC_TO_DATA_PTR(void *, TraceLogStopEventPrivate)); + callWithABI(JS_FUNC_TO_DATA_PTR(void*, TraceLogStopEventPrivate)); PopRegsInMask(save); } @@ -1886,7 +1873,7 @@ MacroAssembler::tracelogStopId(Register logger, Register textId) setupUnalignedABICall(2, temp); passABIArg(logger); passABIArg(textId); - callWithABI(JS_FUNC_TO_DATA_PTR(void *, TraceLogStopEventPrivate)); + callWithABI(JS_FUNC_TO_DATA_PTR(void*, TraceLogStopEventPrivate)); PopRegsInMask(save); } @@ -1982,8 +1969,8 @@ MacroAssembler::convertValueToFloatingPoint(JSContext* cx, const Value& v, Float } bool -MacroAssembler::convertConstantOrRegisterToFloatingPoint(JSContext *cx, ConstantOrRegister src, - FloatRegister output, Label *fail, +MacroAssembler::convertConstantOrRegisterToFloatingPoint(JSContext* cx, ConstantOrRegister src, + FloatRegister output, Label* fail, MIRType outputType) { if (src.constant()) @@ -2533,13 +2520,13 @@ MacroAssembler::Push(jsid id, Register scratchReg) // push it using ImmGCPtr, and then rematerialize the id at runtime. if (JSID_IS_STRING(id)) { - JSString *str = JSID_TO_STRING(id); + JSString* str = JSID_TO_STRING(id); MOZ_ASSERT(((size_t)str & JSID_TYPE_MASK) == 0); MOZ_ASSERT(JSID_TYPE_STRING == 0x0); Push(ImmGCPtr(str)); } else { MOZ_ASSERT(JSID_IS_SYMBOL(id)); - JS::Symbol *sym = JSID_TO_SYMBOL(id); + JS::Symbol* sym = JSID_TO_SYMBOL(id); movePtr(ImmGCPtr(sym), scratchReg); orPtr(Imm32(JSID_TYPE_SYMBOL), scratchReg); Push(scratchReg); diff --git a/js/src/jit/MacroAssembler.h b/js/src/jit/MacroAssembler.h index fd652d0e9e..b4ff0500f0 100644 --- a/js/src/jit/MacroAssembler.h +++ b/js/src/jit/MacroAssembler.h @@ -357,7 +357,7 @@ class MacroAssembler : public MacroAssemblerSpecific template void guardType(const Source& address, TypeSet::Type type, Register scratch, Label* miss); - void guardTypeSetMightBeIncomplete(Register obj, Register scratch, Label *label); + void guardTypeSetMightBeIncomplete(Register obj, Register scratch, Label* label); void loadObjShape(Register objReg, Register dest) { loadPtr(Address(objReg, JSObject::offsetOfShape()), dest); @@ -384,10 +384,10 @@ class MacroAssembler : public MacroAssemblerSpecific void branchTestObjShape(Condition cond, Register obj, Register shape, Label* label) { branchPtr(cond, Address(obj, JSObject::offsetOfShape()), shape, label); } - void branchTestObjGroup(Condition cond, Register obj, ObjectGroup *group, Label *label) { + void branchTestObjGroup(Condition cond, Register obj, ObjectGroup* group, Label* label) { branchPtr(cond, Address(obj, JSObject::offsetOfGroup()), ImmGCPtr(group), label); } - void branchTestObjGroup(Condition cond, Register obj, Register group, Label *label) { + void branchTestObjGroup(Condition cond, Register obj, Register group, Label* label) { branchPtr(cond, Address(obj, JSObject::offsetOfGroup()), group, label); } void branchTestProxyHandlerFamily(Condition cond, Register proxy, Register scratch, @@ -610,9 +610,9 @@ class MacroAssembler : public MacroAssemblerSpecific branchTest32(Assembler::NonZero, address, Imm32(bit), label); } - void branchIfNotInterpretedConstructor(Register fun, Register scratch, Label *label); + void branchIfNotInterpretedConstructor(Register fun, Register scratch, Label* label); - void bumpKey(Int32Key *key, int diff) { + void bumpKey(Int32Key* key, int diff) { if (key->isRegister()) add32(Imm32(diff), key->reg()); else @@ -695,8 +695,8 @@ class MacroAssembler : public MacroAssemblerSpecific bool canonicalizeDoubles = true, unsigned numElems = 0); template - void loadFromTypedArray(Scalar::Type arrayType, const T &src, const ValueOperand &dest, bool allowDouble, - Register temp, Label *fail); + void loadFromTypedArray(Scalar::Type arrayType, const T& src, const ValueOperand& dest, bool allowDouble, + Register temp, Label* fail); template void storeToTypedIntArray(Scalar::Type arrayType, const S& value, const T& dest) { @@ -720,12 +720,12 @@ class MacroAssembler : public MacroAssemblerSpecific } template - void compareExchangeToTypedIntArray(Scalar::Type arrayType, const T &mem, Register oldval, Register newval, + void compareExchangeToTypedIntArray(Scalar::Type arrayType, const T& mem, Register oldval, Register newval, Register temp, AnyRegister output); template - void atomicBinopToTypedIntArray(AtomicOp op, Scalar::Type arrayType, const S &value, - const T &mem, Register temp1, Register temp2, AnyRegister output); + void atomicBinopToTypedIntArray(AtomicOp op, Scalar::Type arrayType, const S& value, + const T& mem, Register temp1, Register temp2, AnyRegister output); void storeToTypedFloatArray(Scalar::Type arrayType, FloatRegister value, const BaseIndex& dest, unsigned numElems = 0); @@ -796,43 +796,41 @@ class MacroAssembler : public MacroAssemblerSpecific // Inline allocation. private: - void checkAllocatorState(Label *fail); + void checkAllocatorState(Label* fail); bool shouldNurseryAllocate(gc::AllocKind allocKind, gc::InitialHeap initialHeap); void nurseryAllocate(Register result, Register temp, gc::AllocKind allocKind, - size_t nDynamicSlots, gc::InitialHeap initialHeap, Label *fail); - void freeListAllocate(Register result, Register temp, gc::AllocKind allocKind, Label *fail); + size_t nDynamicSlots, gc::InitialHeap initialHeap, Label* fail); + void freeListAllocate(Register result, Register temp, gc::AllocKind allocKind, Label* fail); void allocateObject(Register result, Register temp, gc::AllocKind allocKind, - uint32_t nDynamicSlots, gc::InitialHeap initialHeap, Label *fail); - void allocateNonObject(Register result, Register temp, gc::AllocKind allocKind, Label *fail); - void copySlotsFromTemplate(Register obj, const NativeObject *templateObj, + uint32_t nDynamicSlots, gc::InitialHeap initialHeap, Label* fail); + void allocateNonObject(Register result, Register temp, gc::AllocKind allocKind, Label* fail); + void copySlotsFromTemplate(Register obj, const NativeObject* templateObj, uint32_t start, uint32_t end); void fillSlotsWithConstantValue(Address addr, Register temp, uint32_t start, uint32_t end, - const Value &v); + const Value& v); void fillSlotsWithUndefined(Address addr, Register temp, uint32_t start, uint32_t end); void fillSlotsWithUninitialized(Address addr, Register temp, uint32_t start, uint32_t end); - void initGCSlots(Register obj, Register temp, NativeObject *templateObj, bool initContents); + void initGCSlots(Register obj, Register temp, NativeObject* templateObj, bool initContents); public: - void callMallocStub(size_t nbytes, Register result, Label *fail); + void callMallocStub(size_t nbytes, Register result, Label* fail); void callFreeStub(Register slots); - void createGCObject(Register result, Register temp, JSObject *templateObj, - gc::InitialHeap initialHeap, Label *fail, bool initContents = true, + void createGCObject(Register result, Register temp, JSObject* templateObj, + gc::InitialHeap initialHeap, Label* fail, bool initContents = true, bool convertDoubleElements = false); - void newGCThing(Register result, Register temp, JSObject *templateObj, - gc::InitialHeap initialHeap, Label *fail); - void initGCThing(Register obj, Register temp, JSObject *templateObj, + void initGCThing(Register obj, Register temp, JSObject* templateObj, bool initContents = true, bool convertDoubleElements = false); - void initUnboxedObjectContents(Register object, UnboxedPlainObject *templateObject); + void initUnboxedObjectContents(Register object, UnboxedPlainObject* templateObject); - void newGCString(Register result, Register temp, Label *fail); - void newGCFatInlineString(Register result, Register temp, Label *fail); + void newGCString(Register result, Register temp, Label* fail); + void newGCFatInlineString(Register result, Register temp, Label* fail); // Compares two strings for equality based on the JSOP. // This checks for identical pointers, atoms and length and fails for everything else. void compareStrings(JSOp op, Register left, Register right, Register result, - Label *fail); + Label* fail); // If the JitCode that created this assembler needs to transition into the VM, // we want to store the JitCode on the stack in order to mark it during a GC. @@ -849,7 +847,7 @@ class MacroAssembler : public MacroAssemblerSpecific // Push stub code, and the VMFunction pointer. inline void enterExitFrame(const VMFunction* f = nullptr); - // The JitCode * argument here is one of the tokens defined in the various + // The JitCode* argument here is one of the tokens defined in the various // exit frame layout classes, e.g. NativeExitFrameLayout::Token(). inline void enterFakeExitFrame(JitCode* codeVal); @@ -973,15 +971,15 @@ class MacroAssembler : public MacroAssemblerSpecific // On ARM64, sp can function as the zero register depending on context. // Code shared across platforms must use these functions to be valid. template - void branchTestStackPtr(Condition cond, T t, Label *label) { + void branchTestStackPtr(Condition cond, T t, Label* label) { branchTestPtr(cond, getStackPointer(), t, label); } template - void branchStackPtr(Condition cond, T rhs, Label *label) { + void branchStackPtr(Condition cond, T rhs, Label* label) { branchPtr(cond, getStackPointer(), rhs, label); } template - void branchStackPtrRhs(Condition cond, T lhs, Label *label) { + void branchStackPtrRhs(Condition cond, T lhs, Label* label) { branchPtr(cond, lhs, getStackPointer(), label); } #endif // !JS_CODEGEN_ARM64 diff --git a/js/src/jit/VMFunctions.cpp b/js/src/jit/VMFunctions.cpp index 269aee2f4d..c8b2553b54 100644 --- a/js/src/jit/VMFunctions.cpp +++ b/js/src/jit/VMFunctions.cpp @@ -57,9 +57,10 @@ VMFunction::addToFunctions() } bool -InvokeFunction(JSContext* cx, HandleObject obj, uint32_t argc, Value* argv, Value* rval) +InvokeFunction(JSContext* cx, HandleObject obj, bool constructing, uint32_t argc, Value* argv, + MutableHandleValue rval) { - AutoArrayRooter argvRoot(cx, argc + 1, argv); + AutoArrayRooter argvRoot(cx, argc + 1 + constructing, argv); // Data in the argument vector is arranged for a JIT -> JIT call. Value thisv = argv[0]; @@ -68,35 +69,19 @@ InvokeFunction(JSContext* cx, HandleObject obj, uint32_t argc, Value* argv, Valu // For constructing functions, |this| is constructed at caller side and we can just call Invoke. // When creating this failed / is impossible at caller site, i.e. MagicValue(JS_IS_CONSTRUCTING), // we use InvokeConstructor that creates it at the callee side. - RootedValue rv(cx); - if (thisv.isMagic(JS_IS_CONSTRUCTING)) { - if (!InvokeConstructor(cx, ObjectValue(*obj), argc, argvWithoutThis, &rv)) - return false; - } else { - if (!Invoke(cx, thisv, ObjectValue(*obj), argc, argvWithoutThis, &rv)) - return false; - } + if (thisv.isMagic(JS_IS_CONSTRUCTING)) + return InvokeConstructor(cx, ObjectValue(*obj), argc, argvWithoutThis, true, rval); - if (obj->is()) { - jsbytecode* pc; - RootedScript script(cx, cx->currentScript(&pc)); - TypeScript::Monitor(cx, script, pc, rv.get()); - } - - *rval = rv; - return true; + return Invoke(cx, thisv, ObjectValue(*obj), argc, argvWithoutThis, rval); } -JSObject * -NewGCObject(JSContext *cx, gc::AllocKind allocKind, gc::InitialHeap initialHeap, - size_t ndynamic, const js::Class *clasp) +bool +InvokeFunctionShuffleNewTarget(JSContext* cx, HandleObject obj, uint32_t numActualArgs, + uint32_t numFormalArgs, Value* argv, MutableHandleValue rval) { - JSObject *obj = js::Allocate(cx, allocKind, ndynamic, initialHeap, clasp); - if (!obj) - return nullptr; - - SetNewObjectMetadata(cx, obj); - return obj; + MOZ_ASSERT(numFormalArgs > numActualArgs); + argv[1 + numActualArgs] = argv[1 + numFormalArgs]; + return InvokeFunction(cx, obj, true, numActualArgs, argv, rval); } bool @@ -193,8 +178,8 @@ MutatePrototype(JSContext* cx, HandlePlainObject obj, HandleValue value) } bool -InitProp(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value, - jsbytecode *pc) +InitProp(JSContext* cx, HandleObject obj, HandlePropertyName name, HandleValue value, + jsbytecode* pc) { RootedId id(cx, NameToId(name)); return InitPropertyOperation(cx, JSOp(*pc), obj, id, value); @@ -202,7 +187,7 @@ InitProp(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue v template bool -LooselyEqual(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool* res) +LooselyEqual(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs, bool* res) { if (!js::LooselyEqual(cx, lhs, rhs, res)) return false; diff --git a/js/src/jit/VMFunctions.h b/js/src/jit/VMFunctions.h index e52a00ffcf..6b5040684f 100644 --- a/js/src/jit/VMFunctions.h +++ b/js/src/jit/VMFunctions.h @@ -55,7 +55,7 @@ enum MaybeTailCall { // specified. In this case, the return type must be boolean to indicate // failure. // -// All functions described by VMFunction take a JSContext * as a first +// All functions described by VMFunction take a JSContext* as a first // argument, and are treated as re-entrant into the VM and therefore fallible. struct VMFunction { @@ -66,7 +66,7 @@ struct VMFunction // Address of the C function. void* wrapped; - // Number of arguments expected, excluding JSContext * as an implicit + // Number of arguments expected, excluding JSContext* as an implicit // first argument and an outparam as a possible implicit final argument. uint32_t explicitArgs; @@ -636,22 +636,23 @@ class AutoDetectInvalidation } }; -bool InvokeFunction(JSContext *cx, HandleObject obj0, uint32_t argc, Value *argv, Value* rval); -JSObject *NewGCObject(JSContext *cx, gc::AllocKind allocKind, gc::InitialHeap initialHeap, - size_t ndynamic, const js::Class *clasp); +bool InvokeFunction(JSContext* cx, HandleObject obj0, bool constructing, uint32_t argc, + Value* argv, MutableHandleValue rval); +bool InvokeFunctionShuffleNewTarget(JSContext* cx, HandleObject obj, uint32_t numActualArgs, + uint32_t numFormalArgs, Value* argv, MutableHandleValue rval); -bool CheckOverRecursed(JSContext *cx); -bool CheckOverRecursedWithExtra(JSContext *cx, BaselineFrame *frame, +bool CheckOverRecursed(JSContext* cx); +bool CheckOverRecursedWithExtra(JSContext* cx, BaselineFrame* frame, uint32_t extra, uint32_t earlyCheck); -bool DefVarOrConst(JSContext *cx, HandlePropertyName dn, unsigned attrs, HandleObject scopeChain); -bool SetConst(JSContext *cx, HandlePropertyName name, HandleObject scopeChain, HandleValue rval); -bool MutatePrototype(JSContext *cx, HandlePlainObject obj, HandleValue value); -bool InitProp(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value, - jsbytecode *pc); +bool DefVarOrConst(JSContext* cx, HandlePropertyName dn, unsigned attrs, HandleObject scopeChain); +bool SetConst(JSContext* cx, HandlePropertyName name, HandleObject scopeChain, HandleValue rval); +bool MutatePrototype(JSContext* cx, HandlePlainObject obj, HandleValue value); +bool InitProp(JSContext* cx, HandleObject obj, HandlePropertyName name, HandleValue value, + jsbytecode* pc); template -bool LooselyEqual(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool* res); +bool LooselyEqual(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs, bool* res); template bool StrictlyEqual(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs, bool* res); diff --git a/js/src/jit/arm/Trampoline-arm.cpp b/js/src/jit/arm/Trampoline-arm.cpp index 51bd35cd79..991f59e351 100644 --- a/js/src/jit/arm/Trampoline-arm.cpp +++ b/js/src/jit/arm/Trampoline-arm.cpp @@ -152,6 +152,16 @@ JitRuntime::generateEnterJIT(JSContext* cx, EnterJitType type) masm.loadPtr(slot_vp, r10); masm.unboxInt32(Address(r10, 0), r10); + { + Label noNewTarget; + masm.branchTest32(Assembler::Zero, r9, Imm32(CalleeToken_FunctionConstructing), + &noNewTarget); + + masm.add32(Imm32(1), r1); + + masm.bind(&noNewTarget); + } + // Guarantee stack alignment of Jit frames. // // This code moves the stack pointer to the location where it should be when @@ -465,12 +475,29 @@ JitRuntime::generateArgumentsRectifier(JSContext* cx, void** returnAddrOut) masm.ma_sub(r6, r8, r2); - masm.moveValue(UndefinedValue(), r5, r4); + // Get the topmost argument. + masm.ma_alu(sp, lsl(r8, 3), r3, OpAdd); // r3 <- r3 + nargs * 8 + masm.ma_add(r3, Imm32(sizeof(RectifierFrameLayout)), r3); - masm.ma_mov(sp, r3); // Save %sp. - masm.ma_mov(sp, r7); // Save %sp again. + { + Label notConstructing; + + masm.branchTest32(Assembler::Zero, r1, Imm32(CalleeToken_FunctionConstructing), + ¬Constructing); + + // Add sizeof(Value) to overcome |this| + masm.ma_dataTransferN(IsLoad, 64, true, r3, Imm32(8), r4, Offset); + masm.ma_dataTransferN(IsStore, 64, true, sp, Imm32(-8), r4, PreIndex); + + // Include the newly pushed newTarget value in the frame size + // calculated below. + masm.add32(Imm32(1), r6); + + masm.bind(¬Constructing); + } // Push undefined. + masm.moveValue(UndefinedValue(), r5, r4); { Label undefLoopTop; masm.bind(&undefLoopTop); @@ -480,11 +507,6 @@ JitRuntime::generateArgumentsRectifier(JSContext* cx, void** returnAddrOut) masm.ma_b(&undefLoopTop, Assembler::NonZero); } - // Get the topmost argument. - - masm.ma_alu(r3, lsl(r8, 3), r3, OpAdd); // r3 <- r3 + nargs * 8 - masm.ma_add(r3, Imm32(sizeof(RectifierFrameLayout)), r3); - // Push arguments, |nargs| + 1 times (to include |this|). { Label copyLoopTop; diff --git a/js/src/jit/x64/Trampoline-x64.cpp b/js/src/jit/x64/Trampoline-x64.cpp index 081e6f4552..4e1d9be42c 100644 --- a/js/src/jit/x64/Trampoline-x64.cpp +++ b/js/src/jit/x64/Trampoline-x64.cpp @@ -87,6 +87,18 @@ JitRuntime::generateEnterJIT(JSContext* cx, EnterJitType type) // Remember number of bytes occupied by argument vector masm.mov(reg_argc, r13); + + // if we are constructing, that also needs to include newTarget + { + Label noNewTarget; + masm.branchTest32(Assembler::Zero, token, Imm32(CalleeToken_FunctionConstructing), + &noNewTarget); + + masm.addq(Imm32(1), r13); + + masm.bind(&noNewTarget); + } + masm.shll(Imm32(3), r13); // r13 = argc * sizeof(Value) static_assert(sizeof(Value) == 1 << 3, "Constant is baked in assembly code"); @@ -111,7 +123,7 @@ JitRuntime::generateEnterJIT(JSContext* cx, EnterJitType type) ***************************************************************/ // r13 still stores the number of bytes in the argument vector. - masm.addq(reg_argv, r13); // r13 points above last argument. + masm.addq(reg_argv, r13); // r13 points above last argument or newTarget // while r13 > rdx, push arguments. { @@ -397,9 +409,19 @@ JitRuntime::generateArgumentsRectifier(JSContext* cx, void** returnAddrOut) masm.andq(Imm32(uint32_t(CalleeTokenMask)), rcx); masm.movzwl(Operand(rcx, JSFunction::offsetOfNargs()), rcx); - // Including |this|, there are (|nformals| + 1) arguments to push to the - // stack. Then we push a JitFrameLayout. We compute the padding expressed - // in the number of extra |undefined| values to push on the stack. + // Stash another copy in r11, since we are going to do destructive operations + // on rcx + masm.mov(rcx, r11); + + static_assert(CalleeToken_FunctionConstructing == 1, + "Ensure that we can use the constructing bit to count the value"); + masm.mov(rax, rdx); + masm.andq(Imm32(uint32_t(CalleeToken_FunctionConstructing)), rdx); + + // Including |this|, and |new.target|, there are (|nformals| + 1 + isConstructing) + // arguments to push to the stack. Then we push a JitFrameLayout. We + // compute the padding expressed in the number of extra |undefined| values + // to push on the stack. static_assert(sizeof(JitFrameLayout) % JitStackAlignment == 0, "No need to consider the JitFrameLayout for aligning the stack"); static_assert(JitStackAlignment % sizeof(Value) == 0, @@ -407,6 +429,7 @@ JitRuntime::generateArgumentsRectifier(JSContext* cx, void** returnAddrOut) MOZ_ASSERT(IsPowerOfTwo(JitStackValueAlignment)); masm.addl(Imm32(JitStackValueAlignment - 1 /* for padding */ + 1 /* for |this| */), rcx); + masm.addl(rdx, rcx); masm.andl(Imm32(~(JitStackValueAlignment - 1)), rcx); // Load the number of |undefined|s to push into %rcx. @@ -456,6 +479,28 @@ JitRuntime::generateArgumentsRectifier(JSContext* cx, void** returnAddrOut) masm.j(Assembler::NonZero, ©LoopTop); } + // if constructing, copy newTarget + { + Label notConstructing; + + masm.branchTest32(Assembler::Zero, rax, Imm32(CalleeToken_FunctionConstructing), + ¬Constructing); + + // thisFrame[numFormals] = prevFrame[argc] + ValueOperand newTarget(r10); + + // +1 for |this|. We want vp[argc], so don't subtract 1 + BaseIndex newTargetSrc(r9, rdx, TimesEight, sizeof(RectifierFrameLayout) + sizeof(Value)); + masm.loadValue(newTargetSrc, newTarget); + + // Again, 1 for |this| + BaseIndex newTargetDest(rsp, r11, TimesEight, sizeof(Value)); + masm.storeValue(newTarget, newTargetDest); + + masm.bind(¬Constructing); + } + + // Caller: // [arg2] [arg1] [this] [[argc] [callee] [descr] [raddr]] <- r9 // diff --git a/js/src/jit/x86-shared/MacroAssembler-x86-shared.h b/js/src/jit/x86-shared/MacroAssembler-x86-shared.h index a4a9880be5..2406fe9317 100644 --- a/js/src/jit/x86-shared/MacroAssembler-x86-shared.h +++ b/js/src/jit/x86-shared/MacroAssembler-x86-shared.h @@ -561,6 +561,11 @@ class MacroAssemblerX86Shared : public Assembler test32(Operand(address), imm); j(cond, label); } + void branchTest32(Condition cond, const Operand& lhs, Imm32 imm, Label* label) { + MOZ_ASSERT(cond == Zero || cond == NonZero || cond == Signed || cond == NotSigned); + test32(lhs, imm); + j(cond, label); + } void jump(Label* label) { jmp(label); diff --git a/js/src/jit/x86/Trampoline-x86.cpp b/js/src/jit/x86/Trampoline-x86.cpp index 55d8be6a31..e4c613de06 100644 --- a/js/src/jit/x86/Trampoline-x86.cpp +++ b/js/src/jit/x86/Trampoline-x86.cpp @@ -65,8 +65,22 @@ JitRuntime::generateEnterJIT(JSContext* cx, EnterJitType type) // compiled function. masm.movl(esp, esi); - // eax <- 8*argc, eax is now the offset betwen argv and the last + // Load the number of values to be copied (argc) into eax masm.loadPtr(Address(ebp, ARG_ARGC), eax); + + // If we are constructing, that also needs to include newTarget + { + Label noNewTarget; + masm.loadPtr(Address(ebp, ARG_CALLEETOKEN), edx); + masm.branchTest32(Assembler::Zero, edx, Imm32(CalleeToken_FunctionConstructing), + &noNewTarget); + + masm.addl(Imm32(1), eax); + + masm.bind(&noNewTarget); + } + + // eax <- 8*numValues, eax is now the offset betwen argv and the last value. masm.shll(Imm32(3), eax); // Guarantee stack alignment of Jit frames. @@ -397,6 +411,14 @@ JitRuntime::generateArgumentsRectifier(JSContext* cx, void** returnAddrOut) MOZ_ASSERT(IsPowerOfTwo(JitStackValueAlignment)); masm.addl(Imm32(JitStackValueAlignment - 1 /* for padding */), ecx); + + // Account for newTarget, if necessary. + static_assert(CalleeToken_FunctionConstructing == 1, + "Ensure that we can use the constructing bit to count an extra push"); + masm.mov(eax, edx); + masm.andl(Imm32(CalleeToken_FunctionConstructing), edx); + masm.addl(edx, ecx); + masm.andl(Imm32(~(JitStackValueAlignment - 1)), ecx); masm.subl(esi, ecx); @@ -453,6 +475,31 @@ JitRuntime::generateArgumentsRectifier(JSContext* cx, void** returnAddrOut) masm.j(Assembler::NonZero, ©LoopTop); } + { + Label notConstructing; + + masm.mov(eax, ebx); + masm.branchTest32(Assembler::Zero, ebx, Imm32(CalleeToken_FunctionConstructing), + ¬Constructing); + + BaseValueIndex src(FramePointer, edx, + sizeof(RectifierFrameLayout) + + sizeof(Value) + + sizeof(void*)); + + masm.andl(Imm32(CalleeTokenMask), ebx); + masm.movzwl(Operand(ebx, JSFunction::offsetOfNargs()), ebx); + + BaseValueIndex dst(esp, ebx, sizeof(Value)); + + ValueOperand newTarget(ecx, edi); + + masm.loadValue(src, newTarget); + masm.storeValue(newTarget, dst); + + masm.bind(¬Constructing); + } + // Construct descriptor, accounting for pushed frame pointer above masm.lea(Operand(FramePointer, sizeof(void*)), ebx); masm.subl(esp, ebx); diff --git a/js/src/jsapi.cpp b/js/src/jsapi.cpp index 2dd518443a..300319ec19 100644 --- a/js/src/jsapi.cpp +++ b/js/src/jsapi.cpp @@ -4416,7 +4416,7 @@ JS::Construct(JSContext* cx, HandleValue fval, const JS::HandleValueArray& args, assertSameCompartment(cx, fval, args); AutoLastFrameCheck lfc(cx); - return InvokeConstructor(cx, fval, args.length(), args.begin(), rval); + return InvokeConstructor(cx, fval, args.length(), args.begin(), false, rval); } static JSObject* @@ -4431,12 +4431,13 @@ JS_NewHelper(JSContext* cx, HandleObject ctor, const JS::HandleValueArray& input // of object to create, create it, and clamp the return value to an object, // among other details. InvokeConstructor does the hard work. InvokeArgs args(cx); - if (!args.init(inputArgs.length())) + if (!args.init(inputArgs.length(), true)) return nullptr; args.setCallee(ObjectValue(*ctor)); args.setThis(NullValue()); PodCopy(args.array(), inputArgs.begin(), inputArgs.length()); + args.newTarget().setObject(*ctor); if (!InvokeConstructor(cx, args)) return nullptr; diff --git a/js/src/jsarray.cpp b/js/src/jsarray.cpp index 485e8272be..eb11e19bdd 100644 --- a/js/src/jsarray.cpp +++ b/js/src/jsarray.cpp @@ -3154,7 +3154,7 @@ array_of(JSContext* cx, unsigned argc, Value* vp) { RootedValue v(cx); Value argv[1] = {NumberValue(args.length())}; - if (!InvokeConstructor(cx, args.thisv(), 1, argv, &v)) + if (!InvokeConstructor(cx, args.thisv(), 1, argv, false, &v)) return false; obj = ToObject(cx, v); if (!obj) @@ -3247,6 +3247,10 @@ bool js::ArrayConstructor(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); + + if (args.isConstructing()) + MOZ_ASSERT(args.newTarget().toObject().as().native() == js::ArrayConstructor); + RootedObjectGroup group(cx, ObjectGroup::callingAllocationSiteGroup(cx, JSProto_Array)); if (!group) return false; diff --git a/js/src/jsfun.cpp b/js/src/jsfun.cpp index b91d0d710b..29e53472d9 100644 --- a/js/src/jsfun.cpp +++ b/js/src/jsfun.cpp @@ -1646,7 +1646,7 @@ js::CallOrConstructBoundFunction(JSContext* cx, unsigned argc, Value* vp) const Value& boundThis = fun->getBoundFunctionThis(); InvokeArgs invokeArgs(cx); - if (!invokeArgs.init(args.length() + argslen)) + if (!invokeArgs.init(args.length() + argslen, args.isConstructing())) return false; /* 15.3.4.5.1, 15.3.4.5.2 step 4. */ @@ -1661,6 +1661,14 @@ js::CallOrConstructBoundFunction(JSContext* cx, unsigned argc, Value* vp) if (!constructing) invokeArgs.setThis(boundThis); + /* ES6 9.4.1.2 step 5 */ + if (constructing) { + if (&args.newTarget().toObject() == fun) + invokeArgs.newTarget().setObject(*target); + else + invokeArgs.newTarget().set(args.newTarget()); + } + if (constructing ? !InvokeConstructor(cx, invokeArgs) : !Invoke(cx, invokeArgs)) return false; diff --git a/js/src/jsiter.cpp b/js/src/jsiter.cpp index 785e2ed9c3..f0cddeae17 100644 --- a/js/src/jsiter.cpp +++ b/js/src/jsiter.cpp @@ -503,16 +503,14 @@ GetCustomIterator(JSContext* cx, HandleObject obj, unsigned flags, MutableHandle if (!Invoke(cx, ObjectValue(*obj), rval, 1, &arg, &rval)) return false; if (rval.isPrimitive()) { - /* - * We are always coming from js::ValueToIterator, and we are no longer on - * trace, so the object we are iterating over is on top of the stack (-1). - */ + // Ignore the stack when throwing. We can't tell whether we were + // supposed to skip over a new.target or not. JSAutoByteString bytes; if (!AtomToPrintableString(cx, name, &bytes)) return false; RootedValue val(cx, ObjectValue(*obj)); ReportValueError2(cx, JSMSG_BAD_TRAP_RETURN_VALUE, - -1, val, nullptr, bytes.ptr()); + JSDVG_IGNORE_STACK, val, nullptr, bytes.ptr()); return false; } objp.set(&rval.toObject()); diff --git a/js/src/jsopcode.cpp b/js/src/jsopcode.cpp index 39ac2da84e..b6f107ae80 100644 --- a/js/src/jsopcode.cpp +++ b/js/src/jsopcode.cpp @@ -119,9 +119,11 @@ js::StackUses(JSScript* script, jsbytecode* pc) switch (op) { case JSOP_POPN: return GET_UINT16(pc); + case JSOP_NEW: + return 2 + GET_ARGC(pc) + 1; default: /* stack: fun, this, [argc arguments] */ - MOZ_ASSERT(op == JSOP_NEW || op == JSOP_CALL || op == JSOP_EVAL || + MOZ_ASSERT(op == JSOP_CALL || op == JSOP_EVAL || op == JSOP_STRICTEVAL || op == JSOP_FUNCALL || op == JSOP_FUNAPPLY); return 2 + GET_ARGC(pc); } diff --git a/js/src/proxy/CrossCompartmentWrapper.cpp b/js/src/proxy/CrossCompartmentWrapper.cpp index 1dd1b94406..01dbe550d9 100644 --- a/js/src/proxy/CrossCompartmentWrapper.cpp +++ b/js/src/proxy/CrossCompartmentWrapper.cpp @@ -304,6 +304,8 @@ CrossCompartmentWrapper::construct(JSContext* cx, HandleObject wrapper, const Ca if (!cx->compartment()->wrap(cx, args[n])) return false; } + if (!cx->compartment()->wrap(cx, args.newTarget())) + return false; if (!Wrapper::construct(cx, wrapper, args)) return false; } diff --git a/js/src/proxy/DirectProxyHandler.cpp b/js/src/proxy/DirectProxyHandler.cpp index c0832a516f..f67e1a852c 100644 --- a/js/src/proxy/DirectProxyHandler.cpp +++ b/js/src/proxy/DirectProxyHandler.cpp @@ -82,7 +82,7 @@ DirectProxyHandler::construct(JSContext* cx, HandleObject proxy, const CallArgs& { assertEnteredPolicy(cx, proxy, JSID_VOID, CALL); RootedValue target(cx, proxy->as().private_()); - return InvokeConstructor(cx, target, args.length(), args.array(), args.rval()); + return InvokeConstructor(cx, target, args.length(), args.array(), true, args.rval()); } bool diff --git a/js/src/proxy/ScriptedDirectProxyHandler.cpp b/js/src/proxy/ScriptedDirectProxyHandler.cpp index a251a510be..96901a8681 100644 --- a/js/src/proxy/ScriptedDirectProxyHandler.cpp +++ b/js/src/proxy/ScriptedDirectProxyHandler.cpp @@ -1060,13 +1060,14 @@ ScriptedDirectProxyHandler::construct(JSContext* cx, HandleObject proxy, const C // step 6 if (trap.isUndefined()) { RootedValue targetv(cx, ObjectValue(*target)); - return InvokeConstructor(cx, targetv, args.length(), args.array(), args.rval()); + return InvokeConstructor(cx, targetv, args.length(), args.array(), true, args.rval()); } // step 8-9 Value constructArgv[] = { ObjectValue(*target), - ObjectValue(*argsArray) + ObjectValue(*argsArray), + args.newTarget() }; RootedValue thisValue(cx, ObjectValue(*handler)); if (!Invoke(cx, thisValue, trap, ArrayLength(constructArgv), constructArgv, args.rval())) diff --git a/js/src/proxy/ScriptedIndirectProxyHandler.cpp b/js/src/proxy/ScriptedIndirectProxyHandler.cpp index 29b8479819..9587cc9abc 100644 --- a/js/src/proxy/ScriptedIndirectProxyHandler.cpp +++ b/js/src/proxy/ScriptedIndirectProxyHandler.cpp @@ -467,7 +467,7 @@ CallableScriptedIndirectProxyHandler::construct(JSContext* cx, HandleObject prox MOZ_ASSERT(ccHolder->getClass() == &CallConstructHolder); RootedValue construct(cx, ccHolder->as().getReservedSlot(1)); MOZ_ASSERT(construct.isObject() && construct.toObject().isCallable()); - return InvokeConstructor(cx, construct, args.length(), args.array(), args.rval()); + return InvokeConstructor(cx, construct, args.length(), args.array(), true, args.rval()); } const CallableScriptedIndirectProxyHandler CallableScriptedIndirectProxyHandler::singleton; diff --git a/js/src/tests/ecma_6/Class/newTargetCCW.js b/js/src/tests/ecma_6/Class/newTargetCCW.js new file mode 100644 index 0000000000..9f5f870d40 --- /dev/null +++ b/js/src/tests/ecma_6/Class/newTargetCCW.js @@ -0,0 +1,10 @@ +// Make sure we wrap the new target on CCW construct calls. +var g = newGlobal(); + +let f = g.eval('(function (expected) { this.accept = new.target === expected; })'); + +for (let i = 0; i < 1100; i++) + assertEq(new f(f).accept, true); + +if (typeof reportCompare === 'function') + reportCompare(0,0,"OK"); diff --git a/js/src/tests/js1_7/extensions/regress-354945-01.js b/js/src/tests/js1_7/extensions/regress-354945-01.js index e842a2c3bd..76f1a3c82f 100644 --- a/js/src/tests/js1_7/extensions/regress-354945-01.js +++ b/js/src/tests/js1_7/extensions/regress-354945-01.js @@ -6,7 +6,7 @@ //----------------------------------------------------------------------------- var BUGNUMBER = 354945; var summary = 'Do not crash with new Iterator'; -var expect = 'TypeError: trap __iterator__ for obj returned a primitive value'; +var expect = 'TypeError: trap __iterator__ for ({__iterator__:(function (){ })}) returned a primitive value'; var actual; diff --git a/js/src/tests/js1_7/extensions/regress-354945-02.js b/js/src/tests/js1_7/extensions/regress-354945-02.js index d09f7fe497..261bf7de17 100644 --- a/js/src/tests/js1_7/extensions/regress-354945-02.js +++ b/js/src/tests/js1_7/extensions/regress-354945-02.js @@ -20,7 +20,7 @@ function test() printBugNumber(BUGNUMBER); printStatus (summary); - expect = 'TypeError: trap __iterator__ for obj returned a primitive value'; + expect = 'TypeError: trap __iterator__ for ({__iterator__:(function (){ })}) returned a primitive value'; var obj = {}; obj.__iterator__ = function(){ }; try diff --git a/js/src/vm/Interpreter.cpp b/js/src/vm/Interpreter.cpp index 6310dec8b5..8fba145379 100644 --- a/js/src/vm/Interpreter.cpp +++ b/js/src/vm/Interpreter.cpp @@ -672,8 +672,9 @@ js::Invoke(JSContext* cx, const CallArgs& args, MaybeConstruct construct) /* MaybeConstruct is a subset of InitialFrameFlags */ InitialFrameFlags initial = (InitialFrameFlags) construct; + unsigned skipForCallee = args.length() + 1 + (construct == CONSTRUCT); if (args.calleev().isPrimitive()) - return ReportIsNotFunction(cx, args.calleev(), args.length() + 1, construct); + return ReportIsNotFunction(cx, args.calleev(), skipForCallee, construct); const Class* clasp = args.callee().getClass(); @@ -686,7 +687,7 @@ js::Invoke(JSContext* cx, const CallArgs& args, MaybeConstruct construct) MOZ_ASSERT_IF(construct, !args.callee().constructHook()); JSNative call = args.callee().callHook(); if (!call) - return ReportIsNotFunction(cx, args.calleev(), args.length() + 1, construct); + return ReportIsNotFunction(cx, args.calleev(), skipForCallee, construct); return CallJSNative(cx, call, args); } @@ -765,15 +766,18 @@ js::InvokeConstructor(JSContext* cx, const CallArgs& args) args.setThis(MagicValue(JS_IS_CONSTRUCTING)); + // +2 here and below to pass over |this| and |new.target| if (!args.calleev().isObject()) - return ReportIsNotFunction(cx, args.calleev(), args.length() + 1, CONSTRUCT); + return ReportIsNotFunction(cx, args.calleev(), args.length() + 2, CONSTRUCT); + + MOZ_ASSERT(args.newTarget().isObject()); JSObject& callee = args.callee(); if (callee.is()) { RootedFunction fun(cx, &callee.as()); if (!fun->isConstructor()) - return ReportIsNotFunction(cx, args.calleev(), args.length() + 1, CONSTRUCT); + return ReportIsNotFunction(cx, args.calleev(), args.length() + 2, CONSTRUCT); if (fun->isNative()) return CallJSNativeConstructor(cx, fun->native(), args); @@ -787,22 +791,26 @@ js::InvokeConstructor(JSContext* cx, const CallArgs& args) JSNative construct = callee.constructHook(); if (!construct) - return ReportIsNotFunction(cx, args.calleev(), args.length() + 1, CONSTRUCT); + return ReportIsNotFunction(cx, args.calleev(), args.length() + 2, CONSTRUCT); return CallJSNativeConstructor(cx, construct, args); } bool js::InvokeConstructor(JSContext* cx, Value fval, unsigned argc, const Value* argv, - MutableHandleValue rval) + bool newTargetInArgv, MutableHandleValue rval) { InvokeArgs args(cx); - if (!args.init(argc)) + if (!args.init(argc, true)) return false; args.setCallee(fval); args.setThis(MagicValue(JS_THIS_POISON)); PodCopy(args.array(), argv, argc); + if (newTargetInArgv) + args.newTarget().set(argv[argc]); + else + args.newTarget().set(fval); if (!InvokeConstructor(cx, args)) return false; @@ -2931,16 +2939,25 @@ CASE(JSOP_STRICTSPREADEVAL) { static_assert(JSOP_SPREADEVAL_LENGTH == JSOP_STRICTSPREADEVAL_LENGTH, "spreadeval and strictspreadeval must be the same size"); - MOZ_ASSERT(REGS.stackDepth() >= 3); + bool construct = JSOp(*REGS.pc) == JSOP_SPREADNEW; - HandleValue callee = REGS.stackHandleAt(-3); - HandleValue thisv = REGS.stackHandleAt(-2); - HandleValue arr = REGS.stackHandleAt(-1); - MutableHandleValue ret = REGS.stackHandleAt(-3); - if (!SpreadCallOperation(cx, script, REGS.pc, thisv, callee, arr, ret)) + MOZ_ASSERT(REGS.stackDepth() >= 3u + construct); + + HandleValue callee = REGS.stackHandleAt(-3 - construct); + HandleValue thisv = REGS.stackHandleAt(-2 - construct); + HandleValue arr = REGS.stackHandleAt(-1 - construct); + MutableHandleValue ret = REGS.stackHandleAt(-3 - construct); + + RootedValue& newTarget = rootValue0; + if (construct) + newTarget = REGS.sp[-1]; + else + newTarget = NullValue(); + + if (!SpreadCallOperation(cx, script, REGS.pc, thisv, callee, arr, newTarget, ret)) goto error; - REGS.sp -= 2; + REGS.sp -= 2 + construct; } END_CASE(JSOP_SPREADCALL) @@ -2959,10 +2976,11 @@ CASE(JSOP_FUNCALL) if (REGS.fp()->hasPushedSPSFrame()) cx->runtime()->spsProfiler.updatePC(script, REGS.pc); - MOZ_ASSERT(REGS.stackDepth() >= 2u + GET_ARGC(REGS.pc)); - CallArgs args = CallArgsFromSp(GET_ARGC(REGS.pc), REGS.sp); - bool construct = (*REGS.pc == JSOP_NEW); + unsigned argStackSlots = GET_ARGC(REGS.pc) + construct; + + MOZ_ASSERT(REGS.stackDepth() >= 2u + GET_ARGC(REGS.pc)); + CallArgs args = CallArgsFromSp(argStackSlots, REGS.sp, construct); RootedFunction& fun = rootFunction0; bool isFunction = IsFunctionObject(args.calleev(), fun.address()); @@ -4581,16 +4599,17 @@ js::InitGetterSetterOperation(JSContext* cx, jsbytecode* pc, HandleObject obj, H bool js::SpreadCallOperation(JSContext* cx, HandleScript script, jsbytecode* pc, HandleValue thisv, - HandleValue callee, HandleValue arr, MutableHandleValue res) + HandleValue callee, HandleValue arr, HandleValue newTarget, MutableHandleValue res) { RootedArrayObject aobj(cx, &arr.toObject().as()); uint32_t length = aobj->length(); JSOp op = JSOp(*pc); + bool constructing = op == JSOP_SPREADNEW; if (length > ARGS_LENGTH_MAX) { JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, - op == JSOP_SPREADNEW ? JSMSG_TOO_MANY_CON_SPREADARGS - : JSMSG_TOO_MANY_FUN_SPREADARGS); + constructing ? JSMSG_TOO_MANY_CON_SPREADARGS + : JSMSG_TOO_MANY_FUN_SPREADARGS); return false; } @@ -4605,7 +4624,7 @@ js::SpreadCallOperation(JSContext* cx, HandleScript script, jsbytecode* pc, Hand InvokeArgs args(cx); - if (!args.init(length)) + if (!args.init(length, constructing)) return false; args.setCallee(callee); @@ -4614,6 +4633,11 @@ js::SpreadCallOperation(JSContext* cx, HandleScript script, jsbytecode* pc, Hand if (!GetElements(cx, aobj, length, args.array())) return false; + if (constructing) { + MOZ_ASSERT(newTarget.isObject()); + args.newTarget().set(newTarget); + } + switch (op) { case JSOP_SPREADNEW: if (!InvokeConstructor(cx, args)) diff --git a/js/src/vm/Interpreter.h b/js/src/vm/Interpreter.h index 4b95d2a8dc..00483e273d 100644 --- a/js/src/vm/Interpreter.h +++ b/js/src/vm/Interpreter.h @@ -95,7 +95,7 @@ InvokeConstructor(JSContext* cx, const CallArgs& args); /* See the fval overload of Invoke. */ extern bool InvokeConstructor(JSContext* cx, Value fval, unsigned argc, const Value* argv, - MutableHandleValue rval); + bool newTargetInArgv, MutableHandleValue rval); /* * Executes a script with the given scopeChain/this. The 'type' indicates @@ -439,7 +439,7 @@ InitGetterSetterOperation(JSContext* cx, jsbytecode* pc, HandleObject obj, Handl bool SpreadCallOperation(JSContext* cx, HandleScript script, jsbytecode* pc, HandleValue thisv, - HandleValue callee, HandleValue arr, MutableHandleValue res); + HandleValue callee, HandleValue arr, HandleValue newTarget, MutableHandleValue res); JSObject* NewObjectOperation(JSContext* cx, HandleScript script, jsbytecode* pc, diff --git a/js/src/vm/Opcodes.h b/js/src/vm/Opcodes.h index 8fa0ca8b3d..d2f68a800a 100644 --- a/js/src/vm/Opcodes.h +++ b/js/src/vm/Opcodes.h @@ -391,9 +391,9 @@ * Category: Statements * Type: Function * Operands: - * Stack: callee, this, args => rval + * Stack: callee, this, args, newTarget => rval */ \ - macro(JSOP_SPREADNEW, 42, "spreadnew", NULL, 1, 3, 1, JOF_BYTE|JOF_INVOKE|JOF_TYPESET) \ + macro(JSOP_SPREADNEW, 42, "spreadnew", NULL, 1, 4, 1, JOF_BYTE|JOF_INVOKE|JOF_TYPESET) \ /* * spreadcall variant of JSOP_EVAL * @@ -766,8 +766,8 @@ * Category: Statements * Type: Function * Operands: uint16_t argc - * Stack: callee, this, args[0], ..., args[argc-1] => rval - * nuses: (argc+2) + * Stack: callee, this, args[0], ..., args[argc-1], newTarget => rval + * nuses: (argc+3) */ \ macro(JSOP_NEW, 82, js_new_str, NULL, 3, -1, 1, JOF_UINT16|JOF_INVOKE|JOF_TYPESET) \ /* diff --git a/js/src/vm/Stack-inl.h b/js/src/vm/Stack-inl.h index 4394d1a966..2aa42afa70 100644 --- a/js/src/vm/Stack-inl.h +++ b/js/src/vm/Stack-inl.h @@ -291,7 +291,10 @@ InterpreterStack::getCallFrame(JSContext* cx, const CallArgs& args, HandleScript // Pad any missing arguments with |undefined|. MOZ_ASSERT(args.length() < nformal); - nvals += nformal + 2; // Include callee, |this|. + bool isConstructing = *flags & InterpreterFrame::CONSTRUCTING; + unsigned nfunctionState = 2 + isConstructing; // callee, |this|, |new.target| + + nvals += nformal + nfunctionState; uint8_t* buffer = allocateFrame(cx, sizeof(InterpreterFrame) + nvals * sizeof(Value)); if (!buffer) return nullptr; @@ -302,8 +305,11 @@ InterpreterStack::getCallFrame(JSContext* cx, const CallArgs& args, HandleScript mozilla::PodCopy(argv, args.base(), 2 + args.length()); SetValueRangeToUndefined(argv + 2 + args.length(), nmissing); + if (isConstructing) + argv[2 + nformal] = args.newTarget(); + *pargv = argv + 2; - return reinterpret_cast(argv + 2 + nformal); + return reinterpret_cast(argv + nfunctionState + nformal); } MOZ_ALWAYS_INLINE bool diff --git a/js/src/vm/Stack.cpp b/js/src/vm/Stack.cpp index 20fbe2db8b..7b9c12c224 100644 --- a/js/src/vm/Stack.cpp +++ b/js/src/vm/Stack.cpp @@ -397,7 +397,7 @@ InterpreterFrame::markValues(JSTracer* trc, Value* sp, jsbytecode* pc) if (hasArgs()) { // Mark callee, |this| and arguments. unsigned argc = Max(numActualArgs(), numFormalArgs()); - TraceRootRange(trc, argc + 2, argv_ - 2, "fp argv"); + TraceRootRange(trc, argc + 2 + isConstructing(), argv_ - 2, "fp argv"); } else { // Mark callee and |this| TraceRootRange(trc, 2, ((Value*)this) - 2, "stack callee and this"); diff --git a/js/src/vm/Stack.h b/js/src/vm/Stack.h index 81e70496e0..51e313c98e 100644 --- a/js/src/vm/Stack.h +++ b/js/src/vm/Stack.h @@ -927,7 +927,7 @@ class InterpreterRegs void popInlineFrame() { pc = fp_->prevpc(); - sp = fp_->prevsp() - fp_->numActualArgs() - 1; + sp = fp_->prevsp() - fp_->numActualArgs() - 1 - fp_->isConstructing(); fp_ = fp_->prev(); MOZ_ASSERT(fp_); } @@ -1019,12 +1019,14 @@ class InvokeArgs : public JS::CallArgs AutoValueVector v_; public: - explicit InvokeArgs(JSContext* cx) : v_(cx) {} + explicit InvokeArgs(JSContext* cx, bool construct = false) : v_(cx) {} - bool init(unsigned argc) { - if (!v_.resize(2 + argc)) + bool init(unsigned argc, bool construct = false) { + if (!v_.resize(2 + argc + construct)) return false; ImplicitCast(*this) = CallArgsFromVp(argc, v_.begin()); + // Set the internal flag, since we are not initializing from a made array + constructing_ = construct; return true; } }; diff --git a/js/src/vm/Xdr.h b/js/src/vm/Xdr.h index 5f94a559ea..398ca43069 100644 --- a/js/src/vm/Xdr.h +++ b/js/src/vm/Xdr.h @@ -29,7 +29,7 @@ namespace js { * * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Internals/Bytecode */ -static const uint32_t XDR_BYTECODE_VERSION_SUBTRAHEND = 277; +static const uint32_t XDR_BYTECODE_VERSION_SUBTRAHEND = 278; static const uint32_t XDR_BYTECODE_VERSION = uint32_t(0xb973c0de - XDR_BYTECODE_VERSION_SUBTRAHEND); diff --git a/netwerk/base/nsICacheInfoChannel.idl b/netwerk/base/nsICacheInfoChannel.idl index a610eb1ac8..f90ee6af60 100644 --- a/netwerk/base/nsICacheInfoChannel.idl +++ b/netwerk/base/nsICacheInfoChannel.idl @@ -27,6 +27,25 @@ interface nsICacheInfoChannel : nsISupports */ boolean isFromCache(); + /** + * Set/get the cache key... uniquely identifies the data in the cache + * for this channel. Holding a reference to this key does NOT prevent + * the cached data from being removed. + * + * A cache key retrieved from a particular instance of nsICachingChannel + * could be set on another instance of nsICachingChannel provided the + * underlying implementations are compatible and provided the new + * channel instance was created with the same URI. The implementation of + * nsICachingChannel would be expected to use the cache entry identified + * by the cache token. Depending on the value of nsIRequest::loadFlags, + * the cache entry may be validated, overwritten, or simply read. + * + * The cache key may be NULL indicating that the URI of the channel is + * sufficient to locate the same cache entry. Setting a NULL cache key + * is likewise valid. + */ + attribute nsISupports cacheKey; + /** * Tells the channel to behave as if the LOAD_FROM_CACHE flag has been set, * but without affecting the loads for the entire loadGroup in case of this diff --git a/netwerk/base/nsICachingChannel.idl b/netwerk/base/nsICachingChannel.idl index c9cfd0c490..7c6d2b5dba 100644 --- a/netwerk/base/nsICachingChannel.idl +++ b/netwerk/base/nsICachingChannel.idl @@ -17,7 +17,7 @@ interface nsIFile; * 3) Support for uniquely identifying cached data in cases when the URL * is insufficient (e.g., HTTP form submission). */ -[scriptable, uuid(3d46b469-7405-416e-ba42-84899963b403)] +[scriptable, uuid(436b939d-e391-48e5-ba64-ab0e496e3400)] interface nsICachingChannel : nsICacheInfoChannel { /** @@ -45,25 +45,6 @@ interface nsICachingChannel : nsICacheInfoChannel */ attribute nsISupports offlineCacheToken; - /** - * Set/get the cache key... uniquely identifies the data in the cache - * for this channel. Holding a reference to this key does NOT prevent - * the cached data from being removed. - * - * A cache key retrieved from a particular instance of nsICachingChannel - * could be set on another instance of nsICachingChannel provided the - * underlying implementations are compatible and provided the new - * channel instance was created with the same URI. The implementation of - * nsICachingChannel would be expected to use the cache entry identified - * by the cache token. Depending on the value of nsIRequest::loadFlags, - * the cache entry may be validated, overwritten, or simply read. - * - * The cache key may be NULL indicating that the URI of the channel is - * sufficient to locate the same cache entry. Setting a NULL cache key - * is likewise valid. - */ - attribute nsISupports cacheKey; - /** * Instructs the channel to only store the metadata of the entry, and not * the content. When reading an existing entry, this automatically sets diff --git a/netwerk/ipc/NeckoChannelParams.ipdlh b/netwerk/ipc/NeckoChannelParams.ipdlh index 32e269cc58..b7087c9cf0 100644 --- a/netwerk/ipc/NeckoChannelParams.ipdlh +++ b/netwerk/ipc/NeckoChannelParams.ipdlh @@ -30,6 +30,18 @@ union OptionalHttpResponseHead nsHttpResponseHead; }; +struct HttpChannelCacheKey +{ + uint32_t postId; + nsCString key; +}; + +union OptionalHttpChannelCacheKey +{ + void_t; + HttpChannelCacheKey; +}; + struct HttpChannelOpenArgs { URIParams uri; @@ -67,6 +79,7 @@ struct HttpChannelOpenArgs uint32_t contentPolicyType; uint32_t innerWindowID; OptionalHttpResponseHead synthesizedResponseHead; + OptionalHttpChannelCacheKey cacheKey; bool allowStaleCacheContent; bool isFromProcessingFrameAttributes; }; diff --git a/netwerk/protocol/http/HttpBaseChannel.h b/netwerk/protocol/http/HttpBaseChannel.h index 14c5171757..57afb8e479 100644 --- a/netwerk/protocol/http/HttpBaseChannel.h +++ b/netwerk/protocol/http/HttpBaseChannel.h @@ -182,7 +182,7 @@ public: NS_IMETHOD GetAllowAltSvc(bool *aAllowAltSvc) override; NS_IMETHOD SetAllowAltSvc(bool aAllowAltSvc) override; NS_IMETHOD GetApiRedirectToURI(nsIURI * *aApiRedirectToURI) override; - nsresult AddSecurityMessage(const nsAString &aMessageTag, const nsAString &aMessageCategory); + virtual nsresult AddSecurityMessage(const nsAString &aMessageTag, const nsAString &aMessageCategory); NS_IMETHOD TakeAllSecurityMessages(nsCOMArray &aMessages) override; NS_IMETHOD GetResponseTimeoutEnabled(bool *aEnable) override; NS_IMETHOD SetResponseTimeoutEnabled(bool aEnable) override; diff --git a/netwerk/protocol/http/HttpChannelChild.cpp b/netwerk/protocol/http/HttpChannelChild.cpp index 8d035cbe53..db9b341a48 100644 --- a/netwerk/protocol/http/HttpChannelChild.cpp +++ b/netwerk/protocol/http/HttpChannelChild.cpp @@ -323,7 +323,8 @@ class StartRequestEvent : public ChannelEvent const nsCString& cachedCharset, const nsCString& securityInfoSerialization, const NetAddr& selfAddr, - const NetAddr& peerAddr) + const NetAddr& peerAddr, + const HttpChannelCacheKey& cacheKey) : mChild(child) , mChannelStatus(channelStatus) , mResponseHead(responseHead) @@ -336,6 +337,7 @@ class StartRequestEvent : public ChannelEvent , mSecurityInfoSerialization(securityInfoSerialization) , mSelfAddr(selfAddr) , mPeerAddr(peerAddr) + , mCacheKey(cacheKey) {} void Run() @@ -344,7 +346,8 @@ class StartRequestEvent : public ChannelEvent mChild->OnStartRequest(mChannelStatus, mResponseHead, mUseResponseHead, mRequestHeaders, mIsFromCache, mCacheEntryAvailable, mCacheExpirationTime, mCachedCharset, - mSecurityInfoSerialization, mSelfAddr, mPeerAddr); + mSecurityInfoSerialization, mSelfAddr, mPeerAddr, + mCacheKey); } private: HttpChannelChild* mChild; @@ -359,6 +362,7 @@ class StartRequestEvent : public ChannelEvent nsCString mSecurityInfoSerialization; NetAddr mSelfAddr; NetAddr mPeerAddr; + HttpChannelCacheKey mCacheKey; }; bool @@ -373,7 +377,8 @@ HttpChannelChild::RecvOnStartRequest(const nsresult& channelStatus, const nsCString& securityInfoSerialization, const NetAddr& selfAddr, const NetAddr& peerAddr, - const int16_t& redirectCount) + const int16_t& redirectCount, + const HttpChannelCacheKey& cacheKey) { LOG(("HttpChannelChild::RecvOnStartRequest [this=%p]\n", this)); // mFlushedForDiversion and mDivertingToParent should NEVER be set at this @@ -392,12 +397,12 @@ HttpChannelChild::RecvOnStartRequest(const nsresult& channelStatus, isFromCache, cacheEntryAvailable, cacheExpirationTime, cachedCharset, securityInfoSerialization, selfAddr, - peerAddr)); + peerAddr, cacheKey)); } else { OnStartRequest(channelStatus, responseHead, useResponseHead, requestHeaders, isFromCache, cacheEntryAvailable, cacheExpirationTime, cachedCharset, securityInfoSerialization, selfAddr, - peerAddr); + peerAddr, cacheKey); } return true; } @@ -413,7 +418,8 @@ HttpChannelChild::OnStartRequest(const nsresult& channelStatus, const nsCString& cachedCharset, const nsCString& securityInfoSerialization, const NetAddr& selfAddr, - const NetAddr& peerAddr) + const NetAddr& peerAddr, + const HttpChannelCacheKey& cacheKey) { LOG(("HttpChannelChild::OnStartRequest [this=%p]\n", this)); @@ -441,6 +447,10 @@ HttpChannelChild::OnStartRequest(const nsresult& channelStatus, mCacheExpirationTime = cacheExpirationTime; mCachedCharset = cachedCharset; + nsRefPtr tmpKey = new nsHttpChannelCacheKey(); + tmpKey->SetData(cacheKey.postId(), cacheKey.key()); + CallQueryInterface(tmpKey.get(), getter_AddRefs(mCacheKey)); + AutoEventEnqueuer ensureSerialDispatch(mEventQ); // replace our request headers with what actually got sent in the parent @@ -991,6 +1001,14 @@ HttpChannelChild::DeleteSelf() Send__delete__(this); } +bool +HttpChannelChild::RecvReportSecurityMessage(const nsString& messageTag, + const nsString& messageCategory) +{ + AddSecurityMessage(messageTag, messageCategory); + return true; +} + class Redirect1Event : public ChannelEvent { public: @@ -1641,6 +1659,20 @@ HttpChannelChild::ContinueAsyncOpen() openArgs.allowStaleCacheContent() = mAllowStaleCacheContent; + if (mCacheKey) { + uint32_t postId; + nsAutoCString key; + nsresult rv = static_cast( + static_cast(mCacheKey.get()))->GetData(&postId, + key); + if (NS_FAILED(rv)) { + return rv; + } + openArgs.cacheKey() = HttpChannelCacheKey(postId, key); + } else { + openArgs.cacheKey() = mozilla::void_t(); + } + propagateLoadInfo(mLoadInfo, openArgs); // The socket transport in the chrome process now holds a logical ref to us @@ -1797,6 +1829,21 @@ HttpChannelChild::GetAllowStaleCacheContent(bool *aAllowStaleCacheContent) return NS_OK; } +NS_IMETHODIMP +HttpChannelChild::GetCacheKey(nsISupports **cacheKey) +{ + NS_IF_ADDREF(*cacheKey = mCacheKey); + return NS_OK; +} +NS_IMETHODIMP +HttpChannelChild::SetCacheKey(nsISupports *cacheKey) +{ + ENSURE_CALLED_BEFORE_ASYNC_OPEN(); + + mCacheKey = cacheKey; + return NS_OK; +} + //----------------------------------------------------------------------------- // HttpChannelChild::nsIResumableChannel //----------------------------------------------------------------------------- diff --git a/netwerk/protocol/http/HttpChannelChild.h b/netwerk/protocol/http/HttpChannelChild.h index 6f54013dac..7f5a687f3e 100644 --- a/netwerk/protocol/http/HttpChannelChild.h +++ b/netwerk/protocol/http/HttpChannelChild.h @@ -117,7 +117,8 @@ protected: const nsCString& securityInfoSerialization, const NetAddr& selfAddr, const NetAddr& peerAddr, - const int16_t& redirectCount) override; + const int16_t& redirectCount, + const HttpChannelCacheKey& cacheKey) override; bool RecvOnTransportAndData(const nsresult& channelStatus, const nsresult& status, const uint64_t& progress, @@ -140,6 +141,9 @@ protected: bool RecvDivertMessages() override; bool RecvDeleteSelf() override; + bool RecvReportSecurityMessage(const nsString& messageTag, + const nsString& messageCategory) override; + bool GetAssociatedContentSecurity(nsIAssociatedContentSecurity** res = nullptr); virtual void DoNotifyListenerCleanup() override; @@ -173,6 +177,7 @@ private: bool mCacheEntryAvailable; uint32_t mCacheExpirationTime; nsCString mCachedCharset; + nsCOMPtr mCacheKey; // If ResumeAt is called before AsyncOpen, we need to send extra data upstream bool mSendResumeAt; @@ -205,7 +210,8 @@ private: const nsCString& cachedCharset, const nsCString& securityInfoSerialization, const NetAddr& selfAddr, - const NetAddr& peerAddr); + const NetAddr& peerAddr, + const HttpChannelCacheKey& cacheKey); void OnTransportAndData(const nsresult& channelStatus, const nsresult& status, const uint64_t progress, diff --git a/netwerk/protocol/http/HttpChannelParent.cpp b/netwerk/protocol/http/HttpChannelParent.cpp index 89243b3661..8334a99570 100644 --- a/netwerk/protocol/http/HttpChannelParent.cpp +++ b/netwerk/protocol/http/HttpChannelParent.cpp @@ -113,7 +113,7 @@ HttpChannelParent::Init(const HttpChannelCreationArgs& aArgs) a.appCacheClientID(), a.allowSpdy(), a.allowAltSvc(), a.fds(), a.requestingPrincipalInfo(), a.triggeringPrincipalInfo(), a.securityFlags(), a.contentPolicyType(), a.innerWindowID(), - a.synthesizedResponseHead(), + a.synthesizedResponseHead(), a.cacheKey(), a.allowStaleCacheContent()); } case HttpChannelCreationArgs::THttpChannelConnectArgs: @@ -269,6 +269,7 @@ HttpChannelParent::DoAsyncOpen( const URIParams& aURI, const uint32_t& aContentPolicyType, const uint32_t& aInnerWindowID, const OptionalHttpResponseHead& aSynthesizedResponseHead, + const OptionalHttpChannelCacheKey& aCacheKey, const bool& aAllowStaleCacheContent) { nsCOMPtr uri = DeserializeURI(aURI); @@ -332,6 +333,7 @@ HttpChannelParent::DoAsyncOpen( const URIParams& aURI, return SendFailedAsyncOpen(rv); mChannel = static_cast(channel.get()); + mChannel->SetWarningReporter(this); mChannel->SetTimingEnabled(true); if (mPBOverride != kPBOverride_Unset) { mChannel->SetPrivate(mPBOverride == kPBOverride_Private ? true : false); @@ -392,6 +394,15 @@ HttpChannelParent::DoAsyncOpen( const URIParams& aURI, mSynthesizedResponseHead = new nsHttpResponseHead(aSynthesizedResponseHead.get_nsHttpResponseHead()); } + if (aCacheKey.type() == OptionalHttpChannelCacheKey::THttpChannelCacheKey) { + nsRefPtr cacheKey = new nsHttpChannelCacheKey(); + cacheKey->SetData(aCacheKey.get_HttpChannelCacheKey().postId(), + aCacheKey.get_HttpChannelCacheKey().key()); + nsCOMPtr cacheKeySupp; + CallQueryInterface(cacheKey.get(), getter_AddRefs(cacheKeySupp)); + mChannel->SetCacheKey(cacheKeySupp); + } + if (priority != nsISupportsPriority::PRIORITY_NORMAL) { mChannel->SetPriority(priority); } @@ -807,6 +818,21 @@ HttpChannelParent::OnStartRequest(nsIRequest *aRequest, nsISupports *aContext) uint16_t redirectCount = 0; mChannel->GetRedirectCount(&redirectCount); + + nsCOMPtr cacheKeySupp; + mChannel->GetCacheKey(getter_AddRefs(cacheKeySupp)); + uint32_t postId = 0; + nsAutoCString key; + if (cacheKeySupp) { + nsresult rv = static_cast( + static_cast(cacheKeySupp.get()))->GetData(&postId, + key); + if (NS_FAILED(rv)) { + return rv; + } + } + HttpChannelCacheKey cacheKey = HttpChannelCacheKey(postId, key); + if (mIPCClosed || !SendOnStartRequest(channelStatus, responseHead ? *responseHead : nsHttpResponseHead(), @@ -816,7 +842,8 @@ HttpChannelParent::OnStartRequest(nsIRequest *aRequest, nsISupports *aContext) mCacheEntry ? true : false, expirationTime, cachedCharset, secInfoSerialization, mChannel->GetSelfAddr(), mChannel->GetPeerAddr(), - redirectCount)) + redirectCount, + cacheKey)) { return NS_ERROR_UNEXPECTED; } @@ -1269,5 +1296,20 @@ HttpChannelParent::GetAuthPrompt(uint32_t aPromptReason, const nsIID& iid, return NS_OK; } +//----------------------------------------------------------------------------- +// HttpChannelSecurityWarningReporter +//----------------------------------------------------------------------------- + +nsresult +HttpChannelParent::ReportSecurityMessage(const nsAString& aMessageTag, + const nsAString& aMessageCategory) +{ + if (NS_WARN_IF(!SendReportSecurityMessage(nsString(aMessageTag), + nsString(aMessageCategory)))) { + return NS_ERROR_UNEXPECTED; + } + return NS_OK; +} + } // namespace net } // namespace mozilla diff --git a/netwerk/protocol/http/HttpChannelParent.h b/netwerk/protocol/http/HttpChannelParent.h index 441a84a6bf..1c9745f214 100644 --- a/netwerk/protocol/http/HttpChannelParent.h +++ b/netwerk/protocol/http/HttpChannelParent.h @@ -44,6 +44,7 @@ class HttpChannelParent final : public PHttpChannelParent , public nsIAuthPromptProvider , public nsINetworkInterceptController , public DisconnectableParent + , public HttpChannelSecurityWarningReporter { virtual ~HttpChannelParent(); @@ -121,6 +122,7 @@ protected: const uint32_t& aContentPolicyType, const uint32_t& aInnerWindowID, const OptionalHttpResponseHead& aSynthesizedResponseHead, + const OptionalHttpChannelCacheKey& aCacheKey, const bool& aAllowStaleCacheContent); virtual bool RecvSetPriority(const uint16_t& priority) override; @@ -155,6 +157,9 @@ protected: void OfflineDisconnect() override; uint32_t GetAppId() override; + nsresult ReportSecurityMessage(const nsAString& aMessageTag, + const nsAString& aMessageCategory) override; + private: nsRefPtr mChannel; nsCOMPtr mCacheEntry; diff --git a/netwerk/protocol/http/PHttpChannel.ipdl b/netwerk/protocol/http/PHttpChannel.ipdl index a0edc6a32d..03f3b8239d 100644 --- a/netwerk/protocol/http/PHttpChannel.ipdl +++ b/netwerk/protocol/http/PHttpChannel.ipdl @@ -8,15 +8,13 @@ include protocol PNecko; include InputStreamParams; include URIParams; +include NeckoChannelParams; include protocol PBlob; //FIXME: bug #792908 include "mozilla/net/NeckoMessageUtils.h"; -using RequestHeaderTuples from "mozilla/net/PHttpChannelParams.h"; using class nsHttpHeaderArray from "nsHttpHeaderArray.h"; -using class nsHttpResponseHead from "nsHttpResponseHead.h"; -using struct nsHttpAtom from "nsHttp.h"; using mozilla::net::NetAddr from "mozilla/net/DNS.h"; using struct mozilla::net::ResourceTimingStruct from "mozilla/net/TimingStruct.h"; @@ -93,7 +91,8 @@ child: nsCString securityInfoSerialization, NetAddr selfAddr, NetAddr peerAddr, - int16_t redirectCount); + int16_t redirectCount, + HttpChannelCacheKey cacheKey); // Combines a single OnDataAvailable and its associated OnProgress & // OnStatus calls into one IPDL message @@ -139,6 +138,10 @@ child: // OnDataAvailable and OnStopRequest messages in the queue back to the parent. DivertMessages(); + // Report a security message to the console associated with this + // channel. + ReportSecurityMessage(nsString messageTag, nsString messageCategory); + // Tell child to delete channel (all IPDL deletes must be done from child to // avoid races: see bug 591708). DeleteSelf(); diff --git a/netwerk/protocol/http/nsHttpChannel.cpp b/netwerk/protocol/http/nsHttpChannel.cpp index f3aea4d8b0..f2b03d2168 100644 --- a/netwerk/protocol/http/nsHttpChannel.cpp +++ b/netwerk/protocol/http/nsHttpChannel.cpp @@ -229,6 +229,7 @@ nsHttpChannel::nsHttpChannel() , mHasAutoRedirectVetoNotifier(0) , mPushedStream(nullptr) , mLocalBlocklist(false) + , mWarningReporter(nullptr) , mDidReval(false) { LOG(("Creating nsHttpChannel [this=%p]\n", this)); @@ -266,6 +267,19 @@ nsHttpChannel::Init(nsIURI *uri, return rv; } + +nsresult +nsHttpChannel::AddSecurityMessage(const nsAString& aMessageTag, + const nsAString& aMessageCategory) +{ + if (mWarningReporter) { + return mWarningReporter->ReportSecurityMessage(aMessageTag, + aMessageCategory); + } + return HttpBaseChannel::AddSecurityMessage(aMessageTag, + aMessageCategory); +} + //----------------------------------------------------------------------------- // nsHttpChannel //----------------------------------------------------------------------------- @@ -6092,35 +6106,6 @@ nsHttpChannel::SetOfflineCacheToken(nsISupports *token) return NS_ERROR_NOT_IMPLEMENTED; } -class nsHttpChannelCacheKey final : public nsISupportsPRUint32, - public nsISupportsCString -{ - NS_DECL_ISUPPORTS - - NS_DECL_NSISUPPORTSPRIMITIVE - NS_FORWARD_NSISUPPORTSPRUINT32(mSupportsPRUint32->) - - // Both interfaces declares toString method with the same signature. - // Thus we have to delegate only to nsISupportsPRUint32 implementation. - NS_IMETHOD GetData(nsACString & aData) override - { - return mSupportsCString->GetData(aData); - } - NS_IMETHOD SetData(const nsACString & aData) override - { - return mSupportsCString->SetData(aData); - } - -public: - nsresult SetData(uint32_t aPostID, const nsACString& aKey); - -protected: - ~nsHttpChannelCacheKey() {} - - nsCOMPtr mSupportsPRUint32; - nsCOMPtr mSupportsCString; -}; - NS_IMPL_ADDREF(nsHttpChannelCacheKey) NS_IMPL_RELEASE(nsHttpChannelCacheKey) NS_INTERFACE_TABLE_HEAD(nsHttpChannelCacheKey) @@ -6166,6 +6151,19 @@ nsresult nsHttpChannelCacheKey::SetData(uint32_t aPostID, return NS_OK; } +nsresult nsHttpChannelCacheKey::GetData(uint32_t *aPostID, + nsACString& aKey) +{ + nsresult rv; + + rv = mSupportsPRUint32->GetData(aPostID); + if (NS_FAILED(rv)) { + return rv; + } + + return mSupportsCString->GetData(aKey); +} + NS_IMETHODIMP nsHttpChannel::GetCacheKey(nsISupports **key) { diff --git a/netwerk/protocol/http/nsHttpChannel.h b/netwerk/protocol/http/nsHttpChannel.h index b004995742..f0e8bcb1ac 100644 --- a/netwerk/protocol/http/nsHttpChannel.h +++ b/netwerk/protocol/http/nsHttpChannel.h @@ -32,6 +32,48 @@ class nsISSLStatus; namespace mozilla { namespace net { class Http2PushedStream; + +class HttpChannelSecurityWarningReporter +{ +public: + virtual nsresult ReportSecurityMessage(const nsAString& aMessageTag, + const nsAString& aMessageCategory) = 0; +}; + +//----------------------------------------------------------------------------- +// nsHttpChannelCacheKey +//----------------------------------------------------------------------------- + +class nsHttpChannelCacheKey final : public nsISupportsPRUint32, + public nsISupportsCString +{ + NS_DECL_ISUPPORTS + + NS_DECL_NSISUPPORTSPRIMITIVE + NS_FORWARD_NSISUPPORTSPRUINT32(mSupportsPRUint32->) + + // Both interfaces declares toString method with the same signature. + // Thus we have to delegate only to nsISupportsPRUint32 implementation. + NS_IMETHOD GetData(nsACString & aData) override + { + return mSupportsCString->GetData(aData); + } + NS_IMETHOD SetData(const nsACString & aData) override + { + return mSupportsCString->SetData(aData); + } + +public: + nsresult SetData(uint32_t aPostID, const nsACString& aKey); + nsresult GetData(uint32_t *aPostID, nsACString& aKey); + +protected: + ~nsHttpChannelCacheKey() {} + + nsCOMPtr mSupportsPRUint32; + nsCOMPtr mSupportsCString; +}; + //----------------------------------------------------------------------------- // nsHttpChannel //----------------------------------------------------------------------------- @@ -139,6 +181,12 @@ public: NS_IMETHOD GetResponseStart(mozilla::TimeStamp *aResponseStart) override; NS_IMETHOD GetResponseEnd(mozilla::TimeStamp *aResponseEnd) override; + nsresult AddSecurityMessage(const nsAString& aMessageTag, + const nsAString& aMessageCategory) override; + + void SetWarningReporter(HttpChannelSecurityWarningReporter* aReporter) + { mWarningReporter = aReporter; } + public: /* internal necko use only */ void InternalSetUploadStream(nsIInputStream *uploadStream) @@ -479,6 +527,9 @@ private: nsCString mUsername; + // If non-null, warnings should be reported to this object. + HttpChannelSecurityWarningReporter* mWarningReporter; + protected: virtual void DoNotifyListenerCleanup() override; diff --git a/netwerk/protocol/viewsource/nsViewSourceChannel.cpp b/netwerk/protocol/viewsource/nsViewSourceChannel.cpp index 2e79317396..ab9c82261b 100644 --- a/netwerk/protocol/viewsource/nsViewSourceChannel.cpp +++ b/netwerk/protocol/viewsource/nsViewSourceChannel.cpp @@ -25,6 +25,7 @@ NS_INTERFACE_MAP_BEGIN(nsViewSourceChannel) NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIHttpChannel, mHttpChannel) NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIHttpChannelInternal, mHttpChannelInternal) NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsICachingChannel, mCachingChannel) + NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsICacheInfoChannel, mCacheInfoChannel) NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIApplicationCacheChannel, mApplicationCacheChannel) NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIUploadChannel, mUploadChannel) NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsIRequest, nsIViewSourceChannel) @@ -80,6 +81,7 @@ nsViewSourceChannel::Init(nsIURI* uri) mHttpChannel = do_QueryInterface(mChannel); mHttpChannelInternal = do_QueryInterface(mChannel); mCachingChannel = do_QueryInterface(mChannel); + mCacheInfoChannel = do_QueryInterface(mChannel); mApplicationCacheChannel = do_QueryInterface(mChannel); mUploadChannel = do_QueryInterface(mChannel); @@ -117,6 +119,7 @@ nsViewSourceChannel::InitSrcdoc(nsIURI* aURI, const nsAString &aSrcdoc) mHttpChannel = do_QueryInterface(mChannel); mHttpChannelInternal = do_QueryInterface(mChannel); mCachingChannel = do_QueryInterface(mChannel); + mCacheInfoChannel = do_QueryInterface(mChannel); mApplicationCacheChannel = do_QueryInterface(mChannel); mUploadChannel = do_QueryInterface(mChannel); return NS_OK; @@ -544,6 +547,7 @@ nsViewSourceChannel::OnStartRequest(nsIRequest *aRequest, nsISupports *aContext) mChannel = do_QueryInterface(aRequest); mHttpChannel = do_QueryInterface(aRequest); mCachingChannel = do_QueryInterface(aRequest); + mCacheInfoChannel = do_QueryInterface(mChannel); mUploadChannel = do_QueryInterface(aRequest); return mListener->OnStartRequest(static_cast diff --git a/netwerk/protocol/viewsource/nsViewSourceChannel.h b/netwerk/protocol/viewsource/nsViewSourceChannel.h index 8f63a5f4aa..e067ba5270 100644 --- a/netwerk/protocol/viewsource/nsViewSourceChannel.h +++ b/netwerk/protocol/viewsource/nsViewSourceChannel.h @@ -35,7 +35,7 @@ public: NS_DECL_NSISTREAMLISTENER NS_DECL_NSIREQUESTOBSERVER NS_DECL_NSIHTTPCHANNEL - NS_FORWARD_SAFE_NSICACHEINFOCHANNEL(mCachingChannel) + NS_FORWARD_SAFE_NSICACHEINFOCHANNEL(mCacheInfoChannel) NS_FORWARD_SAFE_NSICACHINGCHANNEL(mCachingChannel) NS_FORWARD_SAFE_NSIAPPLICATIONCACHECHANNEL(mApplicationCacheChannel) NS_FORWARD_SAFE_NSIAPPLICATIONCACHECONTAINER(mApplicationCacheChannel) @@ -58,6 +58,7 @@ protected: nsCOMPtr mHttpChannel; nsCOMPtr mHttpChannelInternal; nsCOMPtr mCachingChannel; + nsCOMPtr mCacheInfoChannel; nsCOMPtr mApplicationCacheChannel; nsCOMPtr mUploadChannel; nsCOMPtr mListener; diff --git a/uriloader/base/nsDocLoader.cpp b/uriloader/base/nsDocLoader.cpp index 308ad52710..368f17b2bf 100644 --- a/uriloader/base/nsDocLoader.cpp +++ b/uriloader/base/nsDocLoader.cpp @@ -37,7 +37,6 @@ static NS_DEFINE_CID(kThisImplCID, NS_THIS_DOCLOADER_IMPL_CID); -#if defined(PR_LOGGING) // // Log module for nsIDocumentLoader logging... // @@ -50,7 +49,6 @@ static NS_DEFINE_CID(kThisImplCID, NS_THIS_DOCLOADER_IMPL_CID); // the file nspr.log // PRLogModuleInfo* gDocLoaderLog = nullptr; -#endif /* PR_LOGGING */ #if defined(DEBUG) @@ -105,11 +103,9 @@ nsDocLoader::nsDocLoader() mDontFlushLayout(false), mIsFlushingLayout(false) { -#if defined(PR_LOGGING) if (nullptr == gDocLoaderLog) { gDocLoaderLog = PR_NewLogModule("DocLoader"); } -#endif /* PR_LOGGING */ static const PLDHashTableOps hash_table_ops = { @@ -402,7 +398,6 @@ nsDocLoader::OnStartRequest(nsIRequest *request, nsISupports *aCtxt) { // called each time a request is added to the group. -#ifdef PR_LOGGING if (PR_LOG_TEST(gDocLoaderLog, PR_LOG_DEBUG)) { nsAutoCString name; request->GetName(name); @@ -417,7 +412,7 @@ nsDocLoader::OnStartRequest(nsIRequest *request, nsISupports *aCtxt) (mIsLoadingDocument ? "true" : "false"), count)); } -#endif /* PR_LOGGING */ + bool bJustStartedLoading = false; nsLoadFlags loadFlags = 0; @@ -483,7 +478,6 @@ nsDocLoader::OnStopRequest(nsIRequest *aRequest, { nsresult rv = NS_OK; -#ifdef PR_LOGGING if (PR_LOG_TEST(gDocLoaderLog, PR_LOG_DEBUG)) { nsAutoCString name; aRequest->GetName(name); @@ -498,7 +492,6 @@ nsDocLoader::OnStopRequest(nsIRequest *aRequest, aStatus, (mIsLoadingDocument ? "true" : "false"), count)); } -#endif bool bFireTransferring = false; diff --git a/uriloader/base/nsURILoader.cpp b/uriloader/base/nsURILoader.cpp index 85fbbe225f..d0dde71646 100644 --- a/uriloader/base/nsURILoader.cpp +++ b/uriloader/base/nsURILoader.cpp @@ -51,9 +51,7 @@ #include "mozilla/Attributes.h" #include "mozilla/Preferences.h" -#ifdef PR_LOGGING PRLogModuleInfo* nsURILoader::mLog = nullptr; -#endif #define LOG(args) PR_LOG(nsURILoader::mLog, PR_LOG_DEBUG, args) #define LOG_ERROR(args) PR_LOG(nsURILoader::mLog, PR_LOG_ERROR, args) @@ -475,11 +473,9 @@ nsresult nsDocumentOpenInfo::DispatchContent(nsIRequest *request, nsISupports * LOG((" Content handler failed. Aborting load")); request->Cancel(rv); } -#ifdef PR_LOGGING else { LOG((" Content handler taking over load")); } -#endif return rv; } @@ -759,11 +755,9 @@ nsDocumentOpenInfo::TryContentListener(nsIURIContentListener* aListener, nsURILoader::nsURILoader() { -#ifdef PR_LOGGING if (!mLog) { mLog = PR_NewLogModule("URILoader"); } -#endif } nsURILoader::~nsURILoader() @@ -807,7 +801,6 @@ NS_IMETHODIMP nsURILoader::OpenURI(nsIChannel *channel, { NS_ENSURE_ARG_POINTER(channel); -#ifdef PR_LOGGING if (LOG_ENABLED()) { nsCOMPtr uri; channel->GetURI(getter_AddRefs(uri)); @@ -815,7 +808,6 @@ NS_IMETHODIMP nsURILoader::OpenURI(nsIChannel *channel, uri->GetAsciiSpec(spec); LOG(("nsURILoader::OpenURI for %s", spec.get())); } -#endif nsCOMPtr loader; nsresult rv = OpenChannel(channel, @@ -854,7 +846,6 @@ nsresult nsURILoader::OpenChannel(nsIChannel* channel, NS_ASSERTION(channel, "Trying to open a null channel!"); NS_ASSERTION(aWindowContext, "Window context must not be null"); -#ifdef PR_LOGGING if (LOG_ENABLED()) { nsCOMPtr uri; channel->GetURI(getter_AddRefs(uri)); @@ -862,7 +853,6 @@ nsresult nsURILoader::OpenChannel(nsIChannel* channel, uri->GetAsciiSpec(spec); LOG(("nsURILoader::OpenChannel for %s", spec.get())); } -#endif // Let the window context's uriListener know that the open is starting. This // gives that window a chance to abort the load process. diff --git a/uriloader/base/nsURILoader.h b/uriloader/base/nsURILoader.h index 647ed3cdcc..c909300078 100644 --- a/uriloader/base/nsURILoader.h +++ b/uriloader/base/nsURILoader.h @@ -48,12 +48,10 @@ protected: */ nsCOMArray m_listeners; -#ifdef PR_LOGGING /** * NSPR logging. The module is called "URILoader" */ static PRLogModuleInfo* mLog; -#endif friend class nsDocumentOpenInfo; }; diff --git a/uriloader/exthandler/nsExternalHelperAppService.cpp b/uriloader/exthandler/nsExternalHelperAppService.cpp index 04b2caea9b..a3a972bb51 100644 --- a/uriloader/exthandler/nsExternalHelperAppService.cpp +++ b/uriloader/exthandler/nsExternalHelperAppService.cpp @@ -122,9 +122,7 @@ enum { , NS_FOLDER_VALUE_CUSTOM = 2 }; -#ifdef PR_LOGGING PRLogModuleInfo* nsExternalHelperAppService::mLog = nullptr; -#endif // Using level 3 here because the OSHelperAppServices use a log level // of PR_LOG_DEBUG (4), and we want less detailed output here @@ -601,13 +599,11 @@ nsresult nsExternalHelperAppService::Init() if (!obs) return NS_ERROR_FAILURE; -#ifdef PR_LOGGING if (!mLog) { mLog = PR_NewLogModule("HelperAppService"); if (!mLog) return NS_ERROR_OUT_OF_MEMORY; } -#endif nsresult rv = obs->AddObserver(this, "profile-before-change", true); NS_ENSURE_SUCCESS(rv, rv); @@ -1624,12 +1620,10 @@ NS_IMETHODIMP nsExternalAppHandler::OnStartRequest(nsIRequest *request, nsISuppo nsresult transferError = rv; rv = CreateFailedTransfer(aChannel && NS_UsePrivateBrowsing(aChannel)); -#ifdef PR_LOGGING if (NS_FAILED(rv)) { LOG(("Failed to create transfer to report failure." "Will fallback to prompter!")); } -#endif mCanceled = true; request->Cancel(transferError); @@ -2650,7 +2644,6 @@ NS_IMETHODIMP nsExternalHelperAppService::GetFromTypeAndExtension(const nsACStri (*_retval)->SetPrimaryExtension(aFileExt); } -#ifdef PR_LOGGING if (LOG_ENABLED()) { nsAutoCString type; (*_retval)->GetMIMEType(type); @@ -2659,7 +2652,6 @@ NS_IMETHODIMP nsExternalHelperAppService::GetFromTypeAndExtension(const nsACStri (*_retval)->GetPrimaryExtension(ext); LOG(("MIME Info Summary: Type '%s', Primary Ext '%s'\n", type.get(), ext.get())); } -#endif return NS_OK; } diff --git a/uriloader/exthandler/nsExternalHelperAppService.h b/uriloader/exthandler/nsExternalHelperAppService.h index 1c943851f1..235c26b91a 100644 --- a/uriloader/exthandler/nsExternalHelperAppService.h +++ b/uriloader/exthandler/nsExternalHelperAppService.h @@ -141,7 +141,6 @@ protected: bool GetTypeFromExtras(const nsACString& aExtension, nsACString& aMIMEType); -#ifdef PR_LOGGING /** * NSPR Logging Module. Usage: set NSPR_LOG_MODULES=HelperAppService:level, * where level should be 2 for errors, 3 for debug messages from the cross- @@ -149,7 +148,6 @@ protected: */ static PRLogModuleInfo* mLog; -#endif // friend, so that it can access the nspr log module. friend class nsExternalAppHandler; diff --git a/uriloader/prefetch/OfflineCacheUpdateChild.cpp b/uriloader/prefetch/OfflineCacheUpdateChild.cpp index 7115304406..286d176f18 100644 --- a/uriloader/prefetch/OfflineCacheUpdateChild.cpp +++ b/uriloader/prefetch/OfflineCacheUpdateChild.cpp @@ -36,7 +36,6 @@ using namespace mozilla::net; using mozilla::dom::TabChild; using mozilla::dom::ContentChild; -#if defined(PR_LOGGING) // // To enable logging (see prlog.h for full details): // @@ -47,7 +46,6 @@ using mozilla::dom::ContentChild; // the file offlineupdate.log // extern PRLogModuleInfo *gOfflineCacheUpdateLog; -#endif #undef LOG #define LOG(args) PR_LOG(gOfflineCacheUpdateLog, 4, args) @@ -153,7 +151,6 @@ OfflineCacheUpdateChild::AssociateDocument(nsIDOMDocument *aDocument, NS_ENSURE_SUCCESS(rv, rv); if (!existingCache) { -#if defined(PR_LOGGING) if (LOG_ENABLED()) { nsAutoCString clientID; if (aApplicationCache) { @@ -162,7 +159,6 @@ OfflineCacheUpdateChild::AssociateDocument(nsIDOMDocument *aDocument, LOG(("Update %p: associating app cache %s to document %p", this, clientID.get(), aDocument)); } -#endif rv = container->SetApplicationCache(aApplicationCache); NS_ENSURE_SUCCESS(rv, rv); diff --git a/uriloader/prefetch/OfflineCacheUpdateGlue.cpp b/uriloader/prefetch/OfflineCacheUpdateGlue.cpp index 751ce36d55..9a8374bdc6 100644 --- a/uriloader/prefetch/OfflineCacheUpdateGlue.cpp +++ b/uriloader/prefetch/OfflineCacheUpdateGlue.cpp @@ -14,7 +14,6 @@ #include "nsIDocument.h" #include "mozilla/Logging.h" -#if defined(PR_LOGGING) // // To enable logging (see prlog.h for full details): // @@ -25,7 +24,6 @@ // the file offlineupdate.log // extern PRLogModuleInfo *gOfflineCacheUpdateLog; -#endif #undef LOG #define LOG(args) PR_LOG(gOfflineCacheUpdateLog, 4, args) @@ -203,7 +201,6 @@ OfflineCacheUpdateGlue::ApplicationCacheAvailable(nsIApplicationCache *aApplicat NS_ENSURE_SUCCESS(rv, rv); if (!existingCache) { -#if defined(PR_LOGGING) if (LOG_ENABLED()) { nsAutoCString clientID; if (aApplicationCache) { @@ -212,7 +209,6 @@ OfflineCacheUpdateGlue::ApplicationCacheAvailable(nsIApplicationCache *aApplicat LOG(("Update %p: associating app cache %s to document %p", this, clientID.get(), mDocument.get())); } -#endif rv = container->SetApplicationCache(aApplicationCache); NS_ENSURE_SUCCESS(rv, rv); diff --git a/uriloader/prefetch/OfflineCacheUpdateParent.cpp b/uriloader/prefetch/OfflineCacheUpdateParent.cpp index 44102bb43d..cbb210ab18 100644 --- a/uriloader/prefetch/OfflineCacheUpdateParent.cpp +++ b/uriloader/prefetch/OfflineCacheUpdateParent.cpp @@ -17,7 +17,6 @@ using namespace mozilla::ipc; using mozilla::dom::TabParent; -#if defined(PR_LOGGING) // // To enable logging (see prlog.h for full details): // @@ -28,7 +27,6 @@ using mozilla::dom::TabParent; // the file offlineupdate.log // extern PRLogModuleInfo *gOfflineCacheUpdateLog; -#endif #undef LOG #define LOG(args) PR_LOG(gOfflineCacheUpdateLog, 4, args) diff --git a/uriloader/prefetch/nsOfflineCacheUpdate.cpp b/uriloader/prefetch/nsOfflineCacheUpdate.cpp index ec0bfb5fd9..b8656d4b2c 100644 --- a/uriloader/prefetch/nsOfflineCacheUpdate.cpp +++ b/uriloader/prefetch/nsOfflineCacheUpdate.cpp @@ -51,7 +51,6 @@ static const uint32_t kParallelLoadLimit = 15; // Quota for offline apps when preloading static const int32_t kCustomProfileQuota = 512000; -#if defined(PR_LOGGING) // // To enable logging (see prlog.h for full details): // @@ -62,7 +61,6 @@ static const int32_t kCustomProfileQuota = 512000; // the file offlineupdate.log // extern PRLogModuleInfo *gOfflineCacheUpdateLog; -#endif #undef LOG #define LOG(args) PR_LOG(gOfflineCacheUpdateLog, 4, args) @@ -343,13 +341,11 @@ nsOfflineCacheUpdateItem::~nsOfflineCacheUpdateItem() nsresult nsOfflineCacheUpdateItem::OpenChannel(nsOfflineCacheUpdate *aUpdate) { -#if defined(PR_LOGGING) if (LOG_ENABLED()) { nsAutoCString spec; mURI->GetSpec(spec); LOG(("%p: Opening channel for %s", this, spec.get())); } -#endif if (mUpdate) { // Holding a reference to the update means this item is already @@ -467,14 +463,12 @@ nsOfflineCacheUpdateItem::OnStopRequest(nsIRequest *aRequest, nsISupports *aContext, nsresult aStatus) { -#if defined(PR_LOGGING) if (LOG_ENABLED()) { nsAutoCString spec; mURI->GetSpec(spec); LOG(("%p: Done fetching offline item %s [status=%x]\n", this, spec.get(), aStatus)); } -#endif if (mBytesRead == 0 && aStatus == NS_OK) { // we didn't need to read (because LOAD_ONLY_IF_MODIFIED was @@ -1880,13 +1874,11 @@ nsOfflineCacheUpdate::ProcessNextURI() return NS_OK; } -#if defined(PR_LOGGING) if (LOG_ENABLED()) { nsAutoCString spec; runItem->mURI->GetSpec(spec); LOG(("%p: Opening channel for %s", this, spec.get())); } -#endif ++mItemsInProgress; NotifyState(nsIOfflineCacheUpdateObserver::STATE_ITEMSTARTED); diff --git a/uriloader/prefetch/nsOfflineCacheUpdateService.cpp b/uriloader/prefetch/nsOfflineCacheUpdateService.cpp index 3fb585454a..04514e6215 100644 --- a/uriloader/prefetch/nsOfflineCacheUpdateService.cpp +++ b/uriloader/prefetch/nsOfflineCacheUpdateService.cpp @@ -70,7 +70,6 @@ typedef mozilla::docshell::OfflineCacheUpdateParent OfflineCacheUpdateParent; typedef mozilla::docshell::OfflineCacheUpdateChild OfflineCacheUpdateChild; typedef mozilla::docshell::OfflineCacheUpdateGlue OfflineCacheUpdateGlue; -#if defined(PR_LOGGING) // // To enable logging (see prlog.h for full details): // @@ -81,7 +80,6 @@ typedef mozilla::docshell::OfflineCacheUpdateGlue OfflineCacheUpdateGlue; // the file offlineupdate.log // PRLogModuleInfo *gOfflineCacheUpdateLog; -#endif #undef LOG #define LOG(args) PR_LOG(gOfflineCacheUpdateLog, 4, args) @@ -295,10 +293,8 @@ nsOfflineCacheUpdateService::~nsOfflineCacheUpdateService() nsresult nsOfflineCacheUpdateService::Init() { -#if defined(PR_LOGGING) if (!gOfflineCacheUpdateLog) gOfflineCacheUpdateLog = PR_NewLogModule("nsOfflineCacheUpdate"); -#endif // Observe xpcom-shutdown event nsCOMPtr observerService = diff --git a/uriloader/prefetch/nsPrefetchService.cpp b/uriloader/prefetch/nsPrefetchService.cpp index 3a48dbb9d4..ab957c72e0 100644 --- a/uriloader/prefetch/nsPrefetchService.cpp +++ b/uriloader/prefetch/nsPrefetchService.cpp @@ -32,7 +32,6 @@ using namespace mozilla; -#if defined(PR_LOGGING) // // To enable logging (see prlog.h for full details): // @@ -43,7 +42,6 @@ using namespace mozilla; // the file http.log // static PRLogModuleInfo *gPrefetchLog; -#endif #undef LOG #define LOG(args) PR_LOG(gPrefetchLog, 4, args) @@ -419,10 +417,8 @@ nsPrefetchService::~nsPrefetchService() nsresult nsPrefetchService::Init() { -#if defined(PR_LOGGING) if (!gPrefetchLog) gPrefetchLog = PR_NewLogModule("nsPrefetch"); -#endif nsresult rv; @@ -458,13 +454,11 @@ nsPrefetchService::ProcessNextURI() if (NS_FAILED(rv)) break; -#if defined(PR_LOGGING) if (LOG_ENABLED()) { nsAutoCString spec; mCurrentNode->mURI->GetSpec(spec); LOG(("ProcessNextURI [%s]\n", spec.get())); } -#endif // // if opening the channel fails, then just skip to the next uri @@ -645,13 +639,11 @@ nsPrefetchService::Prefetch(nsIURI *aURI, NS_ENSURE_ARG_POINTER(aURI); NS_ENSURE_ARG_POINTER(aReferrerURI); -#if defined(PR_LOGGING) if (LOG_ENABLED()) { nsAutoCString spec; aURI->GetSpec(spec); LOG(("PrefetchURI [%s]\n", spec.get())); } -#endif if (mDisabled) { LOG(("rejected: prefetch service is disabled\n"));