Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Base class for all our document implementations.
*/
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentInlines.h"
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <type_traits>
#include "Attr.h"
#include "AutoplayPolicy.h"
#include "ErrorList.h"
#include "ExpandedPrincipal.h"
#include "MainThreadUtils.h"
#include "MobileViewportManager.h"
#include "NodeUbiReporting.h"
#include "PLDHashTable.h"
#include "StorageAccessPermissionRequest.h"
#include "ThirdPartyUtil.h"
#include "domstubs.h"
#include "gfxPlatform.h"
#include "imgIContainer.h"
#include "imgLoader.h"
#include "imgRequestProxy.h"
#include "js/Value.h"
#include "jsapi.h"
#include "mozAutoDocUpdate.h"
#include "mozIDOMWindow.h"
#include "mozIThirdPartyUtil.h"
#include "mozilla/AbstractTimelineMarker.h"
#include "mozilla/AntiTrackingUtils.h"
#include "mozilla/ArrayIterator.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Base64.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/CSSEnabledState.h"
#include "mozilla/ContentBlockingAllowList.h"
#include "mozilla/ContentBlockingNotifier.h"
#include "mozilla/ContentBlockingUserInteraction.h"
#include "mozilla/ContentPrincipal.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/DocLoadingTimelineMarker.h"
#include "mozilla/DocumentStyleRootIterator.h"
#include "mozilla/EditorBase.h"
#include "mozilla/EditorCommands.h"
#include "mozilla/Encoding.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventListenerManager.h"
#include "mozilla/EventQueue.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/ExtensionPolicyService.h"
#include "mozilla/FullscreenChange.h"
#include "mozilla/GlobalStyleSheetCache.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/IdentifierMapEntry.h"
#include "mozilla/InputTaskManager.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/InternalMutationEvent.h"
#include "mozilla/Likely.h"
#include "mozilla/Logging.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/MacroForEach.h"
#include "mozilla/Maybe.h"
#include "mozilla/MediaFeatureChange.h"
#include "mozilla/MediaManager.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/NullPrincipal.h"
#include "mozilla/OriginAttributes.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/PendingAnimationTracker.h"
#include "mozilla/PendingFullscreenEvent.h"
#include "mozilla/PermissionDelegateHandler.h"
#include "mozilla/PermissionManager.h"
#include "mozilla/Preferences.h"
#include "mozilla/PreloadHashKey.h"
#include "mozilla/PresShell.h"
#include "mozilla/PresShellForwards.h"
#include "mozilla/PresShellInlines.h"
#include "mozilla/PseudoStyleType.h"
#include "mozilla/RefCountType.h"
#include "mozilla/RejectForeignAllowList.h"
#include "mozilla/RelativeTo.h"
#include "mozilla/RestyleManager.h"
#include "mozilla/ReverseIterator.h"
#include "mozilla/SMILAnimationController.h"
#include "mozilla/SMILTimeContainer.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Components.h"
#include "mozilla/ServoStyleConsts.h"
#include "mozilla/ServoStyleSet.h"
#include "mozilla/ServoTypes.h"
#include "mozilla/SizeOfState.h"
#include "mozilla/Span.h"
#include "mozilla/Sprintf.h"
#include "mozilla/StaticAnalysisFunctions.h"
#include "mozilla/StaticPrefs_apz.h"
#include "mozilla/StaticPrefs_browser.h"
#include "mozilla/StaticPrefs_docshell.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_fission.h"
#include "mozilla/StaticPrefs_full_screen_api.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPrefs_network.h"
#include "mozilla/StaticPrefs_page_load.h"
#include "mozilla/StaticPrefs_plugins.h"
#include "mozilla/StaticPrefs_privacy.h"
#include "mozilla/StaticPrefs_security.h"
#include "mozilla/StaticPrefs_widget.h"
#include "mozilla/StaticPresData.h"
#include "mozilla/StorageAccess.h"
#include "mozilla/StoragePrincipalHelper.h"
#include "mozilla/StyleSheet.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TelemetryHistogramEnums.h"
#include "mozilla/TelemetryScalarEnums.h"
#include "mozilla/TextControlElement.h"
#include "mozilla/TextEditor.h"
#include "mozilla/TimelineConsumers.h"
#include "mozilla/TypedEnumBits.h"
#include "mozilla/URLDecorationStripper.h"
#include "mozilla/URLExtraData.h"
#include "mozilla/Unused.h"
#include "mozilla/css/ImageLoader.h"
#include "mozilla/css/Loader.h"
#include "mozilla/css/Rule.h"
#include "mozilla/css/SheetParsingMode.h"
#include "mozilla/dom/AnonymousContent.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/BrowsingContextGroup.h"
#include "mozilla/dom/CDATASection.h"
#include "mozilla/dom/CSPDictionariesBinding.h"
#include "mozilla/dom/CanonicalBrowsingContext.h"
#include "mozilla/dom/ChromeObserver.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/ClientState.h"
#include "mozilla/dom/Comment.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/DOMImplementation.h"
#include "mozilla/dom/DOMIntersectionObserver.h"
#include "mozilla/dom/DOMStringList.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/dom/DocumentBinding.h"
#include "mozilla/dom/DocumentFragment.h"
#include "mozilla/dom/DocumentL10n.h"
#include "mozilla/dom/DocumentTimeline.h"
#include "mozilla/dom/DocumentType.h"
#include "mozilla/dom/ElementBinding.h"
#include "mozilla/dom/Event.h"
#include "mozilla/dom/EventListenerBinding.h"
#include "mozilla/dom/FailedCertSecurityInfoBinding.h"
#include "mozilla/dom/FeaturePolicy.h"
#include "mozilla/dom/FeaturePolicyUtils.h"
#include "mozilla/dom/FontFaceSet.h"
#include "mozilla/dom/FromParser.h"
#include "mozilla/dom/HTMLAllCollection.h"
#include "mozilla/dom/HTMLBodyElement.h"
#include "mozilla/dom/HTMLCollectionBinding.h"
#include "mozilla/dom/HTMLDialogElement.h"
#include "mozilla/dom/HTMLFormElement.h"
#include "mozilla/dom/HTMLIFrameElement.h"
#include "mozilla/dom/HTMLImageElement.h"
#include "mozilla/dom/HTMLInputElement.h"
#include "mozilla/dom/HTMLLinkElement.h"
#include "mozilla/dom/HTMLMediaElement.h"
#include "mozilla/dom/HTMLMetaElement.h"
#include "mozilla/dom/HTMLSharedElement.h"
#include "mozilla/dom/HTMLTextAreaElement.h"
#include "mozilla/dom/ImageTracker.h"
#include "mozilla/dom/Link.h"
#include "mozilla/dom/MediaQueryList.h"
#include "mozilla/dom/MediaSource.h"
#include "mozilla/dom/MutationObservers.h"
#include "mozilla/dom/NameSpaceConstants.h"
#include "mozilla/dom/Navigator.h"
#include "mozilla/dom/NetErrorInfoBinding.h"
#include "mozilla/dom/NodeInfo.h"
#include "mozilla/dom/NodeIterator.h"
#include "mozilla/dom/PContentChild.h"
#include "mozilla/dom/PWindowGlobalChild.h"
#include "mozilla/dom/PageTransitionEvent.h"
#include "mozilla/dom/PageTransitionEventBinding.h"
#include "mozilla/dom/Performance.h"
#include "mozilla/dom/PermissionMessageUtils.h"
#include "mozilla/dom/PostMessageEvent.h"
#include "mozilla/dom/ProcessingInstruction.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/PromiseNativeHandler.h"
#include "mozilla/dom/ResizeObserverController.h"
#include "mozilla/dom/SVGElement.h"
#include "mozilla/dom/SVGDocument.h"
#include "mozilla/dom/SVGSVGElement.h"
#include "mozilla/dom/SVGUseElement.h"
#include "mozilla/dom/ScriptLoader.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/ServiceWorkerContainer.h"
#include "mozilla/dom/ServiceWorkerDescriptor.h"
#include "mozilla/dom/ServiceWorkerManager.h"
#include "mozilla/dom/ShadowIncludingTreeIterator.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/StyleSheetApplicableStateChangeEvent.h"
#include "mozilla/dom/StyleSheetApplicableStateChangeEventBinding.h"
#include "mozilla/dom/StyleSheetList.h"
#include "mozilla/dom/TimeoutManager.h"
#include "mozilla/dom/Touch.h"
#include "mozilla/dom/TouchEvent.h"
#include "mozilla/dom/TreeOrderedArrayInlines.h"
#include "mozilla/dom/TreeWalker.h"
#include "mozilla/dom/URL.h"
#include "mozilla/dom/UserActivation.h"
#include "mozilla/dom/WindowBinding.h"
#include "mozilla/dom/WindowContext.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/WindowProxyHolder.h"
#include "mozilla/dom/WorkerDocumentListener.h"
#include "mozilla/dom/XPathEvaluator.h"
#include "mozilla/dom/nsCSPContext.h"
#include "mozilla/dom/nsCSPUtils.h"
#include "mozilla/extensions/WebExtensionPolicy.h"
#include "mozilla/fallible.h"
#include "mozilla/gfx/BaseCoord.h"
#include "mozilla/gfx/BaseSize.h"
#include "mozilla/gfx/Coord.h"
#include "mozilla/gfx/Point.h"
#include "mozilla/gfx/ScaleFactor.h"
#include "mozilla/glean/GleanMetrics.h"
#include "mozilla/intl/LocaleService.h"
#include "mozilla/ipc/IdleSchedulerChild.h"
#include "mozilla/ipc/MessageChannel.h"
#include "mozilla/net/ChannelEventQueue.h"
#include "mozilla/net/CookieJarSettings.h"
#include "mozilla/net/NeckoChannelParams.h"
#include "mozilla/net/RequestContextService.h"
#include "nsAboutProtocolUtils.h"
#include "nsAlgorithm.h"
#include "nsAttrValue.h"
#include "nsAttrValueInlines.h"
#include "nsBaseHashtable.h"
#include "nsBidiUtils.h"
#include "nsCRT.h"
#include "nsCSSPropertyID.h"
#include "nsCSSProps.h"
#include "nsCSSPseudoElements.h"
#include "nsCSSRendering.h"
#include "nsCanvasFrame.h"
#include "nsCaseTreatment.h"
#include "nsCharsetSource.h"
#include "nsCommandManager.h"
#include "nsCommandParams.h"
#include "nsComponentManagerUtils.h"
#include "nsContentCreatorFunctions.h"
#include "nsContentList.h"
#include "nsContentPermissionHelper.h"
#include "nsContentSecurityUtils.h"
#include "nsContentUtils.h"
#include "nsCoord.h"
#include "nsCycleCollectionNoteChild.h"
#include "nsCycleCollectionTraversalCallback.h"
#include "nsDOMAttributeMap.h"
#include "nsDOMCaretPosition.h"
#include "nsDOMNavigationTiming.h"
#include "nsDOMString.h"
#include "nsDeviceContext.h"
#include "nsDocShell.h"
#include "nsDocShellLoadTypes.h"
#include "nsEffectiveTLDService.h"
#include "nsError.h"
#include "nsEscape.h"
#include "nsFocusManager.h"
#include "nsFrameLoader.h"
#include "nsFrameLoaderOwner.h"
#include "nsGenericHTMLElement.h"
#include "nsGlobalWindowInner.h"
#include "nsGlobalWindowOuter.h"
#include "nsHTMLCSSStyleSheet.h"
#include "nsHTMLDocument.h"
#include "nsHTMLStyleSheet.h"
#include "nsHtml5Module.h"
#include "nsHtml5Parser.h"
#include "nsHtml5TreeOpExecutor.h"
#include "nsIAsyncShutdown.h"
#include "nsIAuthPrompt.h"
#include "nsIAuthPrompt2.h"
#include "nsIBFCacheEntry.h"
#include "nsIBaseWindow.h"
#include "nsIBrowserChild.h"
#include "nsIBrowserUsage.h"
#include "nsICSSLoaderObserver.h"
#include "nsICategoryManager.h"
#include "nsICertOverrideService.h"
#include "nsIContent.h"
#include "nsIContentInlines.h"
#include "nsIContentPolicy.h"
#include "nsIContentSecurityPolicy.h"
#include "nsIContentSink.h"
#include "nsICookieJarSettings.h"
#include "nsICookieService.h"
#include "nsIDOMXULCommandDispatcher.h"
#include "nsIDocShell.h"
#include "nsIDocShellTreeItem.h"
#include "nsIDocumentActivity.h"
#include "nsIDocumentEncoder.h"
#include "nsIDocumentLoader.h"
#include "nsIDocumentLoaderFactory.h"
#include "nsIDocumentObserver.h"
#include "nsIEditingSession.h"
#include "nsIEditor.h"
#include "nsIEffectiveTLDService.h"
#include "nsIFile.h"
#include "nsIFileChannel.h"
#include "nsIFrame.h"
#include "nsIGlobalObject.h"
#include "nsIHTMLCollection.h"
#include "nsIHttpChannel.h"
#include "nsIHttpChannelInternal.h"
#include "nsIIOService.h"
#include "nsIImageLoadingContent.h"
#include "nsIInlineSpellChecker.h"
#include "nsIInputStreamChannel.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsILayoutHistoryState.h"
#include "nsIMultiPartChannel.h"
#include "nsIMutationObserver.h"
#include "nsINSSErrorsService.h"
#include "nsINamed.h"
#include "nsINodeList.h"
#include "nsIObjectLoadingContent.h"
#include "nsIObserverService.h"
#include "nsIPermission.h"
#include "nsIPrompt.h"
#include "nsIPropertyBag2.h"
#include "nsIPublicKeyPinningService.h"
#include "nsIReferrerInfo.h"
#include "nsIRefreshURI.h"
#include "nsIRequest.h"
#include "nsIRequestContext.h"
#include "nsIRunnable.h"
#include "nsISHEntry.h"
#include "nsIScriptElement.h"
#include "nsIScriptError.h"
#include "nsIScriptGlobalObject.h"
#include "nsIScriptSecurityManager.h"
#include "nsISecurityConsoleMessage.h"
#include "nsISelectionController.h"
#include "nsISerialEventTarget.h"
#include "nsISimpleEnumerator.h"
#include "nsISiteSecurityService.h"
#include "nsISocketProvider.h"
#include "nsISpeculativeConnect.h"
#include "nsIStructuredCloneContainer.h"
#include "nsIThread.h"
#include "nsITimedChannel.h"
#include "nsITimer.h"
#include "nsITransportSecurityInfo.h"
#include "nsIURIMutator.h"
#include "nsIVariant.h"
#include "nsIWeakReference.h"
#include "nsIWebNavigation.h"
#include "nsIWidget.h"
#include "nsIX509Cert.h"
#include "nsIX509CertValidity.h"
#include "nsIXMLContentSink.h"
#include "nsIXULRuntime.h"
#include "nsImageLoadingContent.h"
#include "nsImportModule.h"
#include "nsLanguageAtomService.h"
#include "nsLayoutUtils.h"
#include "nsNetCID.h"
#include "nsNetUtil.h"
#include "nsNodeInfoManager.h"
#include "nsObjectLoadingContent.h"
#include "nsPIDOMWindowInlines.h"
#include "nsPIWindowRoot.h"
#include "nsPoint.h"
#include "nsPointerHashKeys.h"
#include "nsPresContext.h"
#include "nsQueryFrame.h"
#include "nsQueryObject.h"
#include "nsRange.h"
#include "nsRect.h"
#include "nsRefreshDriver.h"
#include "nsSandboxFlags.h"
#include "nsSerializationHelper.h"
#include "nsServiceManagerUtils.h"
#include "nsStringFlags.h"
#include "nsStyleUtil.h"
#include "nsStringIterator.h"
#include "nsStyleSheetService.h"
#include "nsStyleStruct.h"
#include "nsTextNode.h"
#include "nsUnicharUtils.h"
#include "nsWrapperCache.h"
#include "nsWrapperCacheInlines.h"
#include "nsXPCOMCID.h"
#include "nsXULAppAPI.h"
#include "prthread.h"
#include "prtime.h"
#include "prtypes.h"
#include "xpcpublic.h"
// XXX Must be included after mozilla/Encoding.h
#include "encoding_rs.h"
#include "mozilla/dom/XULBroadcastManager.h"
#include "mozilla/dom/XULPersist.h"
#include "nsIAppWindow.h"
#include "nsXULPrototypeDocument.h"
#include "nsXULCommandDispatcher.h"
#include "nsXULPopupManager.h"
#include "nsIDocShellTreeOwner.h"
#define XML_DECLARATION_BITS_DECLARATION_EXISTS (1 << 0)
#define XML_DECLARATION_BITS_ENCODING_EXISTS (1 << 1)
#define XML_DECLARATION_BITS_STANDALONE_EXISTS (1 << 2)
#define XML_DECLARATION_BITS_STANDALONE_YES (1 << 3)
#define NS_MAX_DOCUMENT_WRITE_DEPTH 20
mozilla::LazyLogModule gPageCacheLog("PageCache");
mozilla::LazyLogModule gSHIPBFCacheLog("SHIPBFCache");
mozilla::LazyLogModule gTimeoutDeferralLog("TimeoutDefer");
mozilla::LazyLogModule gUseCountersLog("UseCounters");
namespace mozilla {
namespace dom {
class Document::HeaderData {
public:
HeaderData(nsAtom* aField, const nsAString& aData)
: mField(aField), mData(aData) {}
~HeaderData() {
// Delete iteratively to avoid blowing up the stack, though it shouldn't
// happen in practice.
UniquePtr<HeaderData> next = std::move(mNext);
while (next) {
next = std::move(next->mNext);
}
}
RefPtr<nsAtom> mField;
nsString mData;
UniquePtr<HeaderData> mNext;
};
using LinkArray = nsTArray<Link*>;
AutoTArray<Document*, 8>* Document::sLoadingForegroundTopLevelContentDocument =
nullptr;
static LazyLogModule gDocumentLeakPRLog("DocumentLeak");
static LazyLogModule gCspPRLog("CSP");
LazyLogModule gUserInteractionPRLog("UserInteraction");
static nsresult GetHttpChannelHelper(nsIChannel* aChannel,
nsIHttpChannel** aHttpChannel) {
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
if (httpChannel) {
httpChannel.forget(aHttpChannel);
return NS_OK;
}
nsCOMPtr<nsIMultiPartChannel> multipart = do_QueryInterface(aChannel);
if (!multipart) {
*aHttpChannel = nullptr;
return NS_OK;
}
nsCOMPtr<nsIChannel> baseChannel;
nsresult rv = multipart->GetBaseChannel(getter_AddRefs(baseChannel));
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
httpChannel = do_QueryInterface(baseChannel);
httpChannel.forget(aHttpChannel);
return NS_OK;
}
} // namespace dom
#define NAME_NOT_VALID ((nsSimpleContentList*)1)
IdentifierMapEntry::IdentifierMapEntry(
const IdentifierMapEntry::DependentAtomOrString* aKey)
: mKey(aKey ? *aKey : nullptr) {}
void IdentifierMapEntry::Traverse(
nsCycleCollectionTraversalCallback* aCallback) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mIdentifierMap mNameContentList");
aCallback->NoteXPCOMChild(static_cast<nsINodeList*>(mNameContentList));
if (mImageElement) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mIdentifierMap mImageElement element");
nsIContent* imageElement = mImageElement;
aCallback->NoteXPCOMChild(imageElement);
}
}
bool IdentifierMapEntry::IsEmpty() {
return mIdContentList->IsEmpty() && !mNameContentList && !mChangeCallbacks &&
!mImageElement;
}
bool IdentifierMapEntry::HasNameElement() const {
return mNameContentList && mNameContentList->Length() != 0;
}
void IdentifierMapEntry::AddContentChangeCallback(
Document::IDTargetObserver aCallback, void* aData, bool aForImage) {
if (!mChangeCallbacks) {
mChangeCallbacks = MakeUnique<nsTHashtable<ChangeCallbackEntry>>();
}
ChangeCallback cc = {aCallback, aData, aForImage};
mChangeCallbacks->PutEntry(cc);
}
void IdentifierMapEntry::RemoveContentChangeCallback(
Document::IDTargetObserver aCallback, void* aData, bool aForImage) {
if (!mChangeCallbacks) return;
ChangeCallback cc = {aCallback, aData, aForImage};
mChangeCallbacks->RemoveEntry(cc);
if (mChangeCallbacks->Count() == 0) {
mChangeCallbacks = nullptr;
}
}
void IdentifierMapEntry::FireChangeCallbacks(Element* aOldElement,
Element* aNewElement,
bool aImageOnly) {
if (!mChangeCallbacks) return;
for (auto iter = mChangeCallbacks->Iter(); !iter.Done(); iter.Next()) {
IdentifierMapEntry::ChangeCallbackEntry* entry = iter.Get();
// Don't fire image changes for non-image observers, and don't fire element
// changes for image observers when an image override is active.
if (entry->mKey.mForImage ? (mImageElement && !aImageOnly) : aImageOnly) {
continue;
}
if (!entry->mKey.mCallback(aOldElement, aNewElement, entry->mKey.mData)) {
iter.Remove();
}
}
}
void IdentifierMapEntry::AddIdElement(Element* aElement) {
MOZ_ASSERT(aElement, "Must have element");
MOZ_ASSERT(!mIdContentList->Contains(nullptr), "Why is null in our list?");
size_t index = mIdContentList.Insert(*aElement);
if (index == 0) {
Element* oldElement = mIdContentList->SafeElementAt(1);
FireChangeCallbacks(oldElement, aElement);
}
}
void IdentifierMapEntry::RemoveIdElement(Element* aElement) {
MOZ_ASSERT(aElement, "Missing element");
// This should only be called while the document is in an update.
// Assertions near the call to this method guarantee this.
// This could fire in OOM situations
// Only assert this in HTML documents for now as XUL does all sorts of weird
// crap.
NS_ASSERTION(!aElement->OwnerDoc()->IsHTMLDocument() ||
mIdContentList->Contains(aElement),
"Removing id entry that doesn't exist");
// XXXbz should this ever Compact() I guess when all the content is gone
// we'll just get cleaned up in the natural order of things...
Element* currentElement = mIdContentList->SafeElementAt(0);
mIdContentList.RemoveElement(*aElement);
if (currentElement == aElement) {
FireChangeCallbacks(currentElement, mIdContentList->SafeElementAt(0));
}
}
void IdentifierMapEntry::SetImageElement(Element* aElement) {
Element* oldElement = GetImageIdElement();
mImageElement = aElement;
Element* newElement = GetImageIdElement();
if (oldElement != newElement) {
FireChangeCallbacks(oldElement, newElement, true);
}
}
void IdentifierMapEntry::ClearAndNotify() {
Element* currentElement = mIdContentList->SafeElementAt(0);
mIdContentList.Clear();
if (currentElement) {
FireChangeCallbacks(currentElement, nullptr);
}
mNameContentList = nullptr;
if (mImageElement) {
SetImageElement(nullptr);
}
mChangeCallbacks = nullptr;
}
namespace dom {
class SimpleHTMLCollection final : public nsSimpleContentList,
public nsIHTMLCollection {
public:
explicit SimpleHTMLCollection(nsINode* aRoot) : nsSimpleContentList(aRoot) {}
NS_DECL_ISUPPORTS_INHERITED
virtual nsINode* GetParentObject() override {
return nsSimpleContentList::GetParentObject();
}
virtual uint32_t Length() override { return nsSimpleContentList::Length(); }
virtual Element* GetElementAt(uint32_t aIndex) override {
return mElements.SafeElementAt(aIndex)->AsElement();
}
virtual Element* GetFirstNamedElement(const nsAString& aName,
bool& aFound) override {
aFound = false;
RefPtr<nsAtom> name = NS_Atomize(aName);
for (uint32_t i = 0; i < mElements.Length(); i++) {
MOZ_DIAGNOSTIC_ASSERT(mElements[i]);
Element* element = mElements[i]->AsElement();
if (element->GetID() == name ||
(element->HasName() &&
element->GetParsedAttr(nsGkAtoms::name)->GetAtomValue() == name)) {
aFound = true;
return element;
}
}
return nullptr;
}
virtual void GetSupportedNames(nsTArray<nsString>& aNames) override {
AutoTArray<nsAtom*, 8> atoms;
for (uint32_t i = 0; i < mElements.Length(); i++) {
MOZ_DIAGNOSTIC_ASSERT(mElements[i]);
Element* element = mElements[i]->AsElement();
nsAtom* id = element->GetID();
MOZ_ASSERT(id != nsGkAtoms::_empty);
if (id && !atoms.Contains(id)) {
atoms.AppendElement(id);
}
if (element->HasName()) {
nsAtom* name = element->GetParsedAttr(nsGkAtoms::name)->GetAtomValue();
MOZ_ASSERT(name && name != nsGkAtoms::_empty);
if (name && !atoms.Contains(name)) {
atoms.AppendElement(name);
}
}
}
nsString* names = aNames.AppendElements(atoms.Length());
for (uint32_t i = 0; i < atoms.Length(); i++) {
atoms[i]->ToString(names[i]);
}
}
virtual JSObject* GetWrapperPreserveColorInternal() override {
return nsWrapperCache::GetWrapperPreserveColor();
}
virtual void PreserveWrapperInternal(
nsISupports* aScriptObjectHolder) override {
nsWrapperCache::PreserveWrapper(aScriptObjectHolder);
}
virtual JSObject* WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) override {
return HTMLCollection_Binding::Wrap(aCx, this, aGivenProto);
}
using nsBaseContentList::Item;
private:
virtual ~SimpleHTMLCollection() = default;
};
NS_IMPL_ISUPPORTS_INHERITED(SimpleHTMLCollection, nsSimpleContentList,
nsIHTMLCollection)
} // namespace dom
void IdentifierMapEntry::AddNameElement(nsINode* aNode, Element* aElement) {
if (!mNameContentList) {
mNameContentList = new dom::SimpleHTMLCollection(aNode);
}
mNameContentList->AppendElement(aElement);
}
void IdentifierMapEntry::RemoveNameElement(Element* aElement) {
if (mNameContentList) {
mNameContentList->RemoveElement(aElement);
}
}
bool IdentifierMapEntry::HasIdElementExposedAsHTMLDocumentProperty() const {
Element* idElement = GetIdElement();
return idElement &&
nsGenericHTMLElement::ShouldExposeIdAsHTMLDocumentProperty(idElement);
}
size_t IdentifierMapEntry::SizeOfExcludingThis(
MallocSizeOf aMallocSizeOf) const {
return mKey.mString.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
}
// Helper structs for the content->subdoc map
class SubDocMapEntry : public PLDHashEntryHdr {
public:
// Both of these are strong references
dom::Element* mKey; // must be first, to look like PLDHashEntryStub
dom::Document* mSubDocument;
};
class OnloadBlocker final : public nsIRequest {
public:
OnloadBlocker() = default;
NS_DECL_ISUPPORTS
NS_DECL_NSIREQUEST
private:
~OnloadBlocker() = default;
};
NS_IMPL_ISUPPORTS(OnloadBlocker, nsIRequest)
NS_IMETHODIMP
OnloadBlocker::GetName(nsACString& aResult) {
aResult.AssignLiteral("about:document-onload-blocker");
return NS_OK;
}
NS_IMETHODIMP
OnloadBlocker::IsPending(bool* _retval) {
*_retval = true;
return NS_OK;
}
NS_IMETHODIMP
OnloadBlocker::GetStatus(nsresult* status) {
*status = NS_OK;
return NS_OK;
}
NS_IMETHODIMP OnloadBlocker::SetCanceledReason(const nsACString& aReason) {
return SetCanceledReasonImpl(aReason);
}
NS_IMETHODIMP OnloadBlocker::GetCanceledReason(nsACString& aReason) {
return GetCanceledReasonImpl(aReason);
}
NS_IMETHODIMP OnloadBlocker::CancelWithReason(nsresult aStatus,
const nsACString& aReason) {
return CancelWithReasonImpl(aStatus, aReason);
}
NS_IMETHODIMP
OnloadBlocker::Cancel(nsresult status) { return NS_OK; }
NS_IMETHODIMP
OnloadBlocker::Suspend(void) { return NS_OK; }
NS_IMETHODIMP
OnloadBlocker::Resume(void) { return NS_OK; }
NS_IMETHODIMP
OnloadBlocker::GetLoadGroup(nsILoadGroup** aLoadGroup) {
*aLoadGroup = nullptr;
return NS_OK;
}
NS_IMETHODIMP
OnloadBlocker::SetLoadGroup(nsILoadGroup* aLoadGroup) { return NS_OK; }
NS_IMETHODIMP
OnloadBlocker::GetLoadFlags(nsLoadFlags* aLoadFlags) {
*aLoadFlags = nsIRequest::LOAD_NORMAL;
return NS_OK;
}
NS_IMETHODIMP
OnloadBlocker::GetTRRMode(nsIRequest::TRRMode* aTRRMode) {
return GetTRRModeImpl(aTRRMode);
}
NS_IMETHODIMP
OnloadBlocker::SetTRRMode(nsIRequest::TRRMode aTRRMode) {
return SetTRRModeImpl(aTRRMode);
}
NS_IMETHODIMP
OnloadBlocker::SetLoadFlags(nsLoadFlags aLoadFlags) { return NS_OK; }
// ==================================================================
namespace dom {
ExternalResourceMap::ExternalResourceMap() : mHaveShutDown(false) {}
Document* ExternalResourceMap::RequestResource(
nsIURI* aURI, nsIReferrerInfo* aReferrerInfo, nsINode* aRequestingNode,
Document* aDisplayDocument, ExternalResourceLoad** aPendingLoad) {
// If we ever start allowing non-same-origin loads here, we might need to do
// something interesting with aRequestingPrincipal even for the hashtable
// gets.
MOZ_ASSERT(aURI, "Must have a URI");
MOZ_ASSERT(aRequestingNode, "Must have a node");
MOZ_ASSERT(aReferrerInfo, "Must have a referrerInfo");
*aPendingLoad = nullptr;
if (mHaveShutDown) {
return nullptr;
}
// First, make sure we strip the ref from aURI.
nsCOMPtr<nsIURI> clone;
nsresult rv = NS_GetURIWithoutRef(aURI, getter_AddRefs(clone));
if (NS_FAILED(rv) || !clone) {
return nullptr;
}
ExternalResource* resource;
mMap.Get(clone, &resource);
if (resource) {
return resource->mDocument;
}
bool loadStartSucceeded =
mPendingLoads.WithEntryHandle(clone, [&](auto&& loadEntry) {
if (!loadEntry) {
loadEntry.Insert(MakeRefPtr<PendingLoad>(aDisplayDocument));
if (NS_FAILED(loadEntry.Data()->StartLoad(clone, aReferrerInfo,
aRequestingNode))) {
return false;
}
}
RefPtr<PendingLoad> load(loadEntry.Data());
load.forget(aPendingLoad);
return true;
});
if (!loadStartSucceeded) {
// Make sure we don't thrash things by trying this load again, since
// chances are it failed for good reasons (security check, etc).
// This must be done outside the WithEntryHandle functor, as it accesses
// mPendingLoads.
AddExternalResource(clone, nullptr, nullptr, aDisplayDocument);
}
return nullptr;
}
void ExternalResourceMap::EnumerateResources(SubDocEnumFunc aCallback) {
nsTArray<RefPtr<Document>> docs(mMap.Count());
for (const auto& entry : mMap.Values()) {
if (Document* doc = entry->mDocument) {
docs.AppendElement(doc);
}
}
for (auto& doc : docs) {
if (aCallback(*doc) == CallState::Stop) {
return;
}
}
}
void ExternalResourceMap::Traverse(
nsCycleCollectionTraversalCallback* aCallback) const {
// mPendingLoads will get cleared out as the requests complete, so
// no need to worry about those here.
for (const auto& entry : mMap) {
ExternalResourceMap::ExternalResource* resource = entry.GetWeak();
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mExternalResourceMap.mMap entry"
"->mDocument");
aCallback->NoteXPCOMChild(ToSupports(resource->mDocument));
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mExternalResourceMap.mMap entry"
"->mViewer");
aCallback->NoteXPCOMChild(resource->mViewer);
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(*aCallback,
"mExternalResourceMap.mMap entry"
"->mLoadGroup");
aCallback->NoteXPCOMChild(resource->mLoadGroup);
}
}
void ExternalResourceMap::HideViewers() {
for (const auto& entry : mMap) {
nsCOMPtr<nsIContentViewer> viewer = entry.GetData()->mViewer;
if (viewer) {
viewer->Hide();
}
}
}
void ExternalResourceMap::ShowViewers() {
for (const auto& entry : mMap) {
nsCOMPtr<nsIContentViewer> viewer = entry.GetData()->mViewer;
if (viewer) {
viewer->Show();
}
}
}
void TransferShowingState(Document* aFromDoc, Document* aToDoc) {
MOZ_ASSERT(aFromDoc && aToDoc, "transferring showing state from/to null doc");
if (aFromDoc->IsShowing()) {
aToDoc->OnPageShow(true, nullptr);
}
}
nsresult ExternalResourceMap::AddExternalResource(nsIURI* aURI,
nsIContentViewer* aViewer,
nsILoadGroup* aLoadGroup,
Document* aDisplayDocument) {
MOZ_ASSERT(aURI, "Unexpected call");
MOZ_ASSERT((aViewer && aLoadGroup) || (!aViewer && !aLoadGroup),
"Must have both or neither");
RefPtr<PendingLoad> load;
mPendingLoads.Remove(aURI, getter_AddRefs(load));
nsresult rv = NS_OK;
nsCOMPtr<Document> doc;
if (aViewer) {
doc = aViewer->GetDocument();
NS_ASSERTION(doc, "Must have a document");
doc->SetDisplayDocument(aDisplayDocument);
// Make sure that hiding our viewer will tear down its presentation.
aViewer->SetSticky(false);
rv = aViewer->Init(nullptr, nsIntRect(0, 0, 0, 0), nullptr);
if (NS_SUCCEEDED(rv)) {
rv = aViewer->Open(nullptr, nullptr);
}
if (NS_FAILED(rv)) {
doc = nullptr;
aViewer = nullptr;
aLoadGroup = nullptr;
}
}
ExternalResource* newResource =
mMap.InsertOrUpdate(aURI, MakeUnique<ExternalResource>()).get();
newResource->mDocument = doc;
newResource->mViewer = aViewer;
newResource->mLoadGroup = aLoadGroup;
if (doc) {
if (nsPresContext* pc = doc->GetPresContext()) {
pc->RecomputeBrowsingContextDependentData();
}
TransferShowingState(aDisplayDocument, doc);
}
const nsTArray<nsCOMPtr<nsIObserver>>& obs = load->Observers();
for (uint32_t i = 0; i < obs.Length(); ++i) {
obs[i]->Observe(ToSupports(doc), "external-resource-document-created",
nullptr);
}
return rv;
}
NS_IMPL_ISUPPORTS(ExternalResourceMap::PendingLoad, nsIStreamListener,
nsIRequestObserver)
NS_IMETHODIMP
ExternalResourceMap::PendingLoad::OnStartRequest(nsIRequest* aRequest) {
ExternalResourceMap& map = mDisplayDocument->ExternalResourceMap();
if (map.HaveShutDown()) {
return NS_BINDING_ABORTED;
}
nsCOMPtr<nsIContentViewer> viewer;
nsCOMPtr<nsILoadGroup> loadGroup;
nsresult rv =
SetupViewer(aRequest, getter_AddRefs(viewer), getter_AddRefs(loadGroup));
// Make sure to do this no matter what
nsresult rv2 =
map.AddExternalResource(mURI, viewer, loadGroup, mDisplayDocument);
if (NS_FAILED(rv)) {
return rv;
}
if (NS_FAILED(rv2)) {
mTargetListener = nullptr;
return rv2;
}
return mTargetListener->OnStartRequest(aRequest);
}
nsresult ExternalResourceMap::PendingLoad::SetupViewer(
nsIRequest* aRequest, nsIContentViewer** aViewer,
nsILoadGroup** aLoadGroup) {
MOZ_ASSERT(!mTargetListener, "Unexpected call to OnStartRequest");
*aViewer = nullptr;
*aLoadGroup = nullptr;
nsCOMPtr<nsIChannel> chan(do_QueryInterface(aRequest));
NS_ENSURE_TRUE(chan, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest));
if (httpChannel) {
bool requestSucceeded;
if (NS_FAILED(httpChannel->GetRequestSucceeded(&requestSucceeded)) ||
!requestSucceeded) {
// Bail out on this load, since it looks like we have an HTTP error page
return NS_BINDING_ABORTED;
}
}
nsAutoCString type;
chan->GetContentType(type);
nsCOMPtr<nsILoadGroup> loadGroup;
chan->GetLoadGroup(getter_AddRefs(loadGroup));
// Give this document its own loadgroup
nsCOMPtr<nsILoadGroup> newLoadGroup =
do_CreateInstance(NS_LOADGROUP_CONTRACTID);
NS_ENSURE_TRUE(newLoadGroup, NS_ERROR_OUT_OF_MEMORY);
newLoadGroup->SetLoadGroup(loadGroup);
nsCOMPtr<nsIInterfaceRequestor> callbacks;
loadGroup->GetNotificationCallbacks(getter_AddRefs(callbacks));
nsCOMPtr<nsIInterfaceRequestor> newCallbacks =
new LoadgroupCallbacks(callbacks);
newLoadGroup->SetNotificationCallbacks(newCallbacks);
// This is some serious hackery cribbed from docshell
nsCOMPtr<nsICategoryManager> catMan =
do_GetService(NS_CATEGORYMANAGER_CONTRACTID);
NS_ENSURE_TRUE(catMan, NS_ERROR_NOT_AVAILABLE);
nsCString contractId;
nsresult rv =
catMan->GetCategoryEntry("Gecko-Content-Viewers", type, contractId);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDocumentLoaderFactory> docLoaderFactory =
do_GetService(contractId.get());
NS_ENSURE_TRUE(docLoaderFactory, NS_ERROR_NOT_AVAILABLE);
nsCOMPtr<nsIContentViewer> viewer;
nsCOMPtr<nsIStreamListener> listener;
rv = docLoaderFactory->CreateInstance(
"external-resource", chan, newLoadGroup, type, nullptr, nullptr,
getter_AddRefs(listener), getter_AddRefs(viewer));
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED);
nsCOMPtr<nsIParser> parser = do_QueryInterface(listener);
if (!parser) {
/// We don't want to deal with the various fake documents yet
return NS_ERROR_NOT_IMPLEMENTED;
}
// We can't handle HTML and other weird things here yet.
nsIContentSink* sink = parser->GetContentSink();
nsCOMPtr<nsIXMLContentSink> xmlSink = do_QueryInterface(sink);
if (!xmlSink) {
return NS_ERROR_NOT_IMPLEMENTED;
}
listener.swap(mTargetListener);
viewer.forget(aViewer);
newLoadGroup.forget(aLoadGroup);
return NS_OK;
}
NS_IMETHODIMP
ExternalResourceMap::PendingLoad::OnDataAvailable(nsIRequest* aRequest,
nsIInputStream* aStream,
uint64_t aOffset,
uint32_t aCount) {
// mTargetListener might be null if SetupViewer or AddExternalResource failed.
NS_ENSURE_TRUE(mTargetListener, NS_ERROR_FAILURE);
if (mDisplayDocument->ExternalResourceMap().HaveShutDown()) {
return NS_BINDING_ABORTED;
}
return mTargetListener->OnDataAvailable(aRequest, aStream, aOffset, aCount);
}
NS_IMETHODIMP
ExternalResourceMap::PendingLoad::OnStopRequest(nsIRequest* aRequest,
nsresult aStatus) {
// mTargetListener might be null if SetupViewer or AddExternalResource failed
if (mTargetListener) {
nsCOMPtr<nsIStreamListener> listener;
mTargetListener.swap(listener);
return listener->OnStopRequest(aRequest, aStatus);
}
return NS_OK;
}
nsresult ExternalResourceMap::PendingLoad::StartLoad(
nsIURI* aURI, nsIReferrerInfo* aReferrerInfo, nsINode* aRequestingNode) {
MOZ_ASSERT(aURI, "Must have a URI");
MOZ_ASSERT(aRequestingNode, "Must have a node");
MOZ_ASSERT(aReferrerInfo, "Must have a referrerInfo");
nsCOMPtr<nsILoadGroup> loadGroup =
aRequestingNode->OwnerDoc()->GetDocumentLoadGroup();
nsresult rv = NS_OK;
nsCOMPtr<nsIChannel> channel;
rv = NS_NewChannel(getter_AddRefs(channel), aURI, aRequestingNode,
nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_INHERITS_SEC_CONTEXT,
nsIContentPolicy::TYPE_OTHER,
nullptr, // aPerformanceStorage
loadGroup);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel));
if (httpChannel) {
rv = httpChannel->SetReferrerInfo(aReferrerInfo);
Unused << NS_WARN_IF(NS_FAILED(rv));
}
mURI = aURI;
return channel->AsyncOpen(this);
}
NS_IMPL_ISUPPORTS(ExternalResourceMap::LoadgroupCallbacks,
nsIInterfaceRequestor)
#define IMPL_SHIM(_i) \
NS_IMPL_ISUPPORTS(ExternalResourceMap::LoadgroupCallbacks::_i##Shim, _i)
IMPL_SHIM(nsILoadContext)
IMPL_SHIM(nsIProgressEventSink)
IMPL_SHIM(nsIChannelEventSink)
#undef IMPL_SHIM
#define IID_IS(_i) aIID.Equals(NS_GET_IID(_i))
#define TRY_SHIM(_i) \
PR_BEGIN_MACRO \
if (IID_IS(_i)) { \
nsCOMPtr<_i> real = do_GetInterface(mCallbacks); \
if (!real) { \
return NS_NOINTERFACE; \
} \
nsCOMPtr<_i> shim = new _i##Shim(this, real); \
shim.forget(aSink); \
return NS_OK; \
} \
PR_END_MACRO
NS_IMETHODIMP
ExternalResourceMap::LoadgroupCallbacks::GetInterface(const nsIID& aIID,
void** aSink) {
if (mCallbacks && (IID_IS(nsIPrompt) || IID_IS(nsIAuthPrompt) ||
IID_IS(nsIAuthPrompt2) || IID_IS(nsIBrowserChild))) {
return mCallbacks->GetInterface(aIID, aSink);
}
*aSink = nullptr;
TRY_SHIM(nsILoadContext);
TRY_SHIM(nsIProgressEventSink);
TRY_SHIM(nsIChannelEventSink);
return NS_NOINTERFACE;
}
#undef TRY_SHIM
#undef IID_IS
ExternalResourceMap::ExternalResource::~ExternalResource() {
if (mViewer) {
mViewer->Close(nullptr);
mViewer->Destroy();
}
}
// ==================================================================
// =
// ==================================================================
// If we ever have an nsIDocumentObserver notification for stylesheet title
// changes we should update the list from that instead of overriding
// EnsureFresh.
class DOMStyleSheetSetList final : public DOMStringList {
public:
explicit DOMStyleSheetSetList(Document* aDocument);
void Disconnect() { mDocument = nullptr; }
virtual void EnsureFresh() override;
protected:
Document* mDocument; // Our document; weak ref. It'll let us know if it
// dies.
};
DOMStyleSheetSetList::DOMStyleSheetSetList(Document* aDocument)
: mDocument(aDocument) {
NS_ASSERTION(mDocument, "Must have document!");
}
void DOMStyleSheetSetList::EnsureFresh() {
MOZ_ASSERT(NS_IsMainThread());
mNames.Clear();
if (!mDocument) {
return; // Spec says "no exceptions", and we have no style sets if we have
// no document, for sure
}
size_t count = mDocument->SheetCount();
nsAutoString title;
for (size_t index = 0; index < count; index++) {
StyleSheet* sheet = mDocument->SheetAt(index);
NS_ASSERTION(sheet, "Null sheet in sheet list!");
sheet->GetTitle(title);
if (!title.IsEmpty() && !mNames.Contains(title) && !Add(title)) {
return;
}
}
}
// ==================================================================
Document::SelectorCache::SelectorCache(nsIEventTarget* aEventTarget)
: nsExpirationTracker<SelectorCacheKey, 4>(1000, "Document::SelectorCache",
aEventTarget) {}
Document::SelectorCache::~SelectorCache() { AgeAllGenerations(); }
void Document::SelectorCache::NotifyExpired(SelectorCacheKey* aSelector) {
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(aSelector);
// There is no guarantee that this method won't be re-entered when selector
// matching is ongoing because "memory-pressure" could be notified immediately
// when OOM happens according to the design of nsExpirationTracker.
// The perfect solution is to delete the |aSelector| and its
// RawServoSelectorList in mTable asynchronously.
// We remove these objects synchronously for now because NotifyExpired() will
// never be triggered by "memory-pressure" which is not implemented yet in
// the stage 2 of mozalloc_handle_oom().
// Once these objects are removed asynchronously, we should update the warning
// added in mozalloc_handle_oom() as well.
RemoveObject(aSelector);
mTable.Remove(aSelector->mKey);
delete aSelector;
}
Document::PendingFrameStaticClone::~PendingFrameStaticClone() = default;
// ==================================================================
// =
// ==================================================================
Document::InternalCommandDataHashtable*
Document::sInternalCommandDataHashtable = nullptr;
// static
void Document::Shutdown() {
if (sInternalCommandDataHashtable) {
sInternalCommandDataHashtable->Clear();
delete sInternalCommandDataHashtable;
sInternalCommandDataHashtable = nullptr;
}
}
Document::Document(const char* aContentType)
: nsINode(nullptr),
DocumentOrShadowRoot(this),
mCharacterSet(WINDOWS_1252_ENCODING),
mCharacterSetSource(0),
mParentDocument(nullptr),
mCachedRootElement(nullptr),
mNodeInfoManager(nullptr),
#ifdef DEBUG
mStyledLinksCleared(false),
#endif
mBlockAllMixedContent(false),
mBlockAllMixedContentPreloads(false),
mUpgradeInsecureRequests(false),
mUpgradeInsecurePreloads(false),
mDevToolsWatchingDOMMutations(false),
mBidiEnabled(false),
mMayNeedFontPrefsUpdate(true),
mMathMLEnabled(false),
mIsInitialDocumentInWindow(false),
mIgnoreDocGroupMismatches(false),
mLoadedAsData(false),
mAddedToMemoryReportingAsDataDocument(false),
mMayStartLayout(true),
mHaveFiredTitleChange(false),
mIsShowing(false),
mVisible(true),
mRemovedFromDocShell(false),
// mAllowDNSPrefetch starts true, so that we can always reliably && it
// with various values that might disable it. Since we never prefetch
// unless we get a window, and in that case the docshell value will get
// &&-ed in, this is safe.
mAllowDNSPrefetch(true),
mIsStaticDocument(false),
mCreatingStaticClone(false),
mHasPrintCallbacks(false),
mInUnlinkOrDeletion(false),
mHasHadScriptHandlingObject(false),
mIsBeingUsedAsImage(false),
mDocURISchemeIsChrome(false),
mInChromeDocShell(false),
mIsDevToolsDocument(false),
mIsSyntheticDocument(false),
mHasLinksToUpdateRunnable(false),
mFlushingPendingLinkUpdates(false),
mMayHaveDOMMutationObservers(false),
mMayHaveAnimationObservers(false),
mHasCSP(false),
mHasUnsafeEvalCSP(false),
mHasUnsafeInlineCSP(false),
mHasCSPDeliveredThroughHeader(false),
mBFCacheDisallowed(false),
mHasHadDefaultView(false),
mStyleSheetChangeEventsEnabled(false),
mShadowRootAttachedEventEnabled(false),
mIsSrcdocDocument(false),
mHasDisplayDocument(false),
mFontFaceSetDirty(true),
mDidFireDOMContentLoaded(true),
mFrameRequestCallbacksScheduled(false),
mIsTopLevelContentDocument(false),
mIsContentDocument(false),
mDidCallBeginLoad(false),
mEncodingMenuDisabled(false),
mLinksEnabled(true),
mIsSVGGlyphsDocument(false),
mInDestructor(false),
mIsGoingAway(false),
mInXBLUpdate(false),
mNeedsReleaseAfterStackRefCntRelease(false),
mStyleSetFilled(false),
mQuirkSheetAdded(false),
mContentEditableSheetAdded(false),
mDesignModeSheetAdded(false),
mSSApplicableStateNotificationPending(false),
mMayHaveTitleElement(false),
mDOMLoadingSet(false),
mDOMInteractiveSet(false),
mDOMCompleteSet(false),
mAutoFocusFired(false),
mScrolledToRefAlready(false),
mChangeScrollPosWhenScrollingToRef(false),
mDelayFrameLoaderInitialization(false),
mSynchronousDOMContentLoaded(false),
mMaybeServiceWorkerControlled(false),
mAllowZoom(false),
mValidScaleFloat(false),
mValidMinScale(false),
mValidMaxScale(false),
mWidthStrEmpty(false),
mParserAborted(false),
mReportedDocumentUseCounters(false),
mHasReportedShadowDOMUsage(false),
mHasDelayedRefreshEvent(false),
mLoadEventFiring(false),
mSkipLoadEventAfterClose(false),
mDisableCookieAccess(false),
mDisableDocWrite(false),
mTooDeepWriteRecursion(false),
mPendingMaybeEditingStateChanged(false),
mHasBeenEditable(false),
mHasWarnedAboutZoom(false),
mIsRunningExecCommand(false),
mSetCompleteAfterDOMContentLoaded(false),
mDidHitCompleteSheetCache(false),
mPendingFullscreenRequests(0),
mXMLDeclarationBits(0),
mOnloadBlockCount(0),
mWriteLevel(0),
mContentEditableCount(0),
mEditingState(EditingState::eOff),
mCompatMode(eCompatibility_FullStandards),
mReadyState(ReadyState::READYSTATE_UNINITIALIZED),
mAncestorIsLoading(false),
mVisibilityState(dom::VisibilityState::Hidden),
mType(eUnknown),
mDefaultElementType(0),
mAllowXULXBL(eTriUnset),
mSkipDTDSecurityChecks(false),
mBidiOptions(IBMBIDI_DEFAULT_BIDI_OPTIONS),
mSandboxFlags(0),
mPartID(0),
mMarkedCCGeneration(0),
mPresShell(nullptr),
mSubtreeModifiedDepth(0),
mPreloadPictureDepth(0),
mEventsSuppressed(0),
mIgnoreDestructiveWritesCounter(0),
mStaticCloneCount(0),
mWindow(nullptr),
mBFCacheEntry(nullptr),
mInSyncOperationCount(0),
mBlockDOMContentLoaded(0),
mUseCountersInitialized(false),
mShouldReportUseCounters(false),
mShouldSendPageUseCounters(false),
mUserHasInteracted(false),
mHasUserInteractionTimerScheduled(false),
mStackRefCnt(0),
mUpdateNestLevel(0),
mHttpsOnlyStatus(nsILoadInfo::HTTPS_ONLY_UNINITIALIZED),
mViewportType(Unknown),
mViewportFit(ViewportFitType::Auto),
mSubDocuments(nullptr),
mHeaderData(nullptr),
mServoRestyleRootDirtyBits(0),
mThrowOnDynamicMarkupInsertionCounter(0),
mIgnoreOpensDuringUnloadCounter(0),
mSavedResolution(1.0f),
mSavedResolutionBeforeMVM(1.0f),
mGeneration(0),
mCachedTabSizeGeneration(0),
mNextFormNumber(0),
mNextControlNumber(0),
mPreloadService(this),
mShouldNotifyFetchSuccess(false),
mShouldNotifyFormOrPasswordRemoved(false) {
MOZ_LOG(gDocumentLeakPRLog, LogLevel::Debug, ("DOCUMENT %p created", this));
SetIsInDocument();
SetIsConnected(true);
// Create these unconditionally, they will be used to warn about the `zoom`
// property, even if use counters are disabled.
mStyleUseCounters = Servo_UseCounters_Create().Consume();
SetContentType(nsDependentCString(aContentType));
// Start out mLastStyleSheetSet as null, per spec
SetDOMStringToNull(mLastStyleSheetSet);
// void state used to differentiate an empty source from an unselected source
mPreloadPictureFoundSource.SetIsVoid(true);
RecomputeLanguageFromCharset();
mPreloadReferrerInfo = new dom::ReferrerInfo(nullptr);
mReferrerInfo = new dom::ReferrerInfo(nullptr);
}
#ifndef ANDROID
// unused by GeckoView
static bool IsAboutErrorPage(nsGlobalWindowInner* aWin, const char* aSpec) {
if (NS_WARN_IF(!aWin)) {
return false;
}
nsIURI* uri = aWin->GetDocumentURI();
if (NS_WARN_IF(!uri)) {
return false;
}
// getSpec is an expensive operation, hence we first check the scheme
// to see if the caller is actually an about: page.
if (!uri->SchemeIs("about")) {
return false;
}
nsAutoCString aboutSpec;
nsresult rv = NS_GetAboutModuleName(uri, aboutSpec);
NS_ENSURE_SUCCESS(rv, false);
return aboutSpec.EqualsASCII(aSpec);
}
#endif
bool Document::CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject) {
nsGlobalWindowInner* win = xpc::WindowOrNull(aObject);
#ifdef ANDROID
// GeckoView uses data URLs for error pages, so for now just check for any
// error page
return win && win->GetDocument() && win->GetDocument()->IsErrorPage();
#else
return win && IsAboutErrorPage(win, "neterror");
#endif
}
bool Document::CallerIsTrustedAboutHttpsOnlyError(JSContext* aCx,
JSObject* aObject) {
nsGlobalWindowInner* win = xpc::WindowOrNull(aObject);
#ifdef ANDROID
// GeckoView uses data URLs for error pages, so for now just check for any
// error page
return win && win->GetDocument() && win->GetDocument()->IsErrorPage();
#else
return win && IsAboutErrorPage(win, "httpsonlyerror");
#endif
}
already_AddRefed<mozilla::dom::Promise> Document::AddCertException(
bool aIsTemporary, ErrorResult& aError) {
RefPtr<Promise> promise = Promise::Create(GetScopeObject(), aError,
Promise::ePropagateUserInteraction);
if (aError.Failed()) {
return nullptr;
}
nsresult rv = NS_OK;
if (NS_WARN_IF(!mFailedChannel)) {
promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR);
return promise.forget();
}
nsCOMPtr<nsIURI> failedChannelURI;
NS_GetFinalChannelURI(mFailedChannel, getter_AddRefs(failedChannelURI));
if (!failedChannelURI) {
promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR);
return promise.forget();
}
nsCOMPtr<nsIURI> innerURI = NS_GetInnermostURI(failedChannelURI);
if (!innerURI) {
promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR);
return promise.forget();
}
nsAutoCString host;
innerURI->GetAsciiHost(host);
int32_t port;
innerURI->GetPort(&port);
nsCOMPtr<nsITransportSecurityInfo> tsi;
rv = mFailedChannel->GetSecurityInfo(getter_AddRefs(tsi));
if (NS_WARN_IF(NS_FAILED(rv))) {
promise->MaybeReject(rv);
return promise.forget();
}
if (NS_WARN_IF(!tsi)) {
promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR);
return promise.forget();
}
nsCOMPtr<nsIX509Cert> cert;
rv = tsi->GetServerCert(getter_AddRefs(cert));
if (NS_WARN_IF(NS_FAILED(rv))) {
promise->MaybeReject(rv);
return promise.forget();
}
if (NS_WARN_IF(!cert)) {
promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR);
return promise.forget();
}
if (XRE_IsContentProcess()) {
ContentChild* cc = ContentChild::GetSingleton();
MOZ_ASSERT(cc);
OriginAttributes const& attrs = NodePrincipal()->OriginAttributesRef();
cc->SendAddCertException(cert, host, port, attrs, aIsTemporary)
->Then(GetCurrentSerialEventTarget(), __func__,
[promise](const mozilla::MozPromise<
nsresult, mozilla::ipc::ResponseRejectReason,
true>::ResolveOrRejectValue& aValue) {
if (aValue.IsResolve()) {
promise->MaybeResolve(aValue.ResolveValue());
} else {
promise->MaybeRejectWithUndefined();
}