Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / dom / base / nsContentUtils.h
blob3631be216d49c66bfbc3ed56e7a44fde20f65267
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* A namespace class for static content utilities. */
9 #ifndef nsContentUtils_h___
10 #define nsContentUtils_h___
12 #if defined(XP_WIN)
13 # include <float.h>
14 #endif
16 #if defined(SOLARIS)
17 # include <ieeefp.h>
18 #endif
20 #include <cstddef>
21 #include <cstdint>
22 #include <functional>
23 #include <tuple>
24 #include <utility>
25 #include "ErrorList.h"
26 #include "Units.h"
27 #include "js/Id.h"
28 #include "js/RegExpFlags.h"
29 #include "js/RootingAPI.h"
30 #include "mozilla/AlreadyAddRefed.h"
31 #include "mozilla/Assertions.h"
32 #include "mozilla/Attributes.h"
33 #include "mozilla/BasicEvents.h"
34 #include "mozilla/CORSMode.h"
35 #include "mozilla/CallState.h"
36 #include "mozilla/Maybe.h"
37 #include "mozilla/RefPtr.h"
38 #include "mozilla/TimeStamp.h"
39 #include "mozilla/UniquePtr.h"
40 #include "mozilla/dom/BindingDeclarations.h"
41 #include "mozilla/dom/FromParser.h"
42 #include "mozilla/dom/FetchPriority.h"
43 #include "mozilla/fallible.h"
44 #include "mozilla/gfx/Point.h"
45 #include "nsCOMPtr.h"
46 #include "nsIContentPolicy.h"
47 #include "nsINode.h"
48 #include "nsIScriptError.h"
49 #include "nsIThread.h"
50 #include "nsLiteralString.h"
51 #include "nsMargin.h"
52 #include "nsPIDOMWindow.h"
53 #include "nsRFPService.h"
54 #include "nsStringFwd.h"
55 #include "nsTArray.h"
56 #include "nsTLiteralString.h"
57 #include "prtime.h"
59 #if defined(XP_WIN)
60 // Undefine LoadImage to prevent naming conflict with Windows.
61 # undef LoadImage
62 #endif
64 class JSObject;
65 class imgICache;
66 class imgIContainer;
67 class imgINotificationObserver;
68 class imgIRequest;
69 class imgLoader;
70 class imgRequestProxy;
71 class nsAtom;
72 class nsAttrValue;
73 class nsAutoScriptBlockerSuppressNodeRemoved;
74 class nsContentList;
75 class nsCycleCollectionTraversalCallback;
76 class nsDocShell;
77 class nsGlobalWindowInner;
78 class nsHtml5StringParser;
79 class nsIArray;
80 class nsIBidiKeyboard;
81 class nsIChannel;
82 class nsIConsoleService;
83 class nsIContent;
84 class nsIDocShell;
85 class nsIDocShellTreeItem;
86 class nsIDocumentLoaderFactory;
87 class nsIDragSession;
88 class nsIFile;
89 class nsIFragmentContentSink;
90 class nsIFrame;
91 class nsIHttpChannel;
92 class nsIIOService;
93 class nsIImageLoadingContent;
94 class nsIInterfaceRequestor;
95 class nsILoadGroup;
96 class nsILoadInfo;
97 class nsIObserver;
98 class nsIPrincipal;
99 class nsIReferrerInfo;
100 class nsIRequest;
101 class nsIRunnable;
102 class nsIScreen;
103 class nsIScriptContext;
104 class nsIScriptSecurityManager;
105 class nsISerialEventTarget;
106 class nsIStringBundle;
107 class nsIStringBundleService;
108 class nsISupports;
109 class nsITransferable;
110 class nsIURI;
111 class nsIWidget;
112 class nsIWritableVariant;
113 class nsIXPConnect;
114 class nsNodeInfoManager;
115 class nsParser;
116 class nsPIWindowRoot;
117 class nsPresContext;
118 class nsStringBuffer;
119 class nsTextFragment;
120 class nsView;
121 class nsWrapperCache;
123 struct JSContext;
124 struct nsPoint;
126 namespace IPC {
127 class Message;
128 class MessageReader;
129 class MessageWriter;
130 } // namespace IPC
132 namespace JS {
133 class Value;
134 class PropertyDescriptor;
135 } // namespace JS
137 namespace mozilla {
138 class Dispatcher;
139 class EditorBase;
140 class ErrorResult;
141 class EventListenerManager;
142 class HTMLEditor;
143 class LazyLogModule;
144 class LogModule;
145 class PresShell;
146 class TextEditor;
147 class WidgetDragEvent;
148 class WidgetKeyboardEvent;
150 struct InputEventOptions;
152 template <typename ParentType, typename RefType>
153 class RangeBoundaryBase;
155 template <typename T>
156 class NotNull;
157 template <class T>
158 class StaticRefPtr;
160 namespace dom {
161 class IPCImage;
162 struct AutocompleteInfo;
163 class BrowserChild;
164 class BrowserParent;
165 class BrowsingContext;
166 class BrowsingContextGroup;
167 class ContentChild;
168 class ContentFrameMessageManager;
169 class ContentParent;
170 struct CustomElementDefinition;
171 class CustomElementFormValue;
172 class CustomElementRegistry;
173 class DataTransfer;
174 class Document;
175 class DocumentFragment;
176 class DOMArena;
177 class Element;
178 class Event;
179 class EventTarget;
180 class FragmentOrElement;
181 class HTMLElement;
182 class HTMLInputElement;
183 class IPCTransferable;
184 class IPCTransferableData;
185 class IPCTransferableDataImageContainer;
186 class IPCTransferableDataItem;
187 struct LifecycleCallbackArgs;
188 class MessageBroadcaster;
189 class NodeInfo;
190 class OwningFileOrUSVStringOrFormData;
191 class Selection;
192 enum class ShadowRootMode : uint8_t;
193 struct StructuredSerializeOptions;
194 class WorkerPrivate;
195 enum class ElementCallbackType;
196 enum class ReferrerPolicy : uint8_t;
197 } // namespace dom
199 namespace ipc {
200 class BigBuffer;
201 class IProtocol;
202 } // namespace ipc
204 namespace gfx {
205 class DataSourceSurface;
206 enum class SurfaceFormat : int8_t;
207 } // namespace gfx
209 class WindowRenderer;
211 } // namespace mozilla
213 extern const char kLoadAsData[];
215 // Stolen from nsReadableUtils, but that's OK, since we can declare the same
216 // name multiple times.
217 const nsString& EmptyString();
218 const nsCString& EmptyCString();
220 enum EventNameType {
221 EventNameType_None = 0x0000,
222 EventNameType_HTML = 0x0001,
223 EventNameType_XUL = 0x0002,
224 EventNameType_SVGGraphic = 0x0004, // svg graphic elements
225 EventNameType_SVGSVG = 0x0008, // the svg element
226 EventNameType_SMIL = 0x0010, // smil elements
227 EventNameType_HTMLBodyOrFramesetOnly = 0x0020,
229 EventNameType_HTMLXUL = 0x0003,
230 EventNameType_All = 0xFFFF
233 enum class TreeKind : uint8_t { DOM, Flat };
235 struct EventNameMapping {
236 // This holds pointers to nsGkAtoms members, and is therefore safe as a
237 // non-owning reference.
238 nsAtom* MOZ_NON_OWNING_REF mAtom;
239 int32_t mType;
240 mozilla::EventMessage mMessage;
241 mozilla::EventClassID mEventClassID;
244 namespace mozilla {
245 enum class PreventDefaultResult : uint8_t { No, ByContent, ByChrome };
247 namespace dom {
248 enum JSONBehavior { UndefinedIsNullStringLiteral, UndefinedIsVoidString };
250 } // namespace mozilla
252 class nsContentUtils {
253 friend class nsAutoScriptBlockerSuppressNodeRemoved;
254 using Element = mozilla::dom::Element;
255 using Document = mozilla::dom::Document;
256 using Cancelable = mozilla::Cancelable;
257 using CanBubble = mozilla::CanBubble;
258 using Composed = mozilla::Composed;
259 using ChromeOnlyDispatch = mozilla::ChromeOnlyDispatch;
260 using EventMessage = mozilla::EventMessage;
261 using TimeDuration = mozilla::TimeDuration;
262 using Trusted = mozilla::Trusted;
263 using JSONBehavior = mozilla::dom::JSONBehavior;
264 using RFPTarget = mozilla::RFPTarget;
266 public:
267 static nsresult Init();
269 static bool IsCallerChrome();
270 static bool ThreadsafeIsCallerChrome();
271 static bool IsCallerUAWidget();
272 static bool IsFuzzingEnabled()
273 #ifndef FUZZING
275 return false;
277 #else
279 #endif
280 static bool IsErrorPage(nsIURI* aURI);
282 static bool IsCallerChromeOrFuzzingEnabled(JSContext* aCx, JSObject*) {
283 return ThreadsafeIsSystemCaller(aCx) || IsFuzzingEnabled();
286 static bool IsCallerChromeOrElementTransformGettersEnabled(JSContext* aCx,
287 JSObject*);
289 // The APIs for checking whether the caller is system (in the sense of system
290 // principal) should only be used when the JSContext is known to accurately
291 // represent the caller. In practice, that means you should only use them in
292 // two situations at the moment:
294 // 1) Functions used in WebIDL Func annotations.
295 // 2) Bindings code or other code called directly from the JS engine.
297 // Use pretty much anywhere else is almost certainly wrong and should be
298 // replaced with [NeedsCallerType] annotations in bindings.
300 // Check whether the caller is system if you know you're on the main thread.
301 static bool IsSystemCaller(JSContext* aCx);
303 // Check whether the caller is system if you might be on a worker or worklet
304 // thread.
305 static bool ThreadsafeIsSystemCaller(JSContext* aCx);
307 // In the traditional Gecko architecture, both C++ code and untrusted JS code
308 // needed to rely on the same XPCOM method/getter/setter to get work done.
309 // This required lots of security checks in the various exposed methods, which
310 // in turn created difficulty in determining whether the caller was script
311 // (whose access needed to be checked) and internal C++ platform code (whose
312 // access did not need to be checked). To address this problem, Gecko had a
313 // convention whereby the absence of script on the stack was interpretted as
314 // "System Caller" and always granted unfettered access.
316 // Unfortunately, this created a bunch of footguns. For example, when the
317 // implementation of a DOM method wanted to perform a privileged
318 // sub-operation, it needed to "hide" the presence of script on the stack in
319 // order for that sub-operation to be allowed. Additionally, if script could
320 // trigger an API entry point to be invoked in some asynchronous way without
321 // script on the stack, it could potentially perform privilege escalation.
323 // In the modern world, untrusted script should interact with the platform
324 // exclusively over WebIDL APIs, and platform code has a lot more flexibility
325 // in deciding whether or not to use XPCOM. This gives us the flexibility to
326 // do something better.
328 // Going forward, APIs should be designed such that any security checks that
329 // ask the question "is my caller allowed to do this?" should live in WebIDL
330 // API entry points, with a separate method provided for internal callers
331 // that just want to get the job done.
333 // To enforce this and catch bugs, nsContentUtils::SubjectPrincipal will crash
334 // if it is invoked without script on the stack. To land that transition, it
335 // was necessary to go through and whitelist a bunch of callers that were
336 // depending on the old behavior. Those callers should be fixed up, and these
337 // methods should not be used by new code without review from bholley or bz.
338 static bool LegacyIsCallerNativeCode() { return !GetCurrentJSContext(); }
339 static bool LegacyIsCallerChromeOrNativeCode() {
340 return LegacyIsCallerNativeCode() || IsCallerChrome();
342 static nsIPrincipal* SubjectPrincipalOrSystemIfNativeCaller() {
343 if (!GetCurrentJSContext()) {
344 return GetSystemPrincipal();
346 return SubjectPrincipal();
349 static bool LookupBindingMember(
350 JSContext* aCx, nsIContent* aContent, JS::Handle<jsid> aId,
351 JS::MutableHandle<JS::PropertyDescriptor> aDesc);
353 // Check whether we should avoid leaking distinguishing information to JS/CSS.
354 // This function can be called both in the main thread and worker threads.
355 static bool ShouldResistFingerprinting(bool aIsPrivateMode,
356 RFPTarget aTarget);
357 static bool ShouldResistFingerprinting(nsIGlobalObject* aGlobalObject,
358 RFPTarget aTarget);
359 // Similar to the function above, but always allows CallerType::System
360 // callers.
361 static bool ShouldResistFingerprinting(mozilla::dom::CallerType aCallerType,
362 nsIGlobalObject* aGlobalObject,
363 RFPTarget aTarget);
364 static bool ShouldResistFingerprinting(nsIDocShell* aDocShell,
365 RFPTarget aTarget);
366 // These functions are the new, nuanced functions
367 static bool ShouldResistFingerprinting(nsIChannel* aChannel,
368 RFPTarget aTarget);
369 // These functions are labeled as dangerous because they will do the wrong
370 // thing in _most_ cases. They should only be used if you don't have a fully
371 // constructed LoadInfo or Document.
372 // A constant string used as justification is required when calling them,
373 // it should explain why a Document, Channel, LoadInfo, or CookieJarSettings
374 // does not exist in this context.
375 // (see below for more on justification strings.)
376 static bool ShouldResistFingerprinting_dangerous(
377 nsIURI* aURI, const mozilla::OriginAttributes& aOriginAttributes,
378 const char* aJustification, RFPTarget aTarget);
379 static bool ShouldResistFingerprinting_dangerous(nsIPrincipal* aPrincipal,
380 const char* aJustification,
381 RFPTarget aTarget);
384 * Implement a RFP function that only checks the pref, and does not take
385 * into account any additional context such as PBM mode or Web Extensions.
387 * It requires an explanation for why the coarse check is being used instead
388 * of the nuanced check. While there is a gradual cut over of
389 * ShouldResistFingerprinting calls to a nuanced API, some features still
390 * require a legacy function. (Additionally, we sometimes use the coarse
391 * check first, to avoid running additional code to support a nuanced check.)
393 static bool ShouldResistFingerprinting(const char* aJustification,
394 RFPTarget aTarget);
396 // A helper function to calculate the rounded window size for fingerprinting
397 // resistance. The rounded size is based on the chrome UI size and available
398 // screen size. If the inputWidth/Height is greater than the available content
399 // size, this will report the available content size. Otherwise, it will
400 // round the size to the nearest upper 200x100.
401 static void CalcRoundedWindowSizeForResistingFingerprinting(
402 int32_t aChromeWidth, int32_t aChromeHeight, int32_t aScreenWidth,
403 int32_t aScreenHeight, int32_t aInputWidth, int32_t aInputHeight,
404 bool aSetOuterWidth, bool aSetOuterHeight, int32_t* aOutputWidth,
405 int32_t* aOutputHeight);
408 * Returns the parent node of aChild crossing document boundaries, but skips
409 * any cross-process parent frames and continues with the nearest in-process
410 * frame in the hierarchy.
412 * Uses the parent node in the composed document.
414 static nsINode* GetNearestInProcessCrossDocParentNode(nsINode* aChild);
417 * Similar to nsINode::IsInclusiveDescendantOf, except will treat an
418 * HTMLTemplateElement or ShadowRoot as an ancestor of things in the
419 * corresponding DocumentFragment. See the concept of "host-including
420 * inclusive ancestor" in the DOM specification.
422 static bool ContentIsHostIncludingDescendantOf(
423 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
426 * Similar to nsINode::IsInclusiveDescendantOf except it crosses document
427 * boundaries, this function uses ancestor/descendant relations in the
428 * composed document (see shadow DOM spec).
430 static bool ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant,
431 nsINode* aPossibleAncestor);
434 * As with ContentIsCrossDocDescendantOf but crosses shadow boundaries but not
435 * cross document boundaries.
437 * @see nsINode::GetFlattenedTreeParentNode()
439 static bool ContentIsFlattenedTreeDescendantOf(
440 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
443 * Same as `ContentIsFlattenedTreeDescendantOf`, but from the flattened tree
444 * point of view of the style system
446 * @see nsINode::GetFlattenedTreeParentNodeForStyle()
448 static bool ContentIsFlattenedTreeDescendantOfForStyle(
449 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
452 * Retarget an object A against an object B
453 * @see https://dom.spec.whatwg.org/#retarget
455 static nsINode* Retarget(nsINode* aTargetA, nsINode* aTargetB);
458 * @see https://wicg.github.io/element-timing/#get-an-element
460 static Element* GetAnElementForTiming(Element* aTarget,
461 const Document* aDocument,
462 nsIGlobalObject* aGlobal);
465 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
467 * This method fills the |aArray| with all ancestor nodes of |aNode|
468 * including |aNode| at the zero index.
471 static nsresult GetInclusiveAncestors(nsINode* aNode,
472 nsTArray<nsINode*>& aArray);
475 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
477 * This method fills |aAncestorNodes| with all ancestor nodes of |aNode|
478 * including |aNode| (QI'd to nsIContent) at the zero index.
479 * For each ancestor, there is a corresponding element in |aAncestorOffsets|
480 * which is the ComputeIndexOf the child in relation to its parent.
482 * This method just sucks.
484 static nsresult GetInclusiveAncestorsAndOffsets(
485 nsINode* aNode, uint32_t aOffset, nsTArray<nsIContent*>* aAncestorNodes,
486 nsTArray<mozilla::Maybe<uint32_t>>* aAncestorOffsets);
489 * Returns the closest common inclusive ancestor
490 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) , if any,
491 * for two nodes.
493 * Returns null if the nodes are disconnected.
495 static nsINode* GetClosestCommonInclusiveAncestor(nsINode* aNode1,
496 nsINode* aNode2) {
497 if (aNode1 == aNode2) {
498 return aNode1;
501 return GetCommonAncestorHelper(aNode1, aNode2);
504 static nsINode* GetClosestCommonShadowIncludingInclusiveAncestor(
505 nsINode* aNode1, nsINode* aNode2);
508 * Returns the common flattened tree ancestor, if any, for two given content
509 * nodes.
511 static nsIContent* GetCommonFlattenedTreeAncestor(nsIContent* aContent1,
512 nsIContent* aContent2) {
513 if (aContent1 == aContent2) {
514 return aContent1;
517 return GetCommonFlattenedTreeAncestorHelper(aContent1, aContent2);
521 * Returns the common flattened tree ancestor from the point of view of
522 * the selection system, if any, for two given content nodes.
524 static nsIContent* GetCommonFlattenedTreeAncestorForSelection(
525 nsIContent* aContent1, nsIContent* aContent2);
528 * Returns the common flattened tree ancestor from the point of view of the
529 * style system, if any, for two given content nodes.
531 static Element* GetCommonFlattenedTreeAncestorForStyle(Element* aElement1,
532 Element* aElement2);
535 * Returns the common BrowserParent ancestor, if any, for two given
536 * BrowserParent.
538 static mozilla::dom::BrowserParent* GetCommonBrowserParentAncestor(
539 mozilla::dom::BrowserParent* aBrowserParent1,
540 mozilla::dom::BrowserParent* aBrowserParent2);
542 // https://html.spec.whatwg.org/#target-element
543 // https://html.spec.whatwg.org/#find-a-potential-indicated-element
544 static Element* GetTargetElement(Document* aDocument,
545 const nsAString& aAnchorName);
547 * Returns true if aNode1 is before aNode2 in the same connected
548 * tree.
549 * aNode1Index and aNode2Index are in/out arguments. If non-null, and value is
550 * Some, that value is used instead of calling slow ComputeIndexOf on the
551 * parent node. If value is Nothing, the value will be set to the return value
552 * of ComputeIndexOf.
554 static bool PositionIsBefore(nsINode* aNode1, nsINode* aNode2,
555 mozilla::Maybe<uint32_t>* aNode1Index = nullptr,
556 mozilla::Maybe<uint32_t>* aNode2Index = nullptr);
559 * Cache implementation for ComparePoints().
561 * This cache keeps the last cache_size child/index combinations
562 * in a stack-allocated array for fast lookup.
563 * If the cache is full, the entries are overridden,
564 * starting from the oldest entry.
566 * Note: This cache does not observe invalidation. As soon as script has
567 * run, this cache must not be used anymore.
568 * Also, this cache uses raw pointers. Beware!
570 template <size_t cache_size>
571 struct ResizableNodeIndexCache {
573 * Looks up or computes two indices in one loop.
575 void ComputeIndicesOf(const nsINode* aParent, const nsINode* aChild1,
576 const nsINode* aChild2,
577 mozilla::Maybe<uint32_t>& aChild1Index,
578 mozilla::Maybe<uint32_t>& aChild2Index) {
579 bool foundChild1 = false;
580 bool foundChild2 = false;
581 for (size_t cacheIndex = 0; cacheIndex < cache_size; ++cacheIndex) {
582 if (foundChild1 && foundChild2) {
583 return;
585 const nsINode* node = mNodes[cacheIndex];
586 if (!node) {
587 // reached the end of not-fully-populated cache.
588 break;
590 if (!foundChild1 && node == aChild1) {
591 aChild1Index = mIndices[cacheIndex];
592 foundChild1 = true;
593 continue;
595 if (!foundChild2 && node == aChild2) {
596 aChild2Index = mIndices[cacheIndex];
597 foundChild2 = true;
598 continue;
601 if (!foundChild1) {
602 aChild1Index = ComputeAndInsertIndexIntoCache(aParent, aChild1);
604 if (!foundChild2) {
605 aChild2Index = ComputeAndInsertIndexIntoCache(aParent, aChild2);
609 * Looks up or computes child index.
611 mozilla::Maybe<uint32_t> ComputeIndexOf(const nsINode* aParent,
612 const nsINode* aChild) {
613 for (size_t cacheIndex = 0; cacheIndex < cache_size; ++cacheIndex) {
614 const nsINode* node = mNodes[cacheIndex];
615 if (!node) {
616 break;
618 if (node == aChild) {
619 return mIndices[cacheIndex];
622 return ComputeAndInsertIndexIntoCache(aParent, aChild);
625 private:
627 * Computes the index of aChild in aParent, inserts the index into the
628 * cache, and returns the index.
630 mozilla::Maybe<uint32_t> ComputeAndInsertIndexIntoCache(
631 const nsINode* aParent, const nsINode* aChild) {
632 mozilla::Maybe<uint32_t> childIndex = aParent->ComputeIndexOf(aChild);
634 mNodes[mNext] = aChild;
635 mIndices[mNext] = childIndex;
637 ++mNext;
638 if (mNext == cache_size) {
639 // the last element of the cache has been reached.
640 // set mNext to 0 to start overriding the oldest cache entries.
641 mNext = 0;
643 return childIndex;
646 /// Node storage. The array is initialized to null
647 /// by the empty initializer list.
648 const nsINode* mNodes[cache_size]{};
650 mozilla::Maybe<uint32_t> mIndices[cache_size];
652 /// The next element in the cache that will be written to.
653 /// If the cache is full (mNext == cache_size),
654 /// the oldest entries in the cache will be overridden,
655 /// ie. mNext will be set to 0.
656 size_t mNext{0};
660 * Typedef with a reasonable default cache size.
661 * If Caches of different sizes are needed,
662 * ComparePoints would need to become templated.
664 using NodeIndexCache = ResizableNodeIndexCache<100>;
667 * Utility routine to compare two "points", where a point is a node/offset
668 * pair.
669 * Pass a cache object as aParent1Cache if you expect to repeatedly
670 * call this function with the same value as aParent1.
672 * @return -1 if point1 < point2,
673 * 1 if point1 > point2,
674 * 0 if point1 == point2.
675 * `Nothing` if the two nodes aren't in the same connected subtree.
677 static mozilla::Maybe<int32_t> ComparePoints(
678 const nsINode* aParent1, uint32_t aOffset1, const nsINode* aParent2,
679 uint32_t aOffset2, NodeIndexCache* aIndexCache = nullptr);
680 template <typename FPT, typename FRT, typename SPT, typename SRT>
681 static mozilla::Maybe<int32_t> ComparePoints(
682 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
683 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary);
686 * Utility routine to compare two "points", where a point is a
687 * node/offset pair
688 * Returns -1 if point1 < point2, 1, if point1 > point2,
689 * 0 if error or if point1 == point2.
690 * NOTE! If the two nodes aren't in the same connected subtree,
691 * the result is 1, and the optional aDisconnected parameter
692 * is set to true.
694 * Pass a cache object as aIndexCache if you expect to repeatedly
695 * call this function.
696 * ComparePointsCache will store the last X (currently 100) node/index
697 * combinations in a stack-allocated array and does a lookup there
698 * before going into the expensive ComputeIndexOf() method.
700 static int32_t ComparePoints_Deprecated(
701 const nsINode* aParent1, uint32_t aOffset1, const nsINode* aParent2,
702 uint32_t aOffset2, bool* aDisconnected = nullptr,
703 NodeIndexCache* aIndexCache = nullptr);
704 template <typename FPT, typename FRT, typename SPT, typename SRT>
705 static int32_t ComparePoints_Deprecated(
706 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
707 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary,
708 bool* aDisconnected = nullptr);
711 * DO NOT USE this method for comparing the points in new code. this method
712 * emulates same result as `ComparePoints` before bug 1741148.
713 * When the old `ComparePoints` was called with offset value over `INT32_MAX`
714 * or `-1` which is used as "not found" by some API, they were treated as-is
715 * without checking whether the negative value or valid value. Thus, this
716 * handles the negative offset cases in the special paths to keep the
717 * traditional behavior. If you want to use this in new code, it means that
718 * you **should** check the offset values and call `ComparePoints` instead.
720 static mozilla::Maybe<int32_t> ComparePoints_AllowNegativeOffsets(
721 const nsINode* aParent1, int64_t aOffset1, const nsINode* aParent2,
722 int64_t aOffset2) {
723 if (MOZ_UNLIKELY(aOffset1 < 0 || aOffset2 < 0)) {
724 // If in same container, just the offset is compared.
725 if (aParent1 == aParent2) {
726 const int32_t compOffsets =
727 aOffset1 == aOffset2 ? 0 : (aOffset1 < aOffset2 ? -1 : 1);
728 return mozilla::Some(compOffsets);
730 // Otherwise, aOffset1 is referred only when aParent2 is a descendant of
731 // aParent1.
732 if (aOffset1 < 0 && aParent2->IsInclusiveDescendantOf(aParent1)) {
733 return mozilla::Some(-1);
735 // And also aOffset2 is referred only when aParent1 is a descendant of
736 // aParent2.
737 if (aOffset2 < 0 && aParent1->IsInclusiveDescendantOf(aParent2)) {
738 return mozilla::Some(1);
740 // Otherwise, aOffset1 nor aOffset2 is referred so that any value is fine
741 // if negative.
742 return ComparePoints(
743 aParent1, aOffset1 < 0 ? UINT32_MAX : static_cast<uint32_t>(aOffset1),
744 aParent2,
745 aOffset2 < 0 ? UINT32_MAX : static_cast<uint32_t>(aOffset2));
747 return ComparePoints(aParent1, aOffset1, aParent2, aOffset2);
751 * Brute-force search of the element subtree rooted at aContent for
752 * an element with the given id. aId must be nonempty, otherwise
753 * this method may return nodes even if they have no id!
755 static Element* MatchElementId(nsIContent* aContent, const nsAString& aId);
758 * Similar to above, but to be used if one already has an atom for the ID
760 static Element* MatchElementId(nsIContent* aContent, const nsAtom* aId);
763 * Reverses the document position flags passed in.
765 * @param aDocumentPosition The document position flags to be reversed.
767 * @return The reversed document position flags.
769 * @see Node
771 static uint16_t ReverseDocumentPosition(uint16_t aDocumentPosition);
773 static const nsDependentSubstring TrimCharsInSet(const char* aSet,
774 const nsAString& aValue);
776 template <bool IsWhitespace(char16_t)>
777 static const nsDependentSubstring TrimWhitespace(const nsAString& aStr,
778 bool aTrimTrailing = true);
781 * Returns true if aChar is of class Ps, Pi, Po, Pf, or Pe.
783 static bool IsFirstLetterPunctuation(uint32_t aChar);
786 * Returns true if aChar is of class Lu, Ll, Lt, Lm, Lo, Nd, Nl or No
788 static bool IsAlphanumeric(uint32_t aChar);
790 * Returns true if aChar is of class L*, N* or S* (for first-letter).
792 static bool IsAlphanumericOrSymbol(uint32_t aChar);
794 * Returns true if aChar is a kind of hyphen.
796 static bool IsHyphen(uint32_t aChar);
799 * Is the character an HTML whitespace character?
801 * We define whitespace using the list in HTML5 and css3-selectors:
802 * U+0009, U+000A, U+000C, U+000D, U+0020
804 * HTML 4.01 also lists U+200B (zero-width space).
806 static bool IsHTMLWhitespace(char16_t aChar);
809 * Returns whether the character is an HTML whitespace (see IsHTMLWhitespace)
810 * or a nbsp character (U+00A0).
812 static bool IsHTMLWhitespaceOrNBSP(char16_t aChar);
815 * https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
817 static bool IsHTMLBlockLevelElement(nsIContent* aContent);
819 enum ParseHTMLIntegerResultFlags {
820 eParseHTMLInteger_NoFlags = 0,
821 // eParseHTMLInteger_NonStandard is set if the string representation of the
822 // integer was not the canonical one, but matches at least one of the
823 // following:
824 // * had leading whitespaces
825 // * had '+' sign
826 // * had leading '0'
827 // * was '-0'
828 eParseHTMLInteger_NonStandard = 1 << 0,
829 eParseHTMLInteger_DidNotConsumeAllInput = 1 << 1,
830 // Set if one or more error flags were set.
831 eParseHTMLInteger_Error = 1 << 2,
832 eParseHTMLInteger_ErrorNoValue = 1 << 3,
833 eParseHTMLInteger_ErrorOverflow = 1 << 4,
834 // Use this flag to detect the difference between overflow and underflow
835 eParseHTMLInteger_Negative = 1 << 5,
837 static int32_t ParseHTMLInteger(const nsAString& aValue,
838 ParseHTMLIntegerResultFlags* aResult) {
839 return ParseHTMLInteger(aValue.BeginReading(), aValue.EndReading(),
840 aResult);
842 static int32_t ParseHTMLInteger(const char16_t* aStart, const char16_t* aEnd,
843 ParseHTMLIntegerResultFlags* aResult);
844 static int32_t ParseHTMLInteger(const nsACString& aValue,
845 ParseHTMLIntegerResultFlags* aResult) {
846 return ParseHTMLInteger(aValue.BeginReading(), aValue.EndReading(),
847 aResult);
849 static int32_t ParseHTMLInteger(const char* aStart, const char* aEnd,
850 ParseHTMLIntegerResultFlags* aResult);
852 private:
853 template <class CharT>
854 static int32_t ParseHTMLIntegerImpl(const CharT* aStart, const CharT* aEnd,
855 ParseHTMLIntegerResultFlags* aResult);
857 public:
859 * Parse a margin string of format 'top, right, bottom, left' into
860 * an nsIntMargin.
862 * @param aString the string to parse
863 * @param aResult the resulting integer
864 * @return whether the value could be parsed
866 static bool ParseIntMarginValue(const nsAString& aString,
867 nsIntMargin& aResult);
870 * Parse the value of the <font size=""> attribute according to the HTML5
871 * spec as of April 16, 2012.
873 * @param aValue the value to parse
874 * @return 1 to 7, or 0 if the value couldn't be parsed
876 static int32_t ParseLegacyFontSize(const nsAString& aValue);
878 static void Shutdown();
881 * Checks whether two nodes come from the same origin.
883 static nsresult CheckSameOrigin(const nsINode* aTrustedNode,
884 const nsINode* unTrustedNode);
886 // Check if the (JS) caller can access aNode.
887 static bool CanCallerAccess(const nsINode* aNode);
889 // Check if the (JS) caller can access aWindow.
890 // aWindow can be either outer or inner window.
891 static bool CanCallerAccess(nsPIDOMWindowInner* aWindow);
893 // Check if the principal is chrome or an addon with the permission.
894 static bool PrincipalHasPermission(nsIPrincipal& aPrincipal,
895 const nsAtom* aPerm);
897 // Check if the JS caller is chrome or an addon with the permission.
898 static bool CallerHasPermission(JSContext* aCx, const nsAtom* aPerm);
901 * Returns the triggering principal which should be used for the given URL
902 * attribute value with the given subject principal.
904 * If the attribute value is not an absolute URL, the subject principal will
905 * be ignored, and the node principal of aContent will be used instead.
906 * If aContent is non-null, this function will always return a principal.
907 * Otherewise, it may return null if aSubjectPrincipal is null or is rejected
908 * based on the attribute value.
910 * @param aContent The content on which the attribute is being set.
911 * @param aAttrValue The URL value of the attribute. For parsed attribute
912 * values, such as `srcset`, this function should be called separately
913 * for each URL value it contains.
914 * @param aSubjectPrincipal The subject principal of the scripted caller
915 * responsible for setting the attribute, or null if no scripted caller
916 * can be determined.
918 static nsIPrincipal* GetAttrTriggeringPrincipal(
919 nsIContent* aContent, const nsAString& aAttrValue,
920 nsIPrincipal* aSubjectPrincipal);
923 * Returns true if the given string is guaranteed to be treated as an absolute
924 * URL, rather than a relative URL. In practice, this means any complete URL
925 * as supported by nsStandardURL, or any string beginning with a valid scheme
926 * which is known to the IO service, and has the URI_NORELATIVE flag.
928 * If the URL may be treated as absolute in some cases, but relative in others
929 * (for instance, "http:foo", which can be either an absolute or relative URL,
930 * depending on the context), this function returns false.
932 static bool IsAbsoluteURL(const nsACString& aURL);
934 // Check if a node is in the document prolog, i.e. before the document
935 // element.
936 static bool InProlog(nsINode* aNode);
938 static nsIBidiKeyboard* GetBidiKeyboard();
941 * Get the cache security manager service. Can return null if the layout
942 * module has been shut down.
944 static nsIScriptSecurityManager* GetSecurityManager() {
945 return sSecurityManager;
948 // Returns the subject principal from the JSContext. May only be called
949 // from the main thread and assumes an existing compartment.
950 static nsIPrincipal* SubjectPrincipal(JSContext* aCx);
952 // Returns the subject principal. Guaranteed to return non-null. May only
953 // be called when nsContentUtils is initialized.
954 static nsIPrincipal* SubjectPrincipal();
956 // Returns the prinipal of the given JS object. This may only be called on
957 // the main thread for objects from the main thread's JSRuntime. The object
958 // must not be a cross-compartment wrapper, because CCWs are not associated
959 // with a single realm.
960 static nsIPrincipal* ObjectPrincipal(JSObject* aObj);
962 static void GenerateStateKey(nsIContent* aContent, Document* aDocument,
963 nsACString& aKey);
966 * Create a new nsIURI from aSpec, using aBaseURI as the base. The
967 * origin charset of the new nsIURI will be the document charset of
968 * aDocument.
970 static nsresult NewURIWithDocumentCharset(nsIURI** aResult,
971 const nsAString& aSpec,
972 Document* aDocument,
973 nsIURI* aBaseURI);
976 * Returns true if |aName| is a name with dashes.
978 static bool IsNameWithDash(nsAtom* aName);
981 * Returns true if |aName| is a valid name to be registered via
982 * customElements.define.
984 static bool IsCustomElementName(nsAtom* aName, uint32_t aNameSpaceID);
986 static nsresult CheckQName(const nsAString& aQualifiedName,
987 bool aNamespaceAware = true,
988 const char16_t** aColon = nullptr);
990 static nsresult SplitQName(const nsIContent* aNamespaceResolver,
991 const nsString& aQName, int32_t* aNamespace,
992 nsAtom** aLocalName);
994 static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI,
995 const nsAString& aQualifiedName,
996 nsNodeInfoManager* aNodeInfoManager,
997 uint16_t aNodeType,
998 mozilla::dom::NodeInfo** aNodeInfo);
1000 static void SplitExpatName(const char16_t* aExpatName, nsAtom** aPrefix,
1001 nsAtom** aTagName, int32_t* aNameSpaceID);
1003 // Get a permission-manager setting for the given principal and type.
1004 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
1005 // returned, otherwise true is returned. Always returns true for the
1006 // system principal, and false for a null principal.
1007 static bool IsSitePermAllow(nsIPrincipal* aPrincipal,
1008 const nsACString& aType);
1010 // Get a permission-manager setting for the given principal and type.
1011 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
1012 // returned, otherwise true is returned. Always returns false for the
1013 // system principal, and true for a null principal.
1014 static bool IsSitePermDeny(nsIPrincipal* aPrincipal, const nsACString& aType);
1016 // Get a permission-manager setting for the given principal and type.
1017 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
1018 // returned, otherwise true is returned. Always returns true for the
1019 // system principal, and false for a null principal.
1020 // This version checks the permission for an exact host match on
1021 // the principal
1022 static bool IsExactSitePermAllow(nsIPrincipal* aPrincipal,
1023 const nsACString& aType);
1025 // Get a permission-manager setting for the given principal and type.
1026 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
1027 // returned, otherwise true is returned. Always returns false for the
1028 // system principal, and true for a null principal.
1029 // This version checks the permission for an exact host match on
1030 // the principal
1031 static bool IsExactSitePermDeny(nsIPrincipal* aPrincipal,
1032 const nsACString& aType);
1034 // Returns true if the pref exists and is not UNKNOWN_ACTION.
1035 static bool HasSitePerm(nsIPrincipal* aPrincipal, const nsACString& aType);
1037 // Returns true if aDoc1 and aDoc2 have equal NodePrincipal()s.
1038 static bool HaveEqualPrincipals(Document* aDoc1, Document* aDoc2);
1041 * Regster aObserver as a shutdown observer. A strong reference is held
1042 * to aObserver until UnregisterShutdownObserver is called.
1044 static void RegisterShutdownObserver(nsIObserver* aObserver);
1045 static void UnregisterShutdownObserver(nsIObserver* aObserver);
1048 * @return true if aContent has an attribute aName in namespace aNameSpaceID,
1049 * and the attribute value is non-empty.
1051 static bool HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID,
1052 nsAtom* aName);
1055 * Method that gets the primary presContext for the node.
1057 * @param aContent The content node.
1058 * @return the presContext, or nullptr if the content is not in a document
1059 * (if GetComposedDoc returns nullptr)
1061 static nsPresContext* GetContextForContent(const nsIContent* aContent);
1064 * Method that gets the pres shell for the node.
1066 * @param aContent The content node.
1067 * @return the pres shell, or nullptr if the content is not in a document
1068 * (if GetComposedDoc returns nullptr)
1070 static mozilla::PresShell* GetPresShellForContent(const nsIContent* aContent);
1073 * Method to do security and content policy checks on the image URI
1075 * @param aURI uri of the image to be loaded
1076 * @param aNode, the context the image is loaded in (eg an element)
1077 * @param aLoadingDocument the document we belong to
1078 * @param aLoadingPrincipal the principal doing the load
1079 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
1080 * (Optional) The CP content type to use
1081 * @param aImageBlockingStatus the nsIContentPolicy blocking status for this
1082 * image. This will be set even if a security check fails for the
1083 * image, to some reasonable REJECT_* value. This out param will only
1084 * be set if it's non-null.
1085 * @return true if the load can proceed, or false if it is blocked.
1086 * Note that aImageBlockingStatus, if set will always be an ACCEPT
1087 * status if true is returned and always be a REJECT_* status if
1088 * false is returned.
1090 static bool CanLoadImage(nsIURI* aURI, nsINode* aNode,
1091 Document* aLoadingDocument,
1092 nsIPrincipal* aLoadingPrincipal);
1095 * Returns true if objects in aDocument shouldn't initiate image loads.
1097 static bool DocumentInactiveForImageLoads(Document* aDocument);
1100 * Convert a CORSMode into the corresponding imgILoader flags for
1101 * passing to LoadImage.
1102 * @param aMode CORS mode to convert
1103 * @return a bitfield suitable to bitwise OR with other nsIRequest flags
1105 static int32_t CORSModeToLoadImageFlags(mozilla::CORSMode aMode);
1108 * Method to start an image load. This does not do any security checks.
1109 * This method will attempt to make aURI immutable; a caller that wants to
1110 * keep a mutable version around should pass in a clone.
1112 * @param aURI uri of the image to be loaded
1113 * @param aContext element of document where the result of this request
1114 * will be used.
1115 * @param aLoadingDocument the document we belong to
1116 * @param aLoadingPrincipal the principal doing the load
1117 * @param aReferrerInfo the referrerInfo use on channel creation
1118 * @param aObserver the observer for the image load
1119 * @param aLoadFlags the load flags to use. See nsIRequest
1120 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
1121 * (Optional) The CP content type to use
1122 * @param aUseUrgentStartForChannel,(Optional) a flag to mark on channel if it
1123 * is triggered by user input events.
1124 * @return the imgIRequest for the image load
1126 static nsresult LoadImage(
1127 nsIURI* aURI, nsINode* aContext, Document* aLoadingDocument,
1128 nsIPrincipal* aLoadingPrincipal, uint64_t aRequestContextID,
1129 nsIReferrerInfo* aReferrerInfo, imgINotificationObserver* aObserver,
1130 int32_t aLoadFlags, const nsAString& initiatorType,
1131 imgRequestProxy** aRequest,
1132 nsContentPolicyType aContentPolicyType =
1133 nsIContentPolicy::TYPE_INTERNAL_IMAGE,
1134 bool aUseUrgentStartForChannel = false, bool aLinkPreload = false,
1135 uint64_t aEarlyHintPreloaderId = 0,
1136 mozilla::dom::FetchPriority aFetchPriority =
1137 mozilla::dom::FetchPriority::Auto);
1140 * Obtain an image loader that respects the given document/channel's privacy
1141 * status. Null document/channel arguments return the public image loader.
1143 static imgLoader* GetImgLoaderForDocument(Document* aDoc);
1144 static imgLoader* GetImgLoaderForChannel(nsIChannel* aChannel,
1145 Document* aContext);
1148 * Method to get an imgIContainer from an image loading content
1150 * @param aContent The image loading content. Must not be null.
1151 * @param aRequest The image request [out]
1152 * @return the imgIContainer corresponding to the first frame of the image
1154 static already_AddRefed<imgIContainer> GetImageFromContent(
1155 nsIImageLoadingContent* aContent, imgIRequest** aRequest = nullptr);
1158 * Method that decides whether a content node is draggable
1160 * @param aContent The content node to test.
1161 * @return whether it's draggable
1163 static bool ContentIsDraggable(nsIContent* aContent);
1166 * Method that decides whether a content node is a draggable image
1168 * @param aContent The content node to test.
1169 * @return whether it's a draggable image
1171 static bool IsDraggableImage(nsIContent* aContent);
1174 * Method that decides whether a content node is a draggable link
1176 * @param aContent The content node to test.
1177 * @return whether it's a draggable link
1179 static bool IsDraggableLink(const nsIContent* aContent);
1182 * Convenience method to create a new nodeinfo that differs only by prefix and
1183 * name from aNodeInfo. The new nodeinfo's name is set to aName, and prefix is
1184 * set to null.
1186 static nsresult QNameChanged(mozilla::dom::NodeInfo* aNodeInfo, nsAtom* aName,
1187 mozilla::dom::NodeInfo** aResult);
1190 * Returns the appropriate event argument names for the specified
1191 * namespace and event name. Added because we need to switch between
1192 * SVG's "evt" and the rest of the world's "event", and because onerror
1193 * on window takes 5 args.
1195 static void GetEventArgNames(int32_t aNameSpaceID, nsAtom* aEventName,
1196 bool aIsForWindow, uint32_t* aArgCount,
1197 const char*** aArgNames);
1200 * Returns true if this document is in a Private Browsing window.
1202 static bool IsInPrivateBrowsing(const Document* aDoc);
1205 * Returns true if this loadGroup uses Private Browsing.
1207 static bool IsInPrivateBrowsing(nsILoadGroup* aLoadGroup);
1210 * Returns whether a node is in the same tree as another one, accounting for
1211 * anonymous roots.
1213 * This method is particularly useful for callers who are trying to ensure
1214 * that they are working with a non-anonymous descendant of a given node. If
1215 * aContent is a descendant of aNode, a return value of false from this
1216 * method means that it's an anonymous descendant from aNode's point of view.
1218 * Both arguments to this method must be non-null.
1220 static bool IsInSameAnonymousTree(const nsINode* aNode,
1221 const nsINode* aOtherNode);
1224 * Traverse the parent chain from aElement up to aStop, and return true if
1225 * there's an interactive html content; false otherwise.
1227 * Note: This crosses shadow boundaries but not document boundaries.
1229 static bool IsInInteractiveHTMLContent(const Element* aElement,
1230 const Element* aStop);
1233 * Return the nsIXPConnect service.
1235 static nsIXPConnect* XPConnect() { return sXPConnect; }
1238 * Report simple error message to the browser console
1239 * @param aErrorText the error message
1240 * @param aCategory Name of the module reporting error
1241 * @param aFromPrivateWindow Whether from private window or not
1242 * @param aFromChromeContext Whether from chrome context or not
1243 * @param [aErrorFlags] See nsIScriptError.
1245 static void LogSimpleConsoleError(
1246 const nsAString& aErrorText, const nsACString& aCategory,
1247 bool aFromPrivateWindow, bool aFromChromeContext,
1248 uint32_t aErrorFlags = nsIScriptError::errorFlag);
1251 * Report a non-localized error message to the error console.
1252 * @param aErrorText the error message
1253 * @param aErrorFlags See nsIScriptError.
1254 * @param aCategory Name of module reporting error.
1255 * @param aDocument Reference to the document which triggered the message.
1256 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1257 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1258 contains the error (may be empty).
1259 * @param [aLineNumber=0] (Optional) Line number within resource
1260 containing error.
1261 * @param [aColumnNumber=0] (Optional) Column number within resource
1262 containing error.
1263 If aURI is null, then aDocument->GetDocumentURI() is used.
1264 * @param [aLocationMode] (Optional) Specifies the behavior if
1265 error location information is omitted.
1267 enum MissingErrorLocationMode {
1268 // Don't show location information in the error console.
1269 eOMIT_LOCATION,
1270 // Get location information from the currently executing script.
1271 eUSE_CALLING_LOCATION
1273 static nsresult ReportToConsoleNonLocalized(
1274 const nsAString& aErrorText, uint32_t aErrorFlags,
1275 const nsACString& aCategory, const Document* aDocument,
1276 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1277 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0,
1278 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1281 * Report a non-localized error message to the error console base on the
1282 * innerWindowID.
1283 * @param aErrorText the error message
1284 * @param aErrorFlags See nsIScriptError.
1285 * @param aCategory Name of module reporting error.
1286 * @param [aInnerWindowID] Inner window ID for document which triggered the
1287 * message.
1288 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1289 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1290 contains the error (may be empty).
1291 * @param [aLineNumber=0] (Optional) Line number within resource
1292 containing error.
1293 * @param [aColumnNumber=1] (Optional) Column number within resource
1294 containing error.
1295 If aURI is null, then aDocument->GetDocumentURI() is used.
1296 * @param [aLocationMode] (Optional) Specifies the behavior if
1297 error location information is omitted.
1299 static nsresult ReportToConsoleByWindowID(
1300 const nsAString& aErrorText, uint32_t aErrorFlags,
1301 const nsACString& aCategory, uint64_t aInnerWindowID,
1302 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1303 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 1,
1304 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1307 * Report a localized error message to the error console.
1308 * @param aErrorFlags See nsIScriptError.
1309 * @param aCategory Name of module reporting error.
1310 * @param aDocument Reference to the document which triggered the message.
1311 * @param aFile Properties file containing localized message.
1312 * @param aMessageName Name of localized message.
1313 * @param [aParams=empty-array] (Optional) Parameters to be substituted into
1314 localized message.
1315 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1316 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1317 contains the error (may be empty).
1318 * @param [aLineNumber=0] (Optional) Line number within resource
1319 containing error.
1320 * @param [aColumnNumber=0] (Optional) Column number within resource
1321 containing error.
1322 If aURI is null, then aDocument->GetDocumentURI() is used.
1324 enum PropertiesFile {
1325 eCSS_PROPERTIES,
1326 eXUL_PROPERTIES,
1327 eLAYOUT_PROPERTIES,
1328 eFORMS_PROPERTIES,
1329 ePRINTING_PROPERTIES,
1330 eDOM_PROPERTIES,
1331 eHTMLPARSER_PROPERTIES,
1332 eSVG_PROPERTIES,
1333 eBRAND_PROPERTIES,
1334 eCOMMON_DIALOG_PROPERTIES,
1335 eMATHML_PROPERTIES,
1336 eSECURITY_PROPERTIES,
1337 eNECKO_PROPERTIES,
1338 eFORMS_PROPERTIES_en_US,
1339 eDOM_PROPERTIES_en_US,
1340 PropertiesFile_COUNT
1342 static nsresult ReportToConsole(
1343 uint32_t aErrorFlags, const nsACString& aCategory,
1344 const Document* aDocument, PropertiesFile aFile, const char* aMessageName,
1345 const nsTArray<nsString>& aParams = nsTArray<nsString>(),
1346 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1347 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0);
1349 static void ReportEmptyGetElementByIdArg(const Document* aDoc);
1351 static void LogMessageToConsole(const char* aMsg);
1353 static bool SpoofLocaleEnglish();
1356 * Get the localized string named |aKey| in properties file |aFile|.
1358 static nsresult GetLocalizedString(PropertiesFile aFile, const char* aKey,
1359 nsAString& aResult);
1362 * Same as GetLocalizedString, except that it might use en-US locale depending
1363 * on SpoofLocaleEnglish() and whether the document is a built-in browser
1364 * page.
1366 static nsresult GetMaybeLocalizedString(PropertiesFile aFile,
1367 const char* aKey, Document* aDocument,
1368 nsAString& aResult);
1371 * A helper function that parses a sandbox attribute (of an <iframe> or a CSP
1372 * directive) and converts it to the set of flags used internally.
1374 * @param aSandboxAttr the sandbox attribute
1375 * @return the set of flags (SANDBOXED_NONE if aSandboxAttr is
1376 * null)
1378 static uint32_t ParseSandboxAttributeToFlags(const nsAttrValue* aSandboxAttr);
1381 * A helper function that checks if a string matches a valid sandbox flag.
1383 * @param aFlag the potential sandbox flag.
1384 * @return true if the flag is a sandbox flag.
1386 static bool IsValidSandboxFlag(const nsAString& aFlag);
1389 * A helper function that returns a string attribute corresponding to the
1390 * sandbox flags.
1392 * @param aFlags the sandbox flags
1393 * @param aString the attribute corresponding to the flags (null if aFlags
1394 * is zero)
1396 static void SandboxFlagsToString(uint32_t aFlags, nsAString& aString);
1398 static bool PrefetchPreloadEnabled(nsIDocShell* aDocShell);
1400 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1401 nsAString& aSourceSpecOut, uint32_t* aLineOut,
1402 uint32_t* aColumnOut, nsString& aMessageOut);
1404 // Variant on `ExtractErrorValues` with a `nsACString`. This
1405 // method is provided for backwards compatibility. Prefer the
1406 // faster method above for your code.
1407 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1408 nsACString& aSourceSpecOut, uint32_t* aLineOut,
1409 uint32_t* aColumnOut, nsString& aMessageOut);
1411 static nsresult CalculateBufferSizeForImage(
1412 const uint32_t& aStride, const mozilla::gfx::IntSize& aImageSize,
1413 const mozilla::gfx::SurfaceFormat& aFormat, size_t* aMaxBufferSize,
1414 size_t* aUsedBufferSize);
1416 // Returns true if the URI's host is contained in a list which is a comma
1417 // separated domain list. Each item may start with "*.". If starts with
1418 // "*.", it matches any sub-domains.
1419 // The aList argument must be a lower-case string.
1420 static bool IsURIInList(nsIURI* aURI, const nsCString& aList);
1422 // Returns true if the URI's host is contained in a pref list which is a comma
1423 // separated domain list. Each item may start with "*.". If starts with
1424 // "*.", it matches any sub-domains.
1425 static bool IsURIInPrefList(nsIURI* aURI, const char* aPrefName);
1428 * A convenience version of FormatLocalizedString that can be used if all the
1429 * params are in same-typed strings. The variadic template args need to come
1430 * at the end, so we put aResult at the beginning to make sure it's clear
1431 * which is the output and which are the inputs.
1433 template <typename... T>
1434 static nsresult FormatLocalizedString(nsAString& aResult,
1435 PropertiesFile aFile, const char* aKey,
1436 const T&... aParams) {
1437 static_assert(sizeof...(aParams) != 0, "Use GetLocalizedString()");
1438 AutoTArray<nsString, sizeof...(aParams)> params = {
1439 aParams...,
1441 return FormatLocalizedString(aFile, aKey, params, aResult);
1445 * Same as FormatLocalizedString template version, except that it might use
1446 * en-US locale depending on SpoofLocaleEnglish() and whether the document is
1447 * a built-in browser page.
1449 template <typename... T>
1450 static nsresult FormatMaybeLocalizedString(nsAString& aResult,
1451 PropertiesFile aFile,
1452 const char* aKey,
1453 Document* aDocument,
1454 const T&... aParams) {
1455 static_assert(sizeof...(aParams) != 0, "Use GetMaybeLocalizedString()");
1456 AutoTArray<nsString, sizeof...(aParams)> params = {
1457 aParams...,
1459 return FormatMaybeLocalizedString(aFile, aKey, aDocument, params, aResult);
1463 * Fill (with the parameters given) the localized string named |aKey| in
1464 * properties file |aFile| consuming an nsTArray of nsString parameters rather
1465 * than a char16_t** for the sake of avoiding use-after-free errors involving
1466 * temporaries.
1468 static nsresult FormatLocalizedString(PropertiesFile aFile, const char* aKey,
1469 const nsTArray<nsString>& aParamArray,
1470 nsAString& aResult);
1473 * Same as FormatLocalizedString, except that it might use en-US locale
1474 * depending on SpoofLocaleEnglish() and whether the document is a built-in
1475 * browser page.
1477 static nsresult FormatMaybeLocalizedString(
1478 PropertiesFile aFile, const char* aKey, Document* aDocument,
1479 const nsTArray<nsString>& aParamArray, nsAString& aResult);
1482 * Returns true if aDocument is a chrome document
1484 static bool IsChromeDoc(const Document* aDocument);
1487 * Returns true if aDocument is in a docshell whose parent is the same type
1489 static bool IsChildOfSameType(Document* aDoc);
1492 * Returns true if the content-type will be rendered as plain-text.
1494 static bool IsPlainTextType(const nsACString& aContentType);
1497 * Returns true iff the type is rendered as plain text and doesn't support
1498 * non-UTF-8 encodings.
1500 static bool IsUtf8OnlyPlainTextType(const nsACString& aContentType);
1503 * Returns true if aDocument belongs to a chrome docshell for
1504 * display purposes. Returns false for null documents or documents
1505 * which do not belong to a docshell.
1507 static bool IsInChromeDocshell(const Document* aDocument);
1510 * Return the content policy service
1512 static nsIContentPolicy* GetContentPolicy();
1515 * Map internal content policy types to external ones.
1517 static inline ExtContentPolicyType InternalContentPolicyTypeToExternal(
1518 nsContentPolicyType aType);
1521 * check whether the Link header field applies to the context resource
1522 * see <http://tools.ietf.org/html/rfc5988#section-5.2>
1524 static bool LinkContextIsURI(const nsAString& aAnchor, nsIURI* aDocURI);
1527 * Returns true if the content policy type is any of:
1528 * * TYPE_INTERNAL_SCRIPT_PRELOAD
1529 * * TYPE_INTERNAL_IMAGE_PRELOAD
1530 * * TYPE_INTERNAL_STYLESHEET_PRELOAD
1532 static bool IsPreloadType(nsContentPolicyType aType);
1535 * Quick helper to determine whether there are any mutation listeners
1536 * of a given type that apply to this content or any of its ancestors.
1537 * The method has the side effect to call document's MayDispatchMutationEvent
1538 * using aTargetForSubtreeModified as the parameter.
1540 * @param aNode The node to search for listeners
1541 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1542 * @param aTargetForSubtreeModified The node which is the target of the
1543 * possible DOMSubtreeModified event.
1545 * @return true if there are mutation listeners of the specified type
1547 static bool HasMutationListeners(nsINode* aNode, uint32_t aType,
1548 nsINode* aTargetForSubtreeModified);
1551 * Quick helper to determine whether there are any mutation listeners
1552 * of a given type that apply to any content in this document. It is valid
1553 * to pass null for aDocument here, in which case this function always
1554 * returns true.
1556 * @param aDocument The document to search for listeners
1557 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1559 * @return true if there are mutation listeners of the specified type
1561 static bool HasMutationListeners(Document* aDocument, uint32_t aType);
1563 * Synchronously fire DOMNodeRemoved on aChild. Only fires the event if
1564 * there really are listeners by checking using the HasMutationListeners
1565 * function above. The function makes sure to hold the relevant objects alive
1566 * for the duration of the event firing. However there are no guarantees
1567 * that any of the objects are alive by the time the function returns.
1568 * If you depend on that you need to hold references yourself.
1570 * @param aChild The node to fire DOMNodeRemoved at.
1571 * @param aParent The parent of aChild.
1573 MOZ_CAN_RUN_SCRIPT static void MaybeFireNodeRemoved(nsINode* aChild,
1574 nsINode* aParent);
1577 * These methods create and dispatch a trusted event.
1578 * Works only with events which can be created by calling
1579 * Document::CreateEvent() with parameter "Events".
1580 * Note that don't use these methods for "input" event. Use
1581 * DispatchInputEvent() instead.
1583 * @param aDoc The document which will be used to create the event.
1584 * @param aTarget The target of the event.
1585 * @param aEventName The name of the event.
1586 * @param aCanBubble Whether the event can bubble.
1587 * @param aCancelable Is the event cancelable.
1588 * @param aCopmosed Is the event composed.
1589 * @param aDefaultAction Set to true if default action should be taken,
1590 * see EventTarget::DispatchEvent.
1592 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1593 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1594 static nsresult DispatchTrustedEvent(Document* aDoc,
1595 mozilla::dom::EventTarget* aTarget,
1596 const nsAString& aEventName, CanBubble,
1597 Cancelable,
1598 Composed aComposed = Composed::eDefault,
1599 bool* aDefaultAction = nullptr);
1601 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1602 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1603 static nsresult DispatchTrustedEvent(Document* aDoc,
1604 mozilla::dom::EventTarget* aTarget,
1605 const nsAString& aEventName,
1606 CanBubble aCanBubble,
1607 Cancelable aCancelable,
1608 bool* aDefaultAction) {
1609 return DispatchTrustedEvent(aDoc, aTarget, aEventName, aCanBubble,
1610 aCancelable, Composed::eDefault,
1611 aDefaultAction);
1615 * This method creates and dispatches a trusted event using an event message.
1616 * @param aDoc The document which will be used to create the event.
1617 * @param aTarget The target of the event.
1618 * @param aEventMessage The event message.
1619 * @param aCanBubble Whether the event can bubble.
1620 * @param aCancelable Is the event cancelable.
1621 * @param aDefaultAction Set to true if default action should be taken,
1622 * see EventTarget::DispatchEvent.
1624 template <class WidgetEventType>
1625 static nsresult DispatchTrustedEvent(
1626 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1627 EventMessage aEventMessage, CanBubble aCanBubble, Cancelable aCancelable,
1628 bool* aDefaultAction = nullptr,
1629 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1630 WidgetEventType event(true, aEventMessage);
1631 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1632 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1633 aCancelable, Trusted::eYes, aDefaultAction,
1634 aOnlyChromeDispatch);
1638 * This method dispatches "beforeinput" event with EditorInputEvent or
1639 * "input" event with proper event class. If it's unsafe to dispatch,
1640 * this put the event into the script runner queue. In such case, the
1641 * event becomes not cancelable even if it's defined as cancelable by
1642 * the spec.
1643 * Input Events spec defines as:
1644 * Input events are dispatched on elements that act as editing hosts,
1645 * including elements with the contenteditable attribute set, textarea
1646 * elements, and input elements that permit text input.
1648 * @param aEventTarget The event target element of the "beforeinput"
1649 * or "input" event. Must not be nullptr.
1650 * @param aEventMessage Muse be eEditorBeforeInput or eEditorInput.
1651 * @param aEditorInputType The inputType value of InputEvent.
1652 * If aEventTarget won't dispatch "input" event
1653 * with InputEvent, set EditorInputType::eUnknown.
1654 * @param aEditorBase Optional. If this is called by editor,
1655 * editor should set this. Otherwise, leave
1656 * nullptr.
1657 * @param aOptions Optional. If aEditorInputType value requires
1658 * some additional data, they should be properly
1659 * set with this argument.
1660 * @param aEventStatus Returns nsEventStatus_eConsumeNoDefault if
1661 * the dispatching event is cancelable and the
1662 * event was canceled by script (including
1663 * chrome script). Otherwise, returns given
1664 * value. Note that this can be nullptr only
1665 * when the dispatching event is not cancelable.
1667 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(Element* aEventTarget);
1668 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(
1669 Element* aEventTarget, mozilla::EventMessage aEventMessage,
1670 mozilla::EditorInputType aEditorInputType,
1671 mozilla::EditorBase* aEditorBase, mozilla::InputEventOptions&& aOptions,
1672 nsEventStatus* aEventStatus = nullptr);
1675 * This method creates and dispatches a untrusted event.
1676 * Works only with events which can be created by calling
1677 * Document::CreateEvent() with parameter "Events".
1678 * @param aDoc The document which will be used to create the event.
1679 * @param aTarget The target of the event.
1680 * @param aEventName The name of the event.
1681 * @param aCanBubble Whether the event can bubble.
1682 * @param aCancelable Is the event cancelable.
1683 * @param aDefaultAction Set to true if default action should be taken,
1684 * see EventTarget::DispatchEvent.
1686 static nsresult DispatchUntrustedEvent(Document* aDoc,
1687 mozilla::dom::EventTarget* aTarget,
1688 const nsAString& aEventName, CanBubble,
1689 Cancelable,
1690 bool* aDefaultAction = nullptr);
1693 * This method creates and dispatches a untrusted event using an event
1694 * message.
1695 * @param aDoc The document which will be used to create the event.
1696 * @param aTarget The target of the event.
1697 * @param aEventMessage The event message.
1698 * @param aCanBubble Whether the event can bubble.
1699 * @param aCancelable Is the event cancelable.
1700 * @param aDefaultAction Set to true if default action should be taken,
1701 * see EventTarget::DispatchEvent.
1703 template <class WidgetEventType>
1704 static nsresult DispatchUntrustedEvent(
1705 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1706 EventMessage aEventMessage, CanBubble aCanBubble, Cancelable aCancelable,
1707 bool* aDefaultAction = nullptr,
1708 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1709 WidgetEventType event(false, aEventMessage);
1710 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1711 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1712 aCancelable, Trusted::eNo, aDefaultAction,
1713 aOnlyChromeDispatch);
1717 * This method creates and dispatches a trusted event to the chrome
1718 * event handler (the parent object of the DOM Window in the event target
1719 * chain). Note, chrome event handler is used even if aTarget is a chrome
1720 * object. Use DispatchEventOnlyToChrome if the normal event dispatching is
1721 * wanted in case aTarget is a chrome object.
1722 * Works only with events which can be created by calling
1723 * Document::CreateEvent() with parameter "Events".
1724 * @param aDocument The document which will be used to create the event,
1725 * and whose window's chrome handler will be used to
1726 * dispatch the event.
1727 * @param aTarget The target of the event, used for event->SetTarget()
1728 * @param aEventName The name of the event.
1729 * @param aCanBubble Whether the event can bubble.
1730 * @param aCancelable Is the event cancelable.
1731 * @param aDefaultAction Set to true if default action should be taken,
1732 * see EventTarget::DispatchEvent.
1734 static nsresult DispatchChromeEvent(Document* aDoc,
1735 mozilla::dom::EventTarget* aTarget,
1736 const nsAString& aEventName, CanBubble,
1737 Cancelable,
1738 bool* aDefaultAction = nullptr);
1741 * Helper to dispatch a "framefocusrequested" event to chrome, which will only
1742 * bring the window to the foreground and switch tabs if aCanRaise is true.
1744 MOZ_CAN_RUN_SCRIPT_BOUNDARY static void RequestFrameFocus(
1745 Element& aFrameElement, bool aCanRaise,
1746 mozilla::dom::CallerType aCallerType);
1749 * This method creates and dispatches a trusted event.
1750 * If aTarget is not a chrome object, the nearest chrome object in the
1751 * propagation path will be used as the start of the event target chain.
1752 * This method is different than DispatchChromeEvent, which always dispatches
1753 * events to chrome event handler. DispatchEventOnlyToChrome works like
1754 * DispatchTrustedEvent in the case aTarget is a chrome object.
1755 * Works only with events which can be created by calling
1756 * Document::CreateEvent() with parameter "Events".
1757 * @param aDoc The document which will be used to create the event.
1758 * @param aTarget The target of the event.
1759 * @param aEventName The name of the event.
1760 * @param aCanBubble Whether the event can bubble.
1761 * @param aCancelable Is the event cancelable.
1762 * @param aComposed Is the event composed.
1763 * @param aDefaultAction Set to true if default action should be taken,
1764 * see EventTarget::DispatchEvent.
1766 static nsresult DispatchEventOnlyToChrome(
1767 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1768 const nsAString& aEventName, CanBubble, Cancelable,
1769 Composed aComposed = Composed::eDefault, bool* aDefaultAction = nullptr);
1771 static nsresult DispatchEventOnlyToChrome(Document* aDoc,
1772 mozilla::dom::EventTarget* aTarget,
1773 const nsAString& aEventName,
1774 CanBubble aCanBubble,
1775 Cancelable aCancelable,
1776 bool* aDefaultAction) {
1777 return DispatchEventOnlyToChrome(aDoc, aTarget, aEventName, aCanBubble,
1778 aCancelable, Composed::eDefault,
1779 aDefaultAction);
1783 * Determines if an event attribute name (such as onclick) is valid for
1784 * a given element type. Types are from the EventNameType enumeration
1785 * defined above.
1787 * @param aName the event name to look up
1788 * @param aType the type of content
1790 static bool IsEventAttributeName(nsAtom* aName, int32_t aType);
1793 * Return the event message for the event with the given name. The name is
1794 * the event name with the 'on' prefix. Returns eUnidentifiedEvent if the
1795 * event doesn't match a known event name.
1797 * @param aName the event name to look up
1799 static EventMessage GetEventMessage(nsAtom* aName);
1802 * Return the event type atom for a given event message.
1804 static nsAtom* GetEventTypeFromMessage(EventMessage aEventMessage);
1807 * Returns the EventMessage and nsAtom to be used for event listener
1808 * registration.
1810 static EventMessage GetEventMessageAndAtomForListener(const nsAString& aName,
1811 nsAtom** aOnName);
1814 * Return the EventClassID for the event with the given name. The name is the
1815 * event name *without* the 'on' prefix. Returns eBasicEventClass if the event
1816 * is not known to be of any particular event class.
1818 * @param aName the event name to look up
1820 static mozilla::EventClassID GetEventClassID(const nsAString& aName);
1823 * Return the event message and atom for the event with the given name.
1824 * The name is the event name *without* the 'on' prefix.
1825 * Returns eUnidentifiedEvent on the aEventID if the
1826 * event doesn't match a known event name in the category.
1828 * @param aName the event name to look up
1829 * @param aEventClassID only return event id for aEventClassID
1831 static nsAtom* GetEventMessageAndAtom(const nsAString& aName,
1832 mozilla::EventClassID aEventClassID,
1833 EventMessage* aEventMessage);
1836 * Used only during traversal of the XPCOM graph by the cycle
1837 * collector: push a pointer to the listener manager onto the
1838 * children deque, if it exists. Do nothing if there is no listener
1839 * manager.
1841 * Crucially: does not perform any refcounting operations.
1843 * @param aNode The node to traverse.
1844 * @param children The buffer to push a listener manager pointer into.
1846 static void TraverseListenerManager(nsINode* aNode,
1847 nsCycleCollectionTraversalCallback& cb);
1850 * Get the eventlistener manager for aNode, creating it if it does not
1851 * already exist.
1853 * @param aNode The node for which to get the eventlistener manager.
1855 static mozilla::EventListenerManager* GetListenerManagerForNode(
1856 nsINode* aNode);
1858 * Get the eventlistener manager for aNode, returning null if it does not
1859 * already exist.
1861 * @param aNode The node for which to get the eventlistener manager.
1863 static mozilla::EventListenerManager* GetExistingListenerManagerForNode(
1864 const nsINode* aNode);
1866 static void AddEntryToDOMArenaTable(nsINode* aNode,
1867 mozilla::dom::DOMArena* aDOMArena);
1869 static already_AddRefed<mozilla::dom::DOMArena> TakeEntryFromDOMArenaTable(
1870 const nsINode* aNode);
1872 static void UnmarkGrayJSListenersInCCGenerationDocuments();
1875 * Remove the eventlistener manager for aNode.
1877 * @param aNode The node for which to remove the eventlistener manager.
1879 static void RemoveListenerManager(nsINode* aNode);
1881 static bool IsInitialized() { return sInitialized; }
1884 * Checks if the localname/prefix/namespace triple is valid wrt prefix
1885 * and namespace according to the Namespaces in XML and DOM Code
1886 * specfications.
1888 * @param aLocalname localname of the node
1889 * @param aPrefix prefix of the node
1890 * @param aNamespaceID namespace of the node
1892 static bool IsValidNodeName(nsAtom* aLocalName, nsAtom* aPrefix,
1893 int32_t aNamespaceID);
1896 * Creates a DocumentFragment from text using a context node to resolve
1897 * namespaces.
1899 * Please note that for safety reasons, if the node principal of
1900 * aContextNode is the system principal, this function will automatically
1901 * sanitize its input using nsTreeSanitizer.
1903 * Note! In the HTML case with the HTML5 parser enabled, this is only called
1904 * from Range.createContextualFragment() and the implementation here is
1905 * quirky accordingly (html context node behaves like a body context node).
1906 * If you don't want that quirky behavior, don't use this method as-is!
1908 * @param aContextNode the node which is used to resolve namespaces
1909 * @param aFragment the string which is parsed to a DocumentFragment
1910 * @param aReturn the resulting fragment
1911 * @param aPreventScriptExecution whether to mark scripts as already started
1913 static already_AddRefed<mozilla::dom::DocumentFragment>
1914 CreateContextualFragment(nsINode* aContextNode, const nsAString& aFragment,
1915 bool aPreventScriptExecution,
1916 mozilla::ErrorResult& aRv);
1918 MOZ_CAN_RUN_SCRIPT
1919 static void SetHTMLUnsafe(mozilla::dom::FragmentOrElement* aTarget,
1920 Element* aContext, const nsAString& aSource);
1922 * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
1924 * Please note that for safety reasons, if the node principal of aTargetNode
1925 * is the system principal, this function will automatically sanitize its
1926 * input using nsTreeSanitizer.
1928 * @param aSourceBuffer the string being set as innerHTML
1929 * @param aTargetNode the target container
1930 * @param aContextLocalName local name of context node
1931 * @param aContextNamespace namespace of context node
1932 * @param aQuirks true to make <table> not close <p>
1933 * @param aPreventScriptExecution true to prevent scripts from executing;
1934 * don't set to false when parsing into a target node that has been
1935 * bound to tree.
1936 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1937 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1938 * long and NS_OK otherwise.
1939 * @param aFlags defaults to -1 indicating that ParseFragmentHTML will do
1940 * default sanitization for system privileged calls to it. Only
1941 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1942 * which will then used for sanitization of the fragment.
1943 * To pass explicit aFlags use any of the sanitization flags
1944 * listed in nsIParserUtils.idl.
1946 static nsresult ParseFragmentHTML(const nsAString& aSourceBuffer,
1947 nsIContent* aTargetNode,
1948 nsAtom* aContextLocalName,
1949 int32_t aContextNamespace, bool aQuirks,
1950 bool aPreventScriptExecution,
1951 int32_t aFlags = -1);
1954 * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
1956 * Please note that for safety reasons, if the node principal of aDocument
1957 * is the system principal, this function will automatically sanitize its
1958 * input using nsTreeSanitizer.
1960 * @param aSourceBuffer the string being set as innerHTML
1961 * @param aDocument the target document
1962 * @param aTagStack the namespace mapping context
1963 * @param aPreventExecution whether to mark scripts as already started
1964 * @param aFlags, pass -1 and ParseFragmentXML will do default
1965 * sanitization for system privileged calls to it. Only
1966 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1967 * which will then used for sanitization of the fragment.
1968 * To pass explicit aFlags use any of the sanitization flags
1969 * listed in nsIParserUtils.idl.
1970 * @param aReturn the result fragment
1971 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1972 * fragments is made, a return code from the XML parser.
1974 static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
1975 Document* aDocument,
1976 nsTArray<nsString>& aTagStack,
1977 bool aPreventScriptExecution, int32_t aFlags,
1978 mozilla::dom::DocumentFragment** aReturn);
1981 * Parse a string into a document using the HTML parser.
1982 * Script elements are marked unexecutable.
1984 * @param aSourceBuffer the string to parse as an HTML document
1985 * @param aTargetDocument the document object to parse into. Must not have
1986 * child nodes.
1987 * @param aScriptingEnabledForNoscriptParsing whether <noscript> is parsed
1988 * as if scripting was enabled
1989 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1990 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1991 * long and NS_OK otherwise.
1993 static nsresult ParseDocumentHTML(const nsAString& aSourceBuffer,
1994 Document* aTargetDocument,
1995 bool aScriptingEnabledForNoscriptParsing);
1998 * Converts HTML source to plain text by parsing the source and using the
1999 * plain text serializer on the resulting tree.
2001 * @param aSourceBuffer the string to parse as an HTML document
2002 * @param aResultBuffer the string where the plain text result appears;
2003 * may be the same string as aSourceBuffer
2004 * @param aFlags Flags from nsIDocumentEncoder.
2005 * @param aWrapCol Number of columns after which to line wrap; 0 for no
2006 * auto-wrapping
2007 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
2008 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
2009 * long and NS_OK otherwise.
2011 static nsresult ConvertToPlainText(const nsAString& aSourceBuffer,
2012 nsAString& aResultBuffer, uint32_t aFlags,
2013 uint32_t aWrapCol);
2016 * Creates a 'loaded-as-data' HTML document that takes that principal,
2017 * script global, and URL from the argument, which may be null.
2019 static already_AddRefed<Document> CreateInertHTMLDocument(
2020 const Document* aTemplate);
2023 * Creates a 'loaded-as-data' XML document that takes that principal,
2024 * script global, and URL from the argument, which may be null.
2026 static already_AddRefed<Document> CreateInertXMLDocument(
2027 const Document* aTemplate);
2029 public:
2031 * Sets the text contents of a node by replacing all existing children
2032 * with a single text child.
2034 * The function always notifies.
2036 * Will reuse the first text child if one is available. Will not reuse
2037 * existing cdata children.
2039 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2041 * @param aContent Node to set contents of.
2042 * @param aValue Value to set contents to.
2043 * @param aTryReuse When true, the function will try to reuse an existing
2044 * textnodes rather than always creating a new one.
2046 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult SetNodeTextContent(
2047 nsIContent* aContent, const nsAString& aValue, bool aTryReuse);
2050 * Get the textual contents of a node. This is a concatenation of all
2051 * textnodes that are direct or (depending on aDeep) indirect children
2052 * of the node.
2054 * NOTE! No serialization takes place and <br> elements
2055 * are not converted into newlines. Only textnodes and cdata nodes are
2056 * added to the result.
2058 * @see nsLayoutUtils::GetFrameTextContent
2060 * @param aNode Node to get textual contents of.
2061 * @param aDeep If true child elements of aNode are recursivly descended
2062 * into to find text children.
2063 * @param aResult the result. Out param.
2064 * @return false on out of memory errors, true otherwise.
2066 [[nodiscard]] static bool GetNodeTextContent(const nsINode* aNode, bool aDeep,
2067 nsAString& aResult,
2068 const mozilla::fallible_t&);
2070 static void GetNodeTextContent(const nsINode* aNode, bool aDeep,
2071 nsAString& aResult);
2074 * Same as GetNodeTextContents but appends the result rather than sets it.
2076 static bool AppendNodeTextContent(const nsINode* aNode, bool aDeep,
2077 nsAString& aResult,
2078 const mozilla::fallible_t&);
2081 * Utility method that checks if a given node has any non-empty children. This
2082 * method does not descend recursively into children by default.
2084 * @param aDiscoverMode Set to eRecurseIntoChildren to descend recursively
2085 * into children.
2087 enum TextContentDiscoverMode : uint8_t {
2088 eRecurseIntoChildren,
2089 eDontRecurseIntoChildren
2092 static bool HasNonEmptyTextContent(
2093 nsINode* aNode,
2094 TextContentDiscoverMode aDiscoverMode = eDontRecurseIntoChildren);
2097 * Delete strings allocated for nsContentList matches
2099 static void DestroyMatchString(void* aData);
2102 * Notify when the first XUL menu is opened and when the all XUL menus are
2103 * closed. At opening, aInstalling should be TRUE, otherwise, it should be
2104 * FALSE.
2106 MOZ_CAN_RUN_SCRIPT static void NotifyInstalledMenuKeyboardListener(
2107 bool aInstalling);
2110 * Check whether the nsIURI uses the given scheme.
2112 * Note that this will check the innermost URI rather than that of
2113 * the nsIURI itself.
2115 static bool SchemeIs(nsIURI* aURI, const char* aScheme);
2118 * Returns true if aPrincipal is an ExpandedPrincipal.
2120 static bool IsExpandedPrincipal(nsIPrincipal* aPrincipal);
2123 * Returns true if aPrincipal is the system or an ExpandedPrincipal.
2125 static bool IsSystemOrExpandedPrincipal(nsIPrincipal* aPrincipal);
2128 * Gets the system principal from the security manager.
2130 static nsIPrincipal* GetSystemPrincipal();
2133 * Gets the null subject principal singleton. This is only useful for
2134 * assertions.
2136 static nsIPrincipal* GetNullSubjectPrincipal() {
2137 return sNullSubjectPrincipal;
2141 * *aResourcePrincipal is a principal describing who may access the contents
2142 * of a resource. The resource can only be consumed by a principal that
2143 * subsumes *aResourcePrincipal. MAKE SURE THAT NOTHING EVER ACTS WITH THE
2144 * AUTHORITY OF *aResourcePrincipal.
2145 * It may be null to indicate that the resource has no data from any origin
2146 * in it yet and anything may access the resource.
2147 * Additional data is being mixed into the resource from aExtraPrincipal
2148 * (which may be null; if null, no data is being mixed in and this function
2149 * will do nothing). Update *aResourcePrincipal to reflect the new data.
2150 * If *aResourcePrincipal subsumes aExtraPrincipal, nothing needs to change,
2151 * otherwise *aResourcePrincipal is replaced with the system principal.
2152 * Returns true if *aResourcePrincipal changed.
2154 static bool CombineResourcePrincipals(
2155 nsCOMPtr<nsIPrincipal>* aResourcePrincipal,
2156 nsIPrincipal* aExtraPrincipal);
2159 * Trigger a link with uri aLinkURI. If aClick is false, this triggers a
2160 * mouseover on the link, otherwise it triggers a load after doing a
2161 * security check using aContent's principal.
2163 * @param aContent the node on which a link was triggered.
2164 * @param aLinkURI the URI of the link, must be non-null.
2165 * @param aTargetSpec the target (like target=, may be empty).
2166 * @param aClick whether this was a click or not (if false, this method
2167 * assumes you just hovered over the link).
2168 * @param aIsTrusted If false, JS Context will be pushed to stack
2169 * when the link is triggered.
2171 static void TriggerLink(nsIContent* aContent, nsIURI* aLinkURI,
2172 const nsString& aTargetSpec, bool aClick,
2173 bool aIsTrusted);
2176 * Get the link location.
2178 static void GetLinkLocation(mozilla::dom::Element* aElement,
2179 nsString& aLocationString);
2182 * Return top-level widget in the parent chain.
2184 static nsIWidget* GetTopLevelWidget(nsIWidget* aWidget);
2187 * Return the localized ellipsis for UI.
2189 static const nsDependentString GetLocalizedEllipsis();
2192 * Hide any XUL popups associated with aDocument, including any documents
2193 * displayed in child frames. Does nothing if aDocument is null.
2195 MOZ_CAN_RUN_SCRIPT_BOUNDARY static void HidePopupsInDocument(
2196 Document* aDocument);
2199 * Retrieve the current drag session, or null if no drag is currently occuring
2201 static already_AddRefed<nsIDragSession> GetDragSession();
2204 * Initialize and set the dataTransfer field of an WidgetDragEvent.
2206 static nsresult SetDataTransferInEvent(mozilla::WidgetDragEvent* aDragEvent);
2208 // filters the drag and drop action to fit within the effects allowed and
2209 // returns it.
2210 static uint32_t FilterDropEffect(uint32_t aAction, uint32_t aEffectAllowed);
2213 * Return true if the target of a drop event is a content document that is
2214 * an ancestor of the document for the source of the drag.
2216 static bool CheckForSubFrameDrop(nsIDragSession* aDragSession,
2217 mozilla::WidgetDragEvent* aDropEvent);
2220 * Return true if aURI is a local file URI (i.e. file://).
2222 static bool URIIsLocalFile(nsIURI* aURI);
2225 * Get the application manifest URI for this document. The manifest URI
2226 * is specified in the manifest= attribute of the root element of the
2227 * document.
2229 * @param aDocument The document that lists the manifest.
2230 * @param aURI The manifest URI.
2232 static void GetOfflineAppManifest(Document* aDocument, nsIURI** aURI);
2235 * Check whether an application should be allowed to use offline APIs.
2237 static bool OfflineAppAllowed(nsIURI* aURI);
2240 * Check whether an application should be allowed to use offline APIs.
2242 static bool OfflineAppAllowed(nsIPrincipal* aPrincipal);
2245 * Increases the count of blockers preventing scripts from running.
2246 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2247 * this directly
2249 static void AddScriptBlocker();
2252 * Decreases the count of blockers preventing scripts from running.
2253 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2254 * this directly
2256 * WARNING! Calling this function could synchronously execute scripts.
2258 static void RemoveScriptBlocker();
2261 * Add a runnable that is to be executed as soon as it's safe to execute
2262 * scripts.
2263 * NOTE: If it's currently safe to execute scripts, aRunnable will be run
2264 * synchronously before the function returns.
2266 * @param aRunnable The nsIRunnable to run as soon as it's safe to execute
2267 * scripts. Passing null is allowed and results in nothing
2268 * happening. It is also allowed to pass an object that
2269 * has not yet been AddRefed.
2271 static void AddScriptRunner(already_AddRefed<nsIRunnable> aRunnable);
2272 static void AddScriptRunner(nsIRunnable* aRunnable);
2275 * Returns true if it's safe to execute content script and false otherwise.
2277 * The only known case where this lies is mutation events. They run, and can
2278 * run anything else, when this function returns false, but this is ok.
2280 static bool IsSafeToRunScript();
2282 // Returns the browser window with the most recent time stamp that is
2283 // not in private browsing mode.
2284 static already_AddRefed<nsPIDOMWindowOuter> GetMostRecentNonPBWindow();
2287 * Call this function if !IsSafeToRunScript() and we fail to run the script
2288 * (rather than using AddScriptRunner as we usually do). |aDocument| is
2289 * optional as it is only used for showing the URL in the console.
2291 static void WarnScriptWasIgnored(Document* aDocument);
2294 * Add a "synchronous section", in the form of an nsIRunnable run once the
2295 * event loop has reached a "stable state". |aRunnable| must not cause any
2296 * queued events to be processed (i.e. must not spin the event loop).
2297 * We've reached a stable state when the currently executing task/event has
2298 * finished, see
2299 * http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#synchronous-section
2300 * In practice this runs aRunnable once the currently executing event
2301 * finishes. If called multiple times per task/event, all the runnables will
2302 * be executed, in the order in which RunInStableState() was called.
2304 static void RunInStableState(already_AddRefed<nsIRunnable> aRunnable);
2306 /* Add a pending IDBTransaction to be cleaned up at the end of performing a
2307 * microtask checkpoint.
2308 * See the step of "Cleanup Indexed Database Transactions" in
2309 * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
2311 static void AddPendingIDBTransaction(
2312 already_AddRefed<nsIRunnable> aTransaction);
2315 * Returns true if we are doing StableState/MetastableState.
2317 static bool IsInStableOrMetaStableState();
2319 static JSContext* GetCurrentJSContext();
2322 * Case insensitive comparison between two atoms.
2324 static bool EqualsIgnoreASCIICase(nsAtom* aAtom1, nsAtom* aAtom2);
2327 * Case insensitive comparison between two strings. However it only ignores
2328 * case for ASCII characters a-z.
2330 static bool EqualsIgnoreASCIICase(const nsAString& aStr1,
2331 const nsAString& aStr2);
2334 * Convert ASCII A-Z to a-z.
2336 static void ASCIIToLower(nsAString& aStr);
2337 static void ASCIIToLower(nsACString& aStr);
2338 static void ASCIIToLower(const nsAString& aSource, nsAString& aDest);
2339 static void ASCIIToLower(const nsACString& aSource, nsACString& aDest);
2342 * Convert ASCII a-z to A-Z.
2344 static void ASCIIToUpper(nsAString& aStr);
2345 static void ASCIIToUpper(nsACString& aStr);
2346 static void ASCIIToUpper(const nsAString& aSource, nsAString& aDest);
2347 static void ASCIIToUpper(const nsACString& aSource, nsACString& aDest);
2350 * Return whether aStr contains an ASCII uppercase character.
2352 static bool StringContainsASCIIUpper(const nsAString& aStr);
2354 // Returns NS_OK for same origin, error (NS_ERROR_DOM_BAD_URI) if not.
2355 static nsresult CheckSameOrigin(nsIChannel* aOldChannel,
2356 nsIChannel* aNewChannel);
2357 static nsIInterfaceRequestor* SameOriginChecker();
2360 * Returns an ASCII compatible serialization of the nsIPrincipal or nsIURI's
2361 * origin, as specified by the whatwg HTML specification. If the principal
2362 * does not have a host, the origin will be "null".
2364 * https://html.spec.whatwg.org/multipage/browsers.html#ascii-serialisation-of-an-origin
2366 * Note that this is different from nsIPrincipal::GetOrigin, does not contain
2367 * gecko-specific metadata like origin attributes, and should not be used for
2368 * permissions or security checks.
2370 * See also `nsIPrincipal::GetWebExposedOriginSerialization`.
2372 * These methods are thread-safe.
2374 * @pre aPrincipal/aURI must not be null.
2376 * @note this should be used for HTML5 origin determination.
2378 static nsresult GetWebExposedOriginSerialization(nsIURI* aURI,
2379 nsACString& aOrigin);
2380 static nsresult GetWebExposedOriginSerialization(nsIPrincipal* aPrincipal,
2381 nsAString& aOrigin);
2382 static nsresult GetWebExposedOriginSerialization(nsIURI* aURI,
2383 nsAString& aOrigin);
2386 * This method creates and dispatches "command" event, which implements
2387 * XULCommandEvent.
2388 * If aPresShell is not null, dispatching goes via
2389 * PresShell::HandleDOMEventWithTarget().
2391 MOZ_CAN_RUN_SCRIPT
2392 static nsresult DispatchXULCommand(
2393 nsIContent* aTarget, bool aTrusted,
2394 mozilla::dom::Event* aSourceEvent = nullptr,
2395 mozilla::PresShell* aPresShell = nullptr, bool aCtrl = false,
2396 bool aAlt = false, bool aShift = false, bool aMeta = false,
2397 // Including MouseEventBinding here leads
2398 // to incude loops, unfortunately.
2399 uint16_t inputSource = 0 /* MouseEvent_Binding::MOZ_SOURCE_UNKNOWN */,
2400 int16_t aButton = 0);
2402 static bool CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel,
2403 bool aAllowIfInheritsPrincipal);
2406 * The method checks whether the caller can access native anonymous content.
2407 * If there is no JS in the stack or privileged JS is running, this
2408 * method returns true, otherwise false.
2410 static bool CanAccessNativeAnon();
2412 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2413 const nsIID* aIID,
2414 JS::MutableHandle<JS::Value> vp,
2415 bool aAllowWrapping = true) {
2416 return WrapNative(cx, native, nullptr, aIID, vp, aAllowWrapping);
2419 // Same as the WrapNative above, but use this one if aIID is nsISupports' IID.
2420 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2421 JS::MutableHandle<JS::Value> vp,
2422 bool aAllowWrapping = true) {
2423 return WrapNative(cx, native, nullptr, nullptr, vp, aAllowWrapping);
2426 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2427 nsWrapperCache* cache,
2428 JS::MutableHandle<JS::Value> vp,
2429 bool aAllowWrapping = true) {
2430 return WrapNative(cx, native, cache, nullptr, vp, aAllowWrapping);
2433 static void StripNullChars(const nsAString& aInStr, nsAString& aOutStr);
2436 * Strip all \n, \r and nulls from the given string
2437 * @param aString the string to remove newlines from [in/out]
2439 static void RemoveNewlines(nsString& aString);
2442 * Convert Windows and Mac platform linebreaks to \n.
2443 * @param aString the string to convert the newlines inside [in/out]
2445 static void PlatformToDOMLineBreaks(nsString& aString);
2446 [[nodiscard]] static bool PlatformToDOMLineBreaks(nsString& aString,
2447 const mozilla::fallible_t&);
2450 * Populates aResultString with the contents of the string-buffer aBuf, up
2451 * to aBuf's null-terminator. aBuf must not be null. Ownership of the string
2452 * is not transferred.
2454 static void PopulateStringFromStringBuffer(nsStringBuffer* aBuf,
2455 nsAString& aResultString);
2457 static bool IsHandlingKeyBoardEvent() { return sIsHandlingKeyBoardEvent; }
2459 static void SetIsHandlingKeyBoardEvent(bool aHandling) {
2460 sIsHandlingKeyBoardEvent = aHandling;
2464 * Utility method for getElementsByClassName. aRootNode is the node (either
2465 * document or element), which getElementsByClassName was called on.
2467 static already_AddRefed<nsContentList> GetElementsByClassName(
2468 nsINode* aRootNode, const nsAString& aClasses);
2471 * Returns a presshell for this document, if there is one. This will be
2472 * aDoc's direct presshell if there is one, otherwise we'll look at all
2473 * ancestor documents to try to find a presshell, so for example this can
2474 * still find a presshell for documents in display:none frames that have
2475 * no presentation. So you have to be careful how you use this presshell ---
2476 * getting generic data like a device context or widget from it is OK, but it
2477 * might not be this document's actual presentation.
2479 static mozilla::PresShell* FindPresShellForDocument(
2480 const Document* aDocument);
2483 * Like FindPresShellForDocument, but returns the shell's PresContext instead.
2485 static nsPresContext* FindPresContextForDocument(const Document* aDocument);
2488 * Returns the widget for this document if there is one. Looks at all ancestor
2489 * documents to try to find a widget, so for example this can still find a
2490 * widget for documents in display:none frames that have no presentation.
2492 * You should probably use WidgetForContent() instead of this, unless you have
2493 * a good reason to do otherwise.
2495 static nsIWidget* WidgetForDocument(const Document* aDocument);
2498 * Returns the appropriate widget for this element, if there is one. Unlike
2499 * WidgetForDocument(), this returns the correct widget for content in popups.
2501 * You should probably use this instead of WidgetForDocument().
2503 static nsIWidget* WidgetForContent(const nsIContent* aContent);
2506 * Returns a window renderer to use for the given document. Basically we
2507 * look up the document hierarchy for the first document which has
2508 * a presentation with an associated widget, and use that widget's
2509 * window renderer.
2511 * You should probably use WindowRendererForContent() instead of this, unless
2512 * you have a good reason to do otherwise.
2514 * @param aDoc the document for which to return a window renderer.
2515 * @param aAllowRetaining an outparam that states whether the returned
2516 * layer manager should be used for retained layers
2518 static mozilla::WindowRenderer* WindowRendererForDocument(
2519 const Document* aDoc);
2522 * Returns a window renderer to use for the given content. Unlike
2523 * WindowRendererForDocument(), this returns the correct window renderer for
2524 * content in popups.
2526 * You should probably use this instead of WindowRendererForDocument().
2528 static mozilla::WindowRenderer* WindowRendererForContent(
2529 const nsIContent* aContent);
2532 * Determine whether a content node is focused or not,
2534 * @param aContent the content node to check
2535 * @return true if the content node is focused, false otherwise.
2537 static bool IsFocusedContent(const nsIContent* aContent);
2540 * Returns true if calling execCommand with 'cut' or 'copy' arguments is
2541 * allowed for the given subject principal. These are only allowed if the user
2542 * initiated them (like with a mouse-click or key press).
2544 static bool IsCutCopyAllowed(Document* aDocument,
2545 nsIPrincipal& aSubjectPrincipal);
2548 * Returns true if CSSOM origin check should be skipped for WebDriver
2549 * based crawl to be able to collect data from cross-origin CSS style
2550 * sheets. This can be enabled by setting environment variable
2551 * MOZ_BYPASS_CSSOM_ORIGIN_CHECK.
2553 static bool BypassCSSOMOriginCheck() {
2554 #ifdef RELEASE_OR_BETA
2555 return false;
2556 #else
2557 return sBypassCSSOMOriginCheck;
2558 #endif
2562 * Fire mutation events for changes caused by parsing directly into a
2563 * context node.
2565 * @param aDoc the document of the node
2566 * @param aDest the destination node that got stuff appended to it
2567 * @param aOldChildCount the number of children the node had before parsing
2569 static void FireMutationEventsForDirectParsing(Document* aDoc,
2570 nsIContent* aDest,
2571 int32_t aOldChildCount);
2574 * Returns the in-process subtree root document in a document hierarchy.
2575 * This could be a chrome document.
2577 static Document* GetInProcessSubtreeRootDocument(Document* aDoc) {
2578 return const_cast<Document*>(
2579 GetInProcessSubtreeRootDocument(const_cast<const Document*>(aDoc)));
2581 static const Document* GetInProcessSubtreeRootDocument(const Document* aDoc);
2583 static void GetShiftText(nsAString& text);
2584 static void GetControlText(nsAString& text);
2585 static void GetCommandOrWinText(nsAString& text);
2586 static void GetAltText(nsAString& text);
2587 static void GetModifierSeparatorText(nsAString& text);
2590 * Returns if aContent has the 'scrollgrab' property.
2591 * aContent may be null (in this case false is returned).
2593 static bool HasScrollgrab(nsIContent* aContent);
2596 * Flushes the layout tree (recursively)
2598 * @param aWindow the window the flush should start at
2601 static void FlushLayoutForTree(nsPIDOMWindowOuter* aWindow);
2604 * Returns true if content with the given principal is allowed to use XUL
2605 * and XBL and false otherwise.
2607 static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
2610 * Perform cleanup that's appropriate for XPCOM shutdown.
2612 static void XPCOMShutdown();
2615 * Checks if internal PDF viewer is enabled.
2617 static bool IsPDFJSEnabled();
2620 * Checks to see whether the given principal is the internal PDF
2621 * viewer principal.
2623 static bool IsPDFJS(nsIPrincipal* aPrincipal);
2625 * Same, but from WebIDL bindings. Checks whether the subject principal is for
2626 * the internal PDF viewer or system JS.
2628 static bool IsSystemOrPDFJS(JSContext*, JSObject*);
2631 * Checks if the given JSContext is secure or if the subject principal is
2632 * either an addon principal or an expanded principal, which contains at least
2633 * one addon principal.
2635 static bool IsSecureContextOrWebExtension(JSContext*, JSObject*);
2637 enum DocumentViewerType {
2638 TYPE_UNSUPPORTED,
2639 TYPE_CONTENT,
2640 TYPE_FALLBACK,
2641 TYPE_UNKNOWN
2644 static already_AddRefed<nsIDocumentLoaderFactory> FindInternalDocumentViewer(
2645 const nsACString& aType, DocumentViewerType* aLoaderType = nullptr);
2648 * This helper method returns true if the aPattern pattern matches aValue.
2649 * aPattern should not contain leading and trailing slashes (/).
2650 * The pattern has to match the entire value not just a subset.
2651 * aDocument must be a valid pointer (not null).
2653 * This is following the HTML5 specification:
2654 * http://dev.w3.org/html5/spec/forms.html#attr-input-pattern
2656 * WARNING: This method mutates aPattern!
2658 * @param aValue the string to check.
2659 * @param aPattern the string defining the pattern.
2660 * @param aDocument the owner document of the element.
2661 * @param aHasMultiple whether or not there are multiple values.
2662 * @param aFlags the flags to use for creating the regexp object.
2663 * @result whether the given string is matches the pattern, or
2664 * Nothing() if the pattern couldn't be evaluated.
2666 static mozilla::Maybe<bool> IsPatternMatching(
2667 const nsAString& aValue, nsString&& aPattern, const Document* aDocument,
2668 bool aHasMultiple = false,
2669 JS::RegExpFlags aFlags = JS::RegExpFlag::UnicodeSets);
2672 * Calling this adds support for
2673 * ontouch* event handler DOM attributes.
2675 static void InitializeTouchEventTable();
2678 * Test whether the given URI always inherits a security context
2679 * from the document it comes from.
2681 static nsresult URIInheritsSecurityContext(nsIURI* aURI, bool* aResult);
2684 * Called before a channel is created to query whether the new
2685 * channel should inherit the principal.
2687 * The argument aLoadingPrincipal must not be null. The argument
2688 * aURI must be the URI of the new channel. If aInheritForAboutBlank
2689 * is true, then about:blank will be told to inherit the principal.
2690 * If aForceInherit is true, the new channel will be told to inherit
2691 * the principal no matter what.
2693 * The return value is whether the new channel should inherit
2694 * the principal.
2696 static bool ChannelShouldInheritPrincipal(nsIPrincipal* aLoadingPrincipal,
2697 nsIURI* aURI,
2698 bool aInheritForAboutBlank,
2699 bool aForceInherit);
2701 static nsresult Btoa(const nsAString& aBinaryData,
2702 nsAString& aAsciiBase64String);
2704 static nsresult Atob(const nsAString& aAsciiString, nsAString& aBinaryData);
2707 * Returns whether the input element passed in parameter has the autocomplete
2708 * functionality enabled. It is taking into account the form owner.
2709 * NOTE: the caller has to make sure autocomplete makes sense for the
2710 * element's type.
2712 * @param aInput the input element to check. NOTE: aInput can't be null.
2713 * @return whether the input element has autocomplete enabled.
2715 static bool IsAutocompleteEnabled(mozilla::dom::HTMLInputElement* aInput);
2717 enum AutocompleteAttrState : uint8_t {
2718 eAutocompleteAttrState_Unknown = 1,
2719 eAutocompleteAttrState_Invalid,
2720 eAutocompleteAttrState_Valid,
2723 * Parses the value of the autocomplete attribute into aResult, ensuring it's
2724 * composed of valid tokens, otherwise the value "" is used.
2725 * Note that this method is used for form fields, not on a <form> itself.
2727 * @return whether aAttr was valid and can be cached.
2729 static AutocompleteAttrState SerializeAutocompleteAttribute(
2730 const nsAttrValue* aAttr, nsAString& aResult,
2731 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown);
2733 /* Variation that is used to retrieve a dictionary of the parts of the
2734 * autocomplete attribute.
2736 * @return whether aAttr was valid and can be cached.
2738 static AutocompleteAttrState SerializeAutocompleteAttribute(
2739 const nsAttrValue* aAttr, mozilla::dom::AutocompleteInfo& aInfo,
2740 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown,
2741 bool aGrantAllValidValue = false);
2744 * This will parse aSource, to extract the value of the pseudo attribute
2745 * with the name specified in aName. See
2746 * http://www.w3.org/TR/xml-stylesheet/#NT-StyleSheetPI for the specification
2747 * which is used to parse aSource.
2749 * @param aSource the string to parse
2750 * @param aName the name of the attribute to get the value for
2751 * @param aValue [out] the value for the attribute with name specified in
2752 * aAttribute. Empty if the attribute isn't present.
2753 * @return true if the attribute exists and was successfully parsed.
2754 * false if the attribute doesn't exist, or has a malformed
2755 * value, such as an unknown or unterminated entity.
2757 static bool GetPseudoAttributeValue(const nsString& aSource, nsAtom* aName,
2758 nsAString& aValue);
2761 * Returns true if the language name is a version of JavaScript and
2762 * false otherwise
2764 static bool IsJavaScriptLanguage(const nsString& aName);
2766 static bool IsJavascriptMIMEType(const nsAString& aMIMEType);
2768 static void SplitMimeType(const nsAString& aValue, nsString& aType,
2769 nsString& aParams);
2772 * Check whether aContent and aOffsetInContent points in a selection range of
2773 * one of ranges in aSelection. If aSelection is collapsed, this always
2774 * return false even if aContent and aOffsetInContent is same as the collapsed
2775 * position.
2777 * @param aSelection The selection you want to check whether point is in a
2778 * range of it.
2779 * @param aNode The container node of the point which you want to check.
2780 * @param aOffset The offset in aNode of the point which you want to
2781 * check. aNode and aOffset can be computed with
2782 * UIEvent::GetRangeParentContentAndOffset() if you want to
2783 * check the click point.
2784 * @param aAllowCrossShadowBoundary If true, this method allows the selection
2785 * to have boundaries that cross shadow
2786 * boundaries.
2788 static bool IsPointInSelection(const mozilla::dom::Selection& aSelection,
2789 const nsINode& aNode, const uint32_t aOffset,
2790 const bool aAllowCrossShadowBoundary = false);
2793 * Takes a selection, and a text control element (<input> or <textarea>), and
2794 * returns the offsets in the text content corresponding to the selection.
2795 * The selection's anchor and focus must both be in the root node passed or a
2796 * descendant.
2798 * @param aSelection Selection to check
2799 * @param aRoot Root <input> or <textarea> element
2800 * @param aOutStartOffset Output start offset
2801 * @param aOutEndOffset Output end offset
2803 static void GetSelectionInTextControl(mozilla::dom::Selection* aSelection,
2804 Element* aRoot,
2805 uint32_t& aOutStartOffset,
2806 uint32_t& aOutEndOffset);
2809 * Takes a frame for anonymous content within a text control (<input> or
2810 * <textarea>), and returns an offset in the text content, adjusted for a
2811 * trailing <br> frame.
2813 * @param aOffsetFrame Frame for the text content in which the offset
2814 * lies
2815 * @param aOffset Offset as calculated by GetContentOffsetsFromPoint
2816 * @param aOutOffset Output adjusted offset
2818 * @see GetSelectionInTextControl for the original basis of this function.
2820 static int32_t GetAdjustedOffsetInTextControl(nsIFrame* aOffsetFrame,
2821 int32_t aOffset);
2824 * Returns pointer to HTML editor instance for the aPresContext when there is.
2825 * The HTML editor is shared by contenteditable elements or used in
2826 * designMode. When there are no contenteditable elements and the document
2827 * is not in designMode, this returns nullptr.
2829 static mozilla::HTMLEditor* GetHTMLEditor(nsPresContext* aPresContext);
2830 static mozilla::HTMLEditor* GetHTMLEditor(nsDocShell* aDocShell);
2833 * Returns pointer to a text editor if <input> or <textarea> element is
2834 * active element in the document for aPresContext, or pointer to HTML
2835 * editor if there is (i.e., even if non-editable element has focus or
2836 * nobody has focus). The reason is, HTML editor may handle some input
2837 * even if there is no active editing host.
2838 * Note that this does not return editor in descendant documents.
2840 static mozilla::EditorBase* GetActiveEditor(nsPresContext* aPresContext);
2841 static mozilla::EditorBase* GetActiveEditor(nsPIDOMWindowOuter* aWindow);
2844 * Returns `TextEditor` which manages `aAnonymousContent` if there is.
2845 * Note that this method returns `nullptr` if `TextEditor` for the
2846 * `aAnonymousContent` hasn't been created yet.
2848 static mozilla::TextEditor* GetTextEditorFromAnonymousNodeWithoutCreation(
2849 const nsIContent* aAnonymousContent);
2852 * Returns whether a node has an editable ancestor.
2854 * @param aNode The node to test.
2856 static bool IsNodeInEditableRegion(nsINode* aNode);
2859 * Returns a LogModule that logs debugging info from RFP functions.
2861 static mozilla::LogModule* ResistFingerprintingLog();
2864 * Returns a LogModule that dump calls from content script are logged to.
2865 * This can be enabled with the 'Dump' module, and is useful for synchronizing
2866 * content JS to other logging modules.
2868 static mozilla::LogModule* DOMDumpLog();
2871 * Returns whether a given header is forbidden for an XHR or fetch
2872 * request.
2874 static bool IsForbiddenRequestHeader(const nsACString& aHeader,
2875 const nsACString& aValue);
2878 * Returns whether a given header is forbidden for a system XHR
2879 * request.
2881 static bool IsForbiddenSystemRequestHeader(const nsACString& aHeader);
2884 * Checks whether the header overrides any http methods
2886 static bool IsOverrideMethodHeader(const nsACString& headerName);
2888 * Checks whether the header value contains any forbidden method
2890 static bool ContainsForbiddenMethod(const nsACString& headerValue);
2892 class ParsedRange {
2893 public:
2894 explicit ParsedRange(mozilla::Maybe<uint64_t> aStart,
2895 mozilla::Maybe<uint64_t> aEnd)
2896 : mStart(aStart), mEnd(aEnd) {}
2898 mozilla::Maybe<uint64_t> Start() const { return mStart; }
2899 mozilla::Maybe<uint64_t> End() const { return mEnd; }
2901 bool operator==(const ParsedRange& aOther) const {
2902 return Start() == aOther.Start() && End() == aOther.End();
2905 private:
2906 mozilla::Maybe<uint64_t> mStart;
2907 mozilla::Maybe<uint64_t> mEnd;
2911 * Parse a single range request and return a pair containing the resulting
2912 * start and end of the range.
2914 * See https://fetch.spec.whatwg.org/#simple-range-header-value
2916 static mozilla::Maybe<ParsedRange> ParseSingleRangeRequest(
2917 const nsACString& aHeaderValue, bool aAllowWhitespace);
2920 * Returns whether a given header has characters that aren't permitted
2922 static bool IsCorsUnsafeRequestHeaderValue(const nsACString& aHeaderValue);
2925 * Returns whether a given Accept header value is allowed
2926 * for a non-CORS XHR or fetch request.
2928 static bool IsAllowedNonCorsAccept(const nsACString& aHeaderValue);
2931 * Returns whether a given Content-Type header value is allowed
2932 * for a non-CORS XHR or fetch request.
2934 static bool IsAllowedNonCorsContentType(const nsACString& aHeaderValue);
2937 * Returns whether a given Content-Language or accept-language header value is
2938 * allowed for a non-CORS XHR or fetch request.
2940 static bool IsAllowedNonCorsLanguage(const nsACString& aHeaderValue);
2943 * Returns whether a given Range header value is allowed for a non-CORS XHR or
2944 * fetch request.
2946 static bool IsAllowedNonCorsRange(const nsACString& aHeaderValue);
2949 * Returns whether a given header and value is a CORS-safelisted request
2950 * header per https://fetch.spec.whatwg.org/#cors-safelisted-request-header
2952 static bool IsCORSSafelistedRequestHeader(const nsACString& aName,
2953 const nsACString& aValue);
2956 * Returns whether a given header is forbidden for an XHR or fetch
2957 * response.
2959 static bool IsForbiddenResponseHeader(const nsACString& aHeader);
2962 * Returns the inner window ID for the window associated with a request.
2964 static uint64_t GetInnerWindowID(nsIRequest* aRequest);
2967 * Returns the inner window ID for the window associated with a load group.
2969 static uint64_t GetInnerWindowID(nsILoadGroup* aLoadGroup);
2972 * Encloses aHost in brackets if it is an IPv6 address.
2974 static void MaybeFixIPv6Host(nsACString& aHost);
2977 * If the hostname for aURI is an IPv6 it encloses it in brackets,
2978 * otherwise it just outputs the hostname in aHost.
2980 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsAString& aHost);
2981 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsACString& aHost);
2982 static nsresult GetHostOrIPv6WithBrackets(nsIPrincipal* aPrincipal,
2983 nsACString& aHost);
2986 * Call the given callback on all remote children of the given top-level
2987 * window. Return Callstate::Stop from the callback to stop calling further
2988 * children.
2990 static void CallOnAllRemoteChildren(
2991 nsPIDOMWindowOuter* aWindow,
2992 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
2993 aCallback);
2996 * Given an IPCDataTransferImageContainer construct an imgIContainer for the
2997 * image encoded by the transfer item.
2999 static nsresult DeserializeTransferableDataImageContainer(
3000 const mozilla::dom::IPCTransferableDataImageContainer& aData,
3001 imgIContainer** aContainer);
3004 * Given a flavor obtained from an IPCDataTransferItem or nsITransferable,
3005 * returns true if we should treat the data as an image.
3007 static bool IsFlavorImage(const nsACString& aFlavor);
3009 static bool IPCTransferableDataItemHasKnownFlavor(
3010 const mozilla::dom::IPCTransferableDataItem& aItem);
3012 static nsresult IPCTransferableDataToTransferable(
3013 const mozilla::dom::IPCTransferableData& aTransferableData,
3014 bool aAddDataFlavor, nsITransferable* aTransferable,
3015 const bool aFilterUnknownFlavors);
3017 static nsresult IPCTransferableToTransferable(
3018 const mozilla::dom::IPCTransferable& aIPCTransferable,
3019 bool aAddDataFlavor, nsITransferable* aTransferable,
3020 const bool aFilterUnknownFlavors);
3022 static nsresult IPCTransferableDataItemToVariant(
3023 const mozilla::dom::IPCTransferableDataItem& aItem,
3024 nsIWritableVariant* aVariant);
3026 static void TransferablesToIPCTransferableDatas(
3027 nsIArray* aTransferables,
3028 nsTArray<mozilla::dom::IPCTransferableData>& aIPC, bool aInSyncMessage,
3029 mozilla::dom::ContentParent* aParent);
3031 static void TransferableToIPCTransferableData(
3032 nsITransferable* aTransferable,
3033 mozilla::dom::IPCTransferableData* aTransferableData, bool aInSyncMessage,
3034 mozilla::dom::ContentParent* aParent);
3036 static void TransferableToIPCTransferable(
3037 nsITransferable* aTransferable,
3038 mozilla::dom::IPCTransferable* aIPCTransferable, bool aInSyncMessage,
3039 mozilla::dom::ContentParent* aParent);
3042 * Get the pixel data from the given source surface and return it as a
3043 * BigBuffer. The length and stride will be assigned from the surface.
3045 static mozilla::Maybe<mozilla::ipc::BigBuffer> GetSurfaceData(
3046 mozilla::gfx::DataSourceSurface&, size_t* aLength, int32_t* aStride);
3048 static mozilla::Maybe<mozilla::dom::IPCImage> SurfaceToIPCImage(
3049 mozilla::gfx::DataSourceSurface&);
3050 static already_AddRefed<mozilla::gfx::DataSourceSurface> IPCImageToSurface(
3051 mozilla::dom::IPCImage&&);
3053 // Helpers shared by the implementations of nsContentUtils methods and
3054 // nsIDOMWindowUtils methods.
3055 static mozilla::Modifiers GetWidgetModifiers(int32_t aModifiers);
3056 static nsIWidget* GetWidget(mozilla::PresShell* aPresShell, nsPoint* aOffset);
3057 static int16_t GetButtonsFlagForButton(int32_t aButton);
3058 static mozilla::LayoutDeviceIntPoint ToWidgetPoint(
3059 const mozilla::CSSPoint& aPoint, const nsPoint& aOffset,
3060 nsPresContext* aPresContext);
3061 static nsView* GetViewToDispatchEvent(nsPresContext* aPresContext,
3062 mozilla::PresShell** aPresShell);
3065 * Synthesize a mouse event to the given widget
3066 * (see nsIDOMWindowUtils.sendMouseEvent).
3068 MOZ_CAN_RUN_SCRIPT
3069 static nsresult SendMouseEvent(
3070 mozilla::PresShell* aPresShell, const nsAString& aType, float aX,
3071 float aY, int32_t aButton, int32_t aButtons, int32_t aClickCount,
3072 int32_t aModifiers, bool aIgnoreRootScrollFrame, float aPressure,
3073 unsigned short aInputSourceArg, uint32_t aIdentifier, bool aToWindow,
3074 mozilla::PreventDefaultResult* aPreventDefault,
3075 bool aIsDOMEventSynthesized, bool aIsWidgetEventSynthesized);
3077 static void FirePageShowEventForFrameLoaderSwap(
3078 nsIDocShellTreeItem* aItem,
3079 mozilla::dom::EventTarget* aChromeEventHandler, bool aFireIfShowing,
3080 bool aOnlySystemGroup = false);
3082 static void FirePageHideEventForFrameLoaderSwap(
3083 nsIDocShellTreeItem* aItem,
3084 mozilla::dom::EventTarget* aChromeEventHandler,
3085 bool aOnlySystemGroup = false);
3087 static already_AddRefed<nsPIWindowRoot> GetWindowRoot(Document* aDoc);
3090 * If there is a Referrer-Policy response header in |aChannel|, parse a
3091 * referrer policy from the header.
3093 * @param the channel from which to get the Referrer-Policy header
3094 * @return referrer policy from the response header in aChannel
3096 static mozilla::dom::ReferrerPolicy GetReferrerPolicyFromChannel(
3097 nsIChannel* aChannel);
3099 static bool IsNonSubresourceRequest(nsIChannel* aChannel);
3101 static bool IsNonSubresourceInternalPolicyType(nsContentPolicyType aType);
3103 public:
3105 * Returns true if this window's channel has been marked as a third-party
3106 * tracking resource.
3108 static bool IsThirdPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
3111 * Returns true if this window's channel has been marked as a first-party
3112 * tracking resource.
3114 static bool IsFirstPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
3117 * Serializes a HTML nsINode into its markup representation.
3119 static bool SerializeNodeToMarkup(nsINode* aRoot, bool aDescendentsOnly,
3120 nsAString& aOut);
3123 * Returns true iff the provided JSObject is a global, and its URI matches
3124 * the provided about: URI.
3125 * @param aGlobal the JSObject whose URI to check, if it is a global.
3126 * @param aUri the URI to match, e.g. "about:feeds"
3128 static bool IsSpecificAboutPage(JSObject* aGlobal, const char* aUri);
3130 static void SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible);
3133 * Try to find the docshell corresponding to the given event target.
3135 static nsIDocShell* GetDocShellForEventTarget(
3136 mozilla::dom::EventTarget* aTarget);
3139 * Returns true if the "HTTPS state" of the document should be "modern". See:
3141 * https://html.spec.whatwg.org/#concept-document-https-state
3142 * https://fetch.spec.whatwg.org/#concept-response-https-state
3144 static bool HttpsStateIsModern(Document* aDocument);
3147 * Returns true if the channel is for top-level window and is over secure
3148 * context.
3149 * https://github.com/whatwg/html/issues/4930 tracks the spec side of this.
3151 static bool ComputeIsSecureContext(nsIChannel* aChannel);
3154 * Try to upgrade an element.
3155 * https://html.spec.whatwg.org/multipage/custom-elements.html#concept-try-upgrade
3157 static void TryToUpgradeElement(Element* aElement);
3160 * Creates a new XUL or XHTML element applying any appropriate custom element
3161 * definition.
3163 * If aFromParser != FROM_PARSER_FRAGMENT, a nested event loop permits
3164 * arbitrary changes to the world before this function returns. This should
3165 * probably just be MOZ_CAN_RUN_SCRIPT - bug 1543259.
3167 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult NewXULOrHTMLElement(
3168 Element** aResult, mozilla::dom::NodeInfo* aNodeInfo,
3169 mozilla::dom::FromParser aFromParser, nsAtom* aIsAtom,
3170 mozilla::dom::CustomElementDefinition* aDefinition);
3172 static mozilla::dom::CustomElementRegistry* GetCustomElementRegistry(
3173 Document*);
3176 * Looking up a custom element definition.
3177 * https://html.spec.whatwg.org/#look-up-a-custom-element-definition
3179 static mozilla::dom::CustomElementDefinition* LookupCustomElementDefinition(
3180 Document* aDoc, nsAtom* aNameAtom, uint32_t aNameSpaceID,
3181 nsAtom* aTypeAtom);
3183 static void RegisterCallbackUpgradeElement(Element* aElement,
3184 nsAtom* aTypeName);
3186 static void RegisterUnresolvedElement(Element* aElement, nsAtom* aTypeName);
3187 static void UnregisterUnresolvedElement(Element* aElement);
3189 static void EnqueueUpgradeReaction(
3190 Element* aElement, mozilla::dom::CustomElementDefinition* aDefinition);
3192 static void EnqueueLifecycleCallback(
3193 mozilla::dom::ElementCallbackType aType, Element* aCustomElement,
3194 const mozilla::dom::LifecycleCallbackArgs& aArgs,
3195 mozilla::dom::CustomElementDefinition* aDefinition = nullptr);
3197 static mozilla::dom::CustomElementFormValue ConvertToCustomElementFormValue(
3198 const mozilla::dom::Nullable<
3199 mozilla::dom::OwningFileOrUSVStringOrFormData>& aState);
3201 static mozilla::dom::Nullable<mozilla::dom::OwningFileOrUSVStringOrFormData>
3202 ExtractFormAssociatedCustomElementValue(
3203 nsIGlobalObject* aGlobal,
3204 const mozilla::dom::CustomElementFormValue& aCEValue);
3207 * Appends all "document level" native anonymous content subtree roots for
3208 * aDocument to aElements. Document level NAC subtrees are those created
3209 * by ancestor frames of the document element's primary frame, such as
3210 * the scrollbar elements created by the root scroll frame.
3212 static void AppendDocumentLevelNativeAnonymousContentTo(
3213 Document* aDocument, nsTArray<nsIContent*>& aElements);
3216 * Appends all native anonymous content subtree roots generated by `aContent`
3217 * to `aKids`.
3219 * See `AllChildrenIterator` for the description of the `aFlags` parameter.
3221 static void AppendNativeAnonymousChildren(const nsIContent* aContent,
3222 nsTArray<nsIContent*>& aKids,
3223 uint32_t aFlags);
3226 * Query triggeringPrincipal if there's a 'triggeringprincipal' attribute on
3227 * aLoadingNode, if no such attribute is specified, aDefaultPrincipal is
3228 * returned if it is provided, otherwise the NodePrincipal of aLoadingNode is
3229 * returned.
3231 * Return true if aLoadingNode has a 'triggeringprincipal' attribute, and
3232 * the value 'triggeringprincipal' is also successfully deserialized,
3233 * otherwise return false.
3235 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3236 nsIPrincipal* aDefaultPrincipal,
3237 nsIPrincipal** aTriggeringPrincipal);
3239 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3240 nsIPrincipal** aTriggeringPrincipal) {
3241 return QueryTriggeringPrincipal(aLoadingNode, nullptr,
3242 aTriggeringPrincipal);
3245 // Returns whether the image for the given URI and triggering principal is
3246 // already available. Ideally this should exactly match the "list of available
3247 // images" in the HTML spec, but our implementation of that at best only
3248 // resembles it.
3249 static bool IsImageAvailable(nsIContent*, nsIURI*,
3250 nsIPrincipal* aDefaultTriggeringPrincipal,
3251 mozilla::CORSMode);
3252 static bool IsImageAvailable(nsIURI*, nsIPrincipal* aTriggeringPrincipal,
3253 mozilla::CORSMode, Document*);
3256 * Returns the content policy type that should be used for loading images
3257 * for displaying in the UI. The sources of such images can be <xul:image>,
3258 * <xul:menuitem> on OSX where we load the image through nsMenuItemIconX, etc.
3260 static void GetContentPolicyTypeForUIImageLoading(
3261 nsIContent* aLoadingNode, nsIPrincipal** aTriggeringPrincipal,
3262 nsContentPolicyType& aContentPolicyType, uint64_t* aRequestContextID);
3264 static nsresult CreateJSValueFromSequenceOfObject(
3265 JSContext* aCx, const mozilla::dom::Sequence<JSObject*>& aTransfer,
3266 JS::MutableHandle<JS::Value> aValue);
3269 * This implements the structured cloning algorithm as described by
3270 * https://html.spec.whatwg.org/#structured-cloning.
3272 static void StructuredClone(
3273 JSContext* aCx, nsIGlobalObject* aGlobal, JS::Handle<JS::Value> aValue,
3274 const mozilla::dom::StructuredSerializeOptions& aOptions,
3275 JS::MutableHandle<JS::Value> aRetval, mozilla::ErrorResult& aError);
3278 * Returns true if reserved key events should be prevented from being sent
3279 * to their target. Instead, the key event should be handled by chrome only.
3281 static bool ShouldBlockReservedKeys(mozilla::WidgetKeyboardEvent* aKeyEvent);
3284 * Returns one of the nsIObjectLoadingContent::TYPE_ values describing the
3285 * content type which will be used for the given MIME type when loaded within
3286 * an nsObjectLoadingContent.
3288 * NOTE: This method doesn't take capabilities into account. The caller must
3289 * take that into account.
3291 * @param aMIMEType The MIME type of the document being loaded.
3293 static uint32_t HtmlObjectContentTypeForMIMEType(const nsCString& aMIMEType);
3296 * Detect whether a string is a local-url.
3297 * https://drafts.csswg.org/css-values/#local-urls
3299 static bool IsLocalRefURL(const nsAString& aString);
3302 * Compose a tab id with process id and a serial number.
3304 static uint64_t GenerateTabId();
3307 * Compose a browser id with process id and a serial number.
3309 static uint64_t GenerateBrowserId();
3312 * Generate an id for a BrowsingContext using a range of serial
3313 * numbers reserved for the current process.
3315 static uint64_t GenerateBrowsingContextId();
3318 * Generate an id using a range of serial numbers reserved for the current
3319 * process. aId should be a counter that's incremented every time
3320 * GenerateProcessSpecificId is called.
3322 static uint64_t GenerateProcessSpecificId(uint64_t aId);
3324 static std::tuple<uint64_t, uint64_t> SplitProcessSpecificId(uint64_t aId);
3327 * Generate a window ID which is unique across processes and will never be
3328 * recycled.
3330 static uint64_t GenerateWindowId();
3333 * Generate an ID for a load which is unique across processes and will never
3334 * be recycled.
3336 static uint64_t GenerateLoadIdentifier();
3339 * Determine whether or not the user is currently interacting with the web
3340 * browser. This method is safe to call from off of the main thread.
3342 static bool GetUserIsInteracting();
3344 // Alternate data MIME type used by the ScriptLoader to register and read
3345 // bytecode out of the nsCacheInfoChannel.
3346 [[nodiscard]] static bool InitJSBytecodeMimeType();
3347 static nsCString& JSScriptBytecodeMimeType() {
3348 MOZ_ASSERT(sJSScriptBytecodeMimeType);
3349 return *sJSScriptBytecodeMimeType;
3351 static nsCString& JSModuleBytecodeMimeType() {
3352 MOZ_ASSERT(sJSModuleBytecodeMimeType);
3353 return *sJSModuleBytecodeMimeType;
3357 * Checks if the passed-in name is one of the special names: "_blank", "_top",
3358 * "_parent" or "_self".
3360 static bool IsSpecialName(const nsAString& aName);
3363 * Checks if the passed-in name should override an existing name on the
3364 * window. Values which should not override include: "", "_blank", "_top",
3365 * "_parent" and "_self".
3367 static bool IsOverridingWindowName(const nsAString& aName);
3370 * If there is a SourceMap (higher precedence) or X-SourceMap (lower
3371 * precedence) response header in |aChannel|, set |aResult| to the
3372 * header's value and return true. Otherwise, return false.
3374 * @param aChannel The HTTP channel
3375 * @param aResult The string result.
3377 static bool GetSourceMapURL(nsIHttpChannel* aChannel, nsACString& aResult);
3380 * Returns true if the passed-in mesasge is a pending InputEvent.
3382 * @param aMsg The message to check
3384 static bool IsMessageInputEvent(const IPC::Message& aMsg);
3387 * Returns true if the passed-in message is a critical InputEvent.
3389 * @param aMsg The message to check
3391 static bool IsMessageCriticalInputEvent(const IPC::Message& aMsg);
3393 static void AsyncPrecreateStringBundles();
3395 static bool ContentIsLink(nsIContent* aContent);
3397 static already_AddRefed<mozilla::dom::ContentFrameMessageManager>
3398 TryGetBrowserChildGlobal(nsISupports* aFrom);
3400 // Get a serial number for a newly created inner or outer window.
3401 static uint32_t InnerOrOuterWindowCreated();
3402 // Record that an inner or outer window has been destroyed.
3403 static void InnerOrOuterWindowDestroyed();
3404 // Get the current number of inner or outer windows.
3405 static int32_t GetCurrentInnerOrOuterWindowCount() {
3406 return sInnerOrOuterWindowCount;
3409 // Return an anonymized URI so that it can be safely exposed publicly.
3410 static nsresult AnonymizeURI(nsIURI* aURI, nsCString& aAnonymizedURI);
3413 * Serializes a JSON-like JS::Value into a string.
3414 * Cases where JSON.stringify would return undefined are handled according to
3415 * the |aBehavior| argument:
3417 * - If it is |UndefinedIsNullStringLiteral|, the string "null" is returned.
3418 * - If it is |UndefinedIsVoidString|, the void string is returned.
3420 * The |UndefinedIsNullStringLiteral| case is likely not desirable, but is
3421 * retained for now for historical reasons.
3422 * Usage:
3423 * nsAutoString serializedValue;
3424 * nsContentUtils::StringifyJSON(cx, value, serializedValue, behavior);
3426 static bool StringifyJSON(JSContext* aCx, JS::Handle<JS::Value> aValue,
3427 nsAString& aOutStr, JSONBehavior aBehavior);
3430 * Returns true if the top level ancestor content document of aDocument hasn't
3431 * yet had the first contentful paint and there is a high priority event
3432 * pending in the main thread.
3434 static bool HighPriorityEventPendingForTopLevelDocumentBeforeContentfulPaint(
3435 Document* aDocument);
3438 * Get the inner window corresponding to the incumbent global, including
3439 * mapping extension content script globals to the attached window.
3441 * Returns null if the incumbent global doesn't correspond to an inner window.
3443 static nsGlobalWindowInner* IncumbentInnerWindow();
3446 * Get the inner window corresponding to the entry global, including mapping
3447 * extension content script globals to the attached window.
3449 * Returns null if the entry global doesn't correspond to an inner window.
3451 static nsGlobalWindowInner* EntryInnerWindow();
3454 * Return safe area insets of window that defines as
3455 * https://drafts.csswg.org/css-env-1/#safe-area-insets.
3457 static mozilla::ScreenIntMargin GetWindowSafeAreaInsets(
3458 nsIScreen* aScreen, const mozilla::ScreenIntMargin& aSafeareaInsets,
3459 const mozilla::LayoutDeviceIntRect& aWindowRect);
3461 struct SubresourceCacheValidationInfo {
3462 // The expiration time, in seconds, if known.
3463 mozilla::Maybe<uint32_t> mExpirationTime;
3464 bool mMustRevalidate = false;
3468 * Gets cache validation info for subresources such as images or CSS
3469 * stylesheets.
3471 static SubresourceCacheValidationInfo GetSubresourceCacheValidationInfo(
3472 nsIRequest*, nsIURI*);
3474 static uint32_t SecondsFromPRTime(PRTime aTime) {
3475 return uint32_t(int64_t(aTime) / int64_t(PR_USEC_PER_SEC));
3479 * Converts the given URL to a string and truncates it to the given length.
3481 * Returns an empty string if aURL is null.
3483 static nsCString TruncatedURLForDisplay(nsIURI* aURL, size_t aMaxLen = 128);
3486 * Anonymize the given id by hashing it with the provided origin. The
3487 * resulting id will have the same length as the one that was passed in.
3489 enum class OriginFormat {
3490 Base64,
3491 Plain,
3494 static nsresult AnonymizeId(nsAString& aId, const nsACString& aOriginKey,
3495 OriginFormat aFormat = OriginFormat::Base64);
3498 * Create and load the string bundle for the 'aFile'.
3499 * This API is used to preload the string bundle on the main thread so later
3500 * other thread could access it.
3502 static nsresult EnsureAndLoadStringBundle(PropertiesFile aFile);
3505 * The method asks nsIAppShell to prioritize Gecko's internal tasks over
3506 * the OS level tasks for a short period of time.
3508 static void RequestGeckoTaskBurst();
3510 static void SetMayHaveFormCheckboxStateChangeListeners() {
3511 sMayHaveFormCheckboxStateChangeListeners = true;
3514 static bool MayHaveFormCheckboxStateChangeListeners() {
3515 return sMayHaveFormCheckboxStateChangeListeners;
3518 static void SetMayHaveFormRadioStateChangeListeners() {
3519 sMayHaveFormRadioStateChangeListeners = true;
3522 static bool MayHaveFormRadioStateChangeListeners() {
3523 return sMayHaveFormRadioStateChangeListeners;
3527 * Returns the closest link element in the flat tree of aContent if there's
3528 * one, otherwise returns nullptr.
3530 static nsIContent* GetClosestLinkInFlatTree(nsIContent* aContent);
3532 static bool IsExternalProtocol(nsIURI* aURI);
3535 * Compares the position of aNode1 and aNode2 in the document
3536 * @param aNode1 First content to compare.
3537 * @param aNode2 Second content to compare.
3538 * @param aCommonAncestor Potential ancestor of the contents, if one exists.
3539 * This is only a hint; if it's not an ancestor of
3540 * aNode1 or aNode2, this function will still
3541 * work, but it will be slower.
3542 * @return < 0 if aNode1 is before aNode2,
3543 * > 0 if aNode1 is after aNode2,
3544 * 0 otherwise
3546 template <TreeKind>
3547 static int32_t CompareTreePosition(const nsINode* aNode1,
3548 const nsINode* aNode2,
3549 const nsINode* aCommonAncestor);
3551 MOZ_CAN_RUN_SCRIPT_BOUNDARY
3552 static nsIContent* AttachDeclarativeShadowRoot(
3553 nsIContent* aHost, mozilla::dom::ShadowRootMode aMode, bool aIsClonable,
3554 bool aDelegatesFocus);
3556 private:
3557 static bool InitializeEventTable();
3559 static nsresult EnsureStringBundle(PropertiesFile aFile);
3561 static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
3562 nsIPrincipal* aPrincipal);
3564 static nsresult WrapNative(JSContext* cx, nsISupports* native,
3565 nsWrapperCache* cache, const nsIID* aIID,
3566 JS::MutableHandle<JS::Value> vp,
3567 bool aAllowWrapping);
3569 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3570 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult DispatchEvent(
3571 Document* aDoc, mozilla::dom::EventTarget* aTarget,
3572 const nsAString& aEventName, CanBubble, Cancelable, Composed, Trusted,
3573 bool* aDefaultAction = nullptr,
3574 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3576 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3577 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult DispatchEvent(
3578 Document* aDoc, mozilla::dom::EventTarget* aTarget,
3579 mozilla::WidgetEvent& aWidgetEvent, EventMessage aEventMessage, CanBubble,
3580 Cancelable, Trusted, bool* aDefaultAction = nullptr,
3581 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3583 static void InitializeModifierStrings();
3585 static void DropFragmentParsers();
3587 static bool MatchClassNames(mozilla::dom::Element* aElement,
3588 int32_t aNamespaceID, nsAtom* aAtom, void* aData);
3589 static void DestroyClassNameArray(void* aData);
3590 static void* AllocClassMatchingInfo(nsINode* aRootNode,
3591 const nsString* aClasses);
3593 static mozilla::EventClassID GetEventClassIDFromMessage(
3594 EventMessage aEventMessage);
3596 // Fills in aInfo with the tokens from the supplied autocomplete attribute.
3597 static AutocompleteAttrState InternalSerializeAutocompleteAttribute(
3598 const nsAttrValue* aAttrVal, mozilla::dom::AutocompleteInfo& aInfo,
3599 bool aGrantAllValidValue = false);
3601 static mozilla::CallState CallOnAllRemoteChildren(
3602 mozilla::dom::MessageBroadcaster* aManager,
3603 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
3604 aCallback);
3606 static nsINode* GetCommonAncestorHelper(nsINode* aNode1, nsINode* aNode2);
3607 static nsINode* GetCommonShadowIncludingAncestorHelper(nsINode* aNode1,
3608 nsINode* aNode2);
3609 static nsIContent* GetCommonFlattenedTreeAncestorHelper(
3610 nsIContent* aContent1, nsIContent* aContent2);
3612 static nsIXPConnect* sXPConnect;
3614 static nsIScriptSecurityManager* sSecurityManager;
3615 static nsIPrincipal* sSystemPrincipal;
3616 static nsIPrincipal* sNullSubjectPrincipal;
3618 static nsIConsoleService* sConsoleService;
3620 static nsIStringBundleService* sStringBundleService;
3621 class nsContentUtilsReporter;
3623 static nsIContentPolicy* sContentPolicyService;
3624 static bool sTriedToGetContentPolicy;
3626 static mozilla::StaticRefPtr<nsIBidiKeyboard> sBidiKeyboard;
3628 static bool sInitialized;
3629 static uint32_t sScriptBlockerCount;
3630 static uint32_t sDOMNodeRemovedSuppressCount;
3632 // Not an nsCOMArray because removing elements from those is slower
3633 static AutoTArray<nsCOMPtr<nsIRunnable>, 8>* sBlockedScriptRunners;
3634 static uint32_t sRunnersCountAtFirstBlocker;
3635 static uint32_t sScriptBlockerCountWhereRunnersPrevented;
3637 static nsIInterfaceRequestor* sSameOriginChecker;
3639 static bool sIsHandlingKeyBoardEvent;
3640 #ifndef RELEASE_OR_BETA
3641 static bool sBypassCSSOMOriginCheck;
3642 #endif
3644 class UserInteractionObserver;
3645 static UserInteractionObserver* sUserInteractionObserver;
3647 static nsHtml5StringParser* sHTMLFragmentParser;
3648 static nsParser* sXMLFragmentParser;
3649 static nsIFragmentContentSink* sXMLFragmentSink;
3652 * True if there's a fragment parser activation on the stack.
3654 static bool sFragmentParsingActive;
3656 static nsString* sShiftText;
3657 static nsString* sControlText;
3658 static nsString* sCommandOrWinText;
3659 static nsString* sAltText;
3660 static nsString* sModifierSeparator;
3662 // Alternate data mime types, used by the ScriptLoader to register and read
3663 // the bytecode out of the nsCacheInfoChannel.
3664 static nsCString* sJSScriptBytecodeMimeType;
3665 static nsCString* sJSModuleBytecodeMimeType;
3667 static mozilla::LazyLogModule gResistFingerprintingLog;
3668 static mozilla::LazyLogModule sDOMDumpLog;
3670 static int32_t sInnerOrOuterWindowCount;
3671 static uint32_t sInnerOrOuterWindowSerialCounter;
3673 static bool sMayHaveFormCheckboxStateChangeListeners;
3674 static bool sMayHaveFormRadioStateChangeListeners;
3677 /* static */ inline ExtContentPolicyType
3678 nsContentUtils::InternalContentPolicyTypeToExternal(nsContentPolicyType aType) {
3679 switch (aType) {
3680 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
3681 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
3682 case nsIContentPolicy::TYPE_INTERNAL_MODULE:
3683 case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD:
3684 case nsIContentPolicy::TYPE_INTERNAL_WORKER:
3685 case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
3686 case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
3687 case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS:
3688 case nsIContentPolicy::TYPE_INTERNAL_WORKER_STATIC_MODULE:
3689 case nsIContentPolicy::TYPE_INTERNAL_AUDIOWORKLET:
3690 case nsIContentPolicy::TYPE_INTERNAL_PAINTWORKLET:
3691 case nsIContentPolicy::TYPE_INTERNAL_CHROMEUTILS_COMPILED_SCRIPT:
3692 case nsIContentPolicy::TYPE_INTERNAL_FRAME_MESSAGEMANAGER_SCRIPT:
3693 return ExtContentPolicy::TYPE_SCRIPT;
3695 case nsIContentPolicy::TYPE_INTERNAL_EMBED:
3696 case nsIContentPolicy::TYPE_INTERNAL_OBJECT:
3697 return ExtContentPolicy::TYPE_OBJECT;
3699 case nsIContentPolicy::TYPE_INTERNAL_FRAME:
3700 case nsIContentPolicy::TYPE_INTERNAL_IFRAME:
3701 return ExtContentPolicy::TYPE_SUBDOCUMENT;
3703 case nsIContentPolicy::TYPE_INTERNAL_AUDIO:
3704 case nsIContentPolicy::TYPE_INTERNAL_VIDEO:
3705 case nsIContentPolicy::TYPE_INTERNAL_TRACK:
3706 return ExtContentPolicy::TYPE_MEDIA;
3708 case nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST:
3709 case nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE:
3710 return ExtContentPolicy::TYPE_XMLHTTPREQUEST;
3712 case nsIContentPolicy::TYPE_INTERNAL_IMAGE:
3713 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD:
3714 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON:
3715 return ExtContentPolicy::TYPE_IMAGE;
3717 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
3718 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
3719 return ExtContentPolicy::TYPE_STYLESHEET;
3721 case nsIContentPolicy::TYPE_INTERNAL_DTD:
3722 case nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD:
3723 return ExtContentPolicy::TYPE_DTD;
3725 case nsIContentPolicy::TYPE_INTERNAL_FONT_PRELOAD:
3726 return ExtContentPolicy::TYPE_FONT;
3728 case nsIContentPolicy::TYPE_INTERNAL_FETCH_PRELOAD:
3729 return ExtContentPolicy::TYPE_FETCH;
3731 case nsIContentPolicy::TYPE_INVALID:
3732 case nsIContentPolicy::TYPE_OTHER:
3733 case nsIContentPolicy::TYPE_SCRIPT:
3734 case nsIContentPolicy::TYPE_IMAGE:
3735 case nsIContentPolicy::TYPE_STYLESHEET:
3736 case nsIContentPolicy::TYPE_OBJECT:
3737 case nsIContentPolicy::TYPE_DOCUMENT:
3738 case nsIContentPolicy::TYPE_SUBDOCUMENT:
3739 case nsIContentPolicy::TYPE_PING:
3740 case nsIContentPolicy::TYPE_XMLHTTPREQUEST:
3741 case nsIContentPolicy::TYPE_OBJECT_SUBREQUEST:
3742 case nsIContentPolicy::TYPE_DTD:
3743 case nsIContentPolicy::TYPE_FONT:
3744 case nsIContentPolicy::TYPE_MEDIA:
3745 case nsIContentPolicy::TYPE_WEBSOCKET:
3746 case nsIContentPolicy::TYPE_CSP_REPORT:
3747 case nsIContentPolicy::TYPE_XSLT:
3748 case nsIContentPolicy::TYPE_BEACON:
3749 case nsIContentPolicy::TYPE_FETCH:
3750 case nsIContentPolicy::TYPE_IMAGESET:
3751 case nsIContentPolicy::TYPE_WEB_MANIFEST:
3752 case nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD:
3753 case nsIContentPolicy::TYPE_SPECULATIVE:
3754 case nsIContentPolicy::TYPE_UA_FONT:
3755 case nsIContentPolicy::TYPE_PROXIED_WEBRTC_MEDIA:
3756 case nsIContentPolicy::TYPE_WEB_IDENTITY:
3757 case nsIContentPolicy::TYPE_WEB_TRANSPORT:
3758 // NOTE: When adding something here make sure the enumerator is defined!
3759 return static_cast<ExtContentPolicyType>(aType);
3761 case nsIContentPolicy::TYPE_END:
3762 break;
3763 // Do not add default: so that compilers can catch the missing case.
3766 MOZ_ASSERT(false, "Unhandled nsContentPolicyType value");
3767 return ExtContentPolicy::TYPE_INVALID;
3770 namespace mozilla {
3771 std::ostream& operator<<(
3772 std::ostream& aOut,
3773 const mozilla::PreventDefaultResult aPreventDefaultResult);
3774 } // namespace mozilla
3776 class MOZ_RAII nsAutoScriptBlocker {
3777 public:
3778 explicit nsAutoScriptBlocker() { nsContentUtils::AddScriptBlocker(); }
3779 ~nsAutoScriptBlocker() { nsContentUtils::RemoveScriptBlocker(); }
3781 private:
3784 class MOZ_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved
3785 : public nsAutoScriptBlocker {
3786 public:
3787 nsAutoScriptBlockerSuppressNodeRemoved() {
3788 ++nsContentUtils::sDOMNodeRemovedSuppressCount;
3790 ~nsAutoScriptBlockerSuppressNodeRemoved() {
3791 --nsContentUtils::sDOMNodeRemovedSuppressCount;
3795 namespace mozilla::dom {
3797 class TreeOrderComparator {
3798 public:
3799 bool Equals(nsINode* aElem1, nsINode* aElem2) const {
3800 return aElem1 == aElem2;
3802 bool LessThan(nsINode* aElem1, nsINode* aElem2) const {
3803 return nsContentUtils::PositionIsBefore(aElem1, aElem2);
3807 } // namespace mozilla::dom
3809 #define NS_INTERFACE_MAP_ENTRY_TEAROFF(_interface, _allocator) \
3810 NS_INTERFACE_MAP_ENTRY_TEAROFF_AMBIGUOUS(_interface, _interface, _allocator)
3812 #define NS_INTERFACE_MAP_ENTRY_TEAROFF_AMBIGUOUS(_interface, _implClass, \
3813 _allocator) \
3814 if (aIID.Equals(NS_GET_IID(_interface))) { \
3815 foundInterface = static_cast<_implClass*>(_allocator); \
3816 if (!foundInterface) { \
3817 *aInstancePtr = nullptr; \
3818 return NS_ERROR_OUT_OF_MEMORY; \
3820 } else
3823 * In the following helper macros we exploit the fact that the result of a
3824 * series of additions will not be finite if any one of the operands in the
3825 * series is not finite.
3827 #define NS_ENSURE_FINITE(f, rv) \
3828 if (!std::isfinite(f)) { \
3829 return (rv); \
3832 #define NS_ENSURE_FINITE2(f1, f2, rv) \
3833 if (!std::isfinite((f1) + (f2))) { \
3834 return (rv); \
3837 #define NS_ENSURE_FINITE4(f1, f2, f3, f4, rv) \
3838 if (!std::isfinite((f1) + (f2) + (f3) + (f4))) { \
3839 return (rv); \
3842 #define NS_ENSURE_FINITE5(f1, f2, f3, f4, f5, rv) \
3843 if (!std::isfinite((f1) + (f2) + (f3) + (f4) + (f5))) { \
3844 return (rv); \
3847 #define NS_ENSURE_FINITE6(f1, f2, f3, f4, f5, f6, rv) \
3848 if (!std::isfinite((f1) + (f2) + (f3) + (f4) + (f5) + (f6))) { \
3849 return (rv); \
3852 // Deletes a linked list iteratively to avoid blowing up the stack (bug 460444).
3853 #define NS_CONTENT_DELETE_LIST_MEMBER(type_, ptr_, member_) \
3855 type_* cur = (ptr_)->member_; \
3856 (ptr_)->member_ = nullptr; \
3857 while (cur) { \
3858 type_* next = cur->member_; \
3859 cur->member_ = nullptr; \
3860 delete cur; \
3861 cur = next; \
3865 #endif /* nsContentUtils_h___ */