Backed out 9 changesets (bug 1846848) for causing multiple build bustages. CLOSED...
[gecko.git] / dom / base / nsContentUtils.h
blob3aca84f01071f134856abb19ad3e610a67fe5016
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/fallible.h"
43 #include "mozilla/gfx/Point.h"
44 #include "nsCOMPtr.h"
45 #include "nsIContentPolicy.h"
46 #include "nsINode.h"
47 #include "nsIScriptError.h"
48 #include "nsIThread.h"
49 #include "nsLiteralString.h"
50 #include "nsMargin.h"
51 #include "nsPIDOMWindow.h"
52 #include "nsRFPService.h"
53 #include "nsStringFwd.h"
54 #include "nsTArray.h"
55 #include "nsTLiteralString.h"
56 #include "prtime.h"
58 #if defined(XP_WIN)
59 // Undefine LoadImage to prevent naming conflict with Windows.
60 # undef LoadImage
61 #endif
63 class JSObject;
64 class imgICache;
65 class imgIContainer;
66 class imgINotificationObserver;
67 class imgIRequest;
68 class imgLoader;
69 class imgRequestProxy;
70 class nsAtom;
71 class nsAttrValue;
72 class nsAutoScriptBlockerSuppressNodeRemoved;
73 class nsContentList;
74 class nsCycleCollectionTraversalCallback;
75 class nsDocShell;
76 class nsGlobalWindowInner;
77 class nsHtml5StringParser;
78 class nsIArray;
79 class nsIBidiKeyboard;
80 class nsIChannel;
81 class nsIConsoleService;
82 class nsIContent;
83 class nsIDocShell;
84 class nsIDocShellTreeItem;
85 class nsIDocumentLoaderFactory;
86 class nsIDragSession;
87 class nsIFile;
88 class nsIFragmentContentSink;
89 class nsIFrame;
90 class nsIHttpChannel;
91 class nsIIOService;
92 class nsIImageLoadingContent;
93 class nsIInterfaceRequestor;
94 class nsILoadGroup;
95 class nsILoadInfo;
96 class nsIObserver;
97 class nsIPrincipal;
98 class nsIReferrerInfo;
99 class nsIRequest;
100 class nsIRunnable;
101 class nsIScreen;
102 class nsIScriptContext;
103 class nsIScriptSecurityManager;
104 class nsISerialEventTarget;
105 class nsIStringBundle;
106 class nsIStringBundleService;
107 class nsISupports;
108 class nsITransferable;
109 class nsIURI;
110 class nsIWidget;
111 class nsIWritableVariant;
112 class nsIXPConnect;
113 class nsNodeInfoManager;
114 class nsParser;
115 class nsPIWindowRoot;
116 class nsPresContext;
117 class nsStringBuffer;
118 class nsTextFragment;
119 class nsView;
120 class nsWrapperCache;
122 struct JSContext;
123 struct nsPoint;
125 namespace IPC {
126 class Message;
127 class MessageReader;
128 class MessageWriter;
129 } // namespace IPC
131 namespace JS {
132 class Value;
133 class PropertyDescriptor;
134 } // namespace JS
136 namespace mozilla {
137 class Dispatcher;
138 class EditorBase;
139 class ErrorResult;
140 class EventListenerManager;
141 class HTMLEditor;
142 class LazyLogModule;
143 class LogModule;
144 class PresShell;
145 class TextEditor;
146 class WidgetDragEvent;
147 class WidgetKeyboardEvent;
149 struct InputEventOptions;
151 template <typename ParentType, typename RefType>
152 class RangeBoundaryBase;
154 template <typename T>
155 class NotNull;
156 template <class T>
157 class StaticRefPtr;
159 namespace dom {
160 class IPCImage;
161 struct AutocompleteInfo;
162 class BrowserChild;
163 class BrowserParent;
164 class BrowsingContext;
165 class BrowsingContextGroup;
166 class ContentChild;
167 class ContentFrameMessageManager;
168 class ContentParent;
169 struct CustomElementDefinition;
170 class CustomElementFormValue;
171 class CustomElementRegistry;
172 class DataTransfer;
173 class Document;
174 class DocumentFragment;
175 class DOMArena;
176 class Element;
177 class Event;
178 class EventTarget;
179 class HTMLElement;
180 class HTMLInputElement;
181 class IPCTransferable;
182 class IPCTransferableData;
183 class IPCTransferableDataImageContainer;
184 class IPCTransferableDataItem;
185 struct LifecycleCallbackArgs;
186 class MessageBroadcaster;
187 class NodeInfo;
188 class OwningFileOrUSVStringOrFormData;
189 class Selection;
190 struct StructuredSerializeOptions;
191 class WorkerPrivate;
192 enum class ElementCallbackType;
193 enum class ReferrerPolicy : uint8_t;
194 } // namespace dom
196 namespace ipc {
197 class BigBuffer;
198 class IProtocol;
199 } // namespace ipc
201 namespace gfx {
202 class DataSourceSurface;
203 enum class SurfaceFormat : int8_t;
204 } // namespace gfx
206 class WindowRenderer;
208 } // namespace mozilla
210 extern const char kLoadAsData[];
212 // Stolen from nsReadableUtils, but that's OK, since we can declare the same
213 // name multiple times.
214 const nsString& EmptyString();
215 const nsCString& EmptyCString();
217 enum EventNameType {
218 EventNameType_None = 0x0000,
219 EventNameType_HTML = 0x0001,
220 EventNameType_XUL = 0x0002,
221 EventNameType_SVGGraphic = 0x0004, // svg graphic elements
222 EventNameType_SVGSVG = 0x0008, // the svg element
223 EventNameType_SMIL = 0x0010, // smil elements
224 EventNameType_HTMLBodyOrFramesetOnly = 0x0020,
225 EventNameType_HTMLMarqueeOnly = 0x0040,
227 EventNameType_HTMLXUL = 0x0003,
228 EventNameType_All = 0xFFFF
231 struct EventNameMapping {
232 // This holds pointers to nsGkAtoms members, and is therefore safe as a
233 // non-owning reference.
234 nsAtom* MOZ_NON_OWNING_REF mAtom;
235 int32_t mType;
236 mozilla::EventMessage mMessage;
237 mozilla::EventClassID mEventClassID;
240 namespace mozilla {
241 enum class PreventDefaultResult : uint8_t { No, ByContent, ByChrome };
243 namespace dom {
244 enum JSONBehavior { UndefinedIsNullStringLiteral, UndefinedIsVoidString };
246 } // namespace mozilla
248 class nsContentUtils {
249 friend class nsAutoScriptBlockerSuppressNodeRemoved;
250 using Element = mozilla::dom::Element;
251 using Document = mozilla::dom::Document;
252 using Cancelable = mozilla::Cancelable;
253 using CanBubble = mozilla::CanBubble;
254 using Composed = mozilla::Composed;
255 using ChromeOnlyDispatch = mozilla::ChromeOnlyDispatch;
256 using EventMessage = mozilla::EventMessage;
257 using TimeDuration = mozilla::TimeDuration;
258 using Trusted = mozilla::Trusted;
259 using JSONBehavior = mozilla::dom::JSONBehavior;
260 using RFPTarget = mozilla::RFPTarget;
262 public:
263 static nsresult Init();
265 static bool IsCallerChrome();
266 static bool ThreadsafeIsCallerChrome();
267 static bool IsCallerUAWidget();
268 static bool IsFuzzingEnabled()
269 #ifndef FUZZING
271 return false;
273 #else
275 #endif
276 static bool IsErrorPage(nsIURI* aURI);
278 static bool IsCallerChromeOrFuzzingEnabled(JSContext* aCx, JSObject*) {
279 return ThreadsafeIsSystemCaller(aCx) || IsFuzzingEnabled();
282 static bool IsCallerChromeOrElementTransformGettersEnabled(JSContext* aCx,
283 JSObject*);
285 // The APIs for checking whether the caller is system (in the sense of system
286 // principal) should only be used when the JSContext is known to accurately
287 // represent the caller. In practice, that means you should only use them in
288 // two situations at the moment:
290 // 1) Functions used in WebIDL Func annotations.
291 // 2) Bindings code or other code called directly from the JS engine.
293 // Use pretty much anywhere else is almost certainly wrong and should be
294 // replaced with [NeedsCallerType] annotations in bindings.
296 // Check whether the caller is system if you know you're on the main thread.
297 static bool IsSystemCaller(JSContext* aCx);
299 // Check whether the caller is system if you might be on a worker or worklet
300 // thread.
301 static bool ThreadsafeIsSystemCaller(JSContext* aCx);
303 // In the traditional Gecko architecture, both C++ code and untrusted JS code
304 // needed to rely on the same XPCOM method/getter/setter to get work done.
305 // This required lots of security checks in the various exposed methods, which
306 // in turn created difficulty in determining whether the caller was script
307 // (whose access needed to be checked) and internal C++ platform code (whose
308 // access did not need to be checked). To address this problem, Gecko had a
309 // convention whereby the absence of script on the stack was interpretted as
310 // "System Caller" and always granted unfettered access.
312 // Unfortunately, this created a bunch of footguns. For example, when the
313 // implementation of a DOM method wanted to perform a privileged
314 // sub-operation, it needed to "hide" the presence of script on the stack in
315 // order for that sub-operation to be allowed. Additionally, if script could
316 // trigger an API entry point to be invoked in some asynchronous way without
317 // script on the stack, it could potentially perform privilege escalation.
319 // In the modern world, untrusted script should interact with the platform
320 // exclusively over WebIDL APIs, and platform code has a lot more flexibility
321 // in deciding whether or not to use XPCOM. This gives us the flexibility to
322 // do something better.
324 // Going forward, APIs should be designed such that any security checks that
325 // ask the question "is my caller allowed to do this?" should live in WebIDL
326 // API entry points, with a separate method provided for internal callers
327 // that just want to get the job done.
329 // To enforce this and catch bugs, nsContentUtils::SubjectPrincipal will crash
330 // if it is invoked without script on the stack. To land that transition, it
331 // was necessary to go through and whitelist a bunch of callers that were
332 // depending on the old behavior. Those callers should be fixed up, and these
333 // methods should not be used by new code without review from bholley or bz.
334 static bool LegacyIsCallerNativeCode() { return !GetCurrentJSContext(); }
335 static bool LegacyIsCallerChromeOrNativeCode() {
336 return LegacyIsCallerNativeCode() || IsCallerChrome();
338 static nsIPrincipal* SubjectPrincipalOrSystemIfNativeCaller() {
339 if (!GetCurrentJSContext()) {
340 return GetSystemPrincipal();
342 return SubjectPrincipal();
345 static bool LookupBindingMember(
346 JSContext* aCx, nsIContent* aContent, JS::Handle<jsid> aId,
347 JS::MutableHandle<JS::PropertyDescriptor> aDesc);
349 // Check whether we should avoid leaking distinguishing information to JS/CSS.
350 // This function can be called both in the main thread and worker threads.
351 static bool ShouldResistFingerprinting(RFPTarget aTarget);
352 static bool ShouldResistFingerprinting(nsIGlobalObject* aGlobalObject,
353 RFPTarget aTarget);
354 // Similar to the function above, but always allows CallerType::System
355 // callers.
356 static bool ShouldResistFingerprinting(mozilla::dom::CallerType aCallerType,
357 nsIGlobalObject* aGlobalObject,
358 RFPTarget aTarget);
359 static bool ShouldResistFingerprinting(nsIDocShell* aDocShell,
360 RFPTarget aTarget);
361 // These functions are the new, nuanced functions
362 static bool ShouldResistFingerprinting(nsIChannel* aChannel,
363 RFPTarget aTarget);
364 // These functions are labeled as dangerous because they will do the wrong
365 // thing in _most_ cases. They should only be used if you don't have a fully
366 // constructed LoadInfo or Document.
367 // A constant string used as justification is required when calling them,
368 // it should explain why a Document, Channel, LoadInfo, or CookieJarSettings
369 // does not exist in this context.
370 // (see below for more on justification strings.)
371 static bool ShouldResistFingerprinting_dangerous(
372 nsIURI* aURI, const mozilla::OriginAttributes& aOriginAttributes,
373 const char* aJustification, RFPTarget aTarget);
374 static bool ShouldResistFingerprinting_dangerous(nsIPrincipal* aPrincipal,
375 const char* aJustification,
376 RFPTarget aTarget);
379 * Implement a RFP function that only checks the pref, and does not take
380 * into account any additional context such as PBM mode or Web Extensions.
382 * It requires an explanation for why the coarse check is being used instead
383 * of the nuanced check. While there is a gradual cut over of
384 * ShouldResistFingerprinting calls to a nuanced API, some features still
385 * require a legacy function. (Additionally, we sometimes use the coarse
386 * check first, to avoid running additional code to support a nuanced check.)
388 static bool ShouldResistFingerprinting(const char* aJustification,
389 RFPTarget aTarget);
391 // A helper function to calculate the rounded window size for fingerprinting
392 // resistance. The rounded size is based on the chrome UI size and available
393 // screen size. If the inputWidth/Height is greater than the available content
394 // size, this will report the available content size. Otherwise, it will
395 // round the size to the nearest upper 200x100.
396 static void CalcRoundedWindowSizeForResistingFingerprinting(
397 int32_t aChromeWidth, int32_t aChromeHeight, int32_t aScreenWidth,
398 int32_t aScreenHeight, int32_t aInputWidth, int32_t aInputHeight,
399 bool aSetOuterWidth, bool aSetOuterHeight, int32_t* aOutputWidth,
400 int32_t* aOutputHeight);
403 * Returns the parent node of aChild crossing document boundaries, but skips
404 * any cross-process parent frames and continues with the nearest in-process
405 * frame in the hierarchy.
407 * Uses the parent node in the composed document.
409 static nsINode* GetNearestInProcessCrossDocParentNode(nsINode* aChild);
412 * Similar to nsINode::IsInclusiveDescendantOf, except will treat an
413 * HTMLTemplateElement or ShadowRoot as an ancestor of things in the
414 * corresponding DocumentFragment. See the concept of "host-including
415 * inclusive ancestor" in the DOM specification.
417 static bool ContentIsHostIncludingDescendantOf(
418 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
421 * Similar to nsINode::IsInclusiveDescendantOf except it crosses document
422 * boundaries, this function uses ancestor/descendant relations in the
423 * composed document (see shadow DOM spec).
425 static bool ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant,
426 nsINode* aPossibleAncestor);
429 * As with ContentIsCrossDocDescendantOf but crosses shadow boundaries but not
430 * cross document boundaries.
432 * @see nsINode::GetFlattenedTreeParentNode()
434 static bool ContentIsFlattenedTreeDescendantOf(
435 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
438 * Same as `ContentIsFlattenedTreeDescendantOf`, but from the flattened tree
439 * point of view of the style system
441 * @see nsINode::GetFlattenedTreeParentNodeForStyle()
443 static bool ContentIsFlattenedTreeDescendantOfForStyle(
444 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
447 * Retarget an object A against an object B
448 * @see https://dom.spec.whatwg.org/#retarget
450 static nsINode* Retarget(nsINode* aTargetA, nsINode* aTargetB);
453 * @see https://wicg.github.io/element-timing/#get-an-element
455 static Element* GetAnElementForTiming(Element* aTarget,
456 const Document* aDocument,
457 nsIGlobalObject* aGlobal);
460 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
462 * This method fills the |aArray| with all ancestor nodes of |aNode|
463 * including |aNode| at the zero index.
466 static nsresult GetInclusiveAncestors(nsINode* aNode,
467 nsTArray<nsINode*>& aArray);
470 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
472 * This method fills |aAncestorNodes| with all ancestor nodes of |aNode|
473 * including |aNode| (QI'd to nsIContent) at the zero index.
474 * For each ancestor, there is a corresponding element in |aAncestorOffsets|
475 * which is the ComputeIndexOf the child in relation to its parent.
477 * This method just sucks.
479 static nsresult GetInclusiveAncestorsAndOffsets(
480 nsINode* aNode, uint32_t aOffset, nsTArray<nsIContent*>* aAncestorNodes,
481 nsTArray<mozilla::Maybe<uint32_t>>* aAncestorOffsets);
484 * Returns the closest common inclusive ancestor
485 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) , if any,
486 * for two nodes.
488 * Returns null if the nodes are disconnected.
490 static nsINode* GetClosestCommonInclusiveAncestor(nsINode* aNode1,
491 nsINode* aNode2) {
492 if (aNode1 == aNode2) {
493 return aNode1;
496 return GetCommonAncestorHelper(aNode1, aNode2);
500 * Returns the common flattened tree ancestor, if any, for two given content
501 * nodes.
503 static nsIContent* GetCommonFlattenedTreeAncestor(nsIContent* aContent1,
504 nsIContent* aContent2) {
505 if (aContent1 == aContent2) {
506 return aContent1;
509 return GetCommonFlattenedTreeAncestorHelper(aContent1, aContent2);
513 * Returns the common flattened tree ancestor from the point of view of the
514 * style system, if any, for two given content nodes.
516 static Element* GetCommonFlattenedTreeAncestorForStyle(Element* aElement1,
517 Element* aElement2);
520 * Returns the common BrowserParent ancestor, if any, for two given
521 * BrowserParent.
523 static mozilla::dom::BrowserParent* GetCommonBrowserParentAncestor(
524 mozilla::dom::BrowserParent* aBrowserParent1,
525 mozilla::dom::BrowserParent* aBrowserParent2);
527 // https://html.spec.whatwg.org/#target-element
528 // https://html.spec.whatwg.org/#find-a-potential-indicated-element
529 static Element* GetTargetElement(Document* aDocument,
530 const nsAString& aAnchorName);
532 * Returns true if aNode1 is before aNode2 in the same connected
533 * tree.
534 * aNode1Index and aNode2Index are in/out arguments. If non-null, and value is
535 * Some, that value is used instead of calling slow ComputeIndexOf on the
536 * parent node. If value is Nothing, the value will be set to the return value
537 * of ComputeIndexOf.
539 static bool PositionIsBefore(nsINode* aNode1, nsINode* aNode2,
540 mozilla::Maybe<uint32_t>* aNode1Index = nullptr,
541 mozilla::Maybe<uint32_t>* aNode2Index = nullptr);
543 struct ComparePointsCache {
544 mozilla::Maybe<uint32_t> ComputeIndexOf(const nsINode* aParent,
545 const nsINode* aChild) {
546 if (aParent == mParent && aChild == mChild) {
547 return mIndex;
550 mIndex = aParent->ComputeIndexOf(aChild);
551 mParent = aParent;
552 mChild = aChild;
553 return mIndex;
556 private:
557 const nsINode* mParent = nullptr;
558 const nsINode* mChild = nullptr;
559 mozilla::Maybe<uint32_t> mIndex;
563 * Utility routine to compare two "points", where a point is a node/offset
564 * pair.
565 * Pass a cache object as aParent1Cache if you expect to repeatedly
566 * call this function with the same value as aParent1.
568 * @return -1 if point1 < point2,
569 * 1 if point1 > point2,
570 * 0 if point1 == point2.
571 * `Nothing` if the two nodes aren't in the same connected subtree.
573 static mozilla::Maybe<int32_t> ComparePoints(
574 const nsINode* aParent1, uint32_t aOffset1, const nsINode* aParent2,
575 uint32_t aOffset2, ComparePointsCache* aParent1Cache = nullptr);
576 template <typename FPT, typename FRT, typename SPT, typename SRT>
577 static mozilla::Maybe<int32_t> ComparePoints(
578 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
579 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary);
582 * Utility routine to compare two "points", where a point is a
583 * node/offset pair
584 * Returns -1 if point1 < point2, 1, if point1 > point2,
585 * 0 if error or if point1 == point2.
586 * NOTE! If the two nodes aren't in the same connected subtree,
587 * the result is 1, and the optional aDisconnected parameter
588 * is set to true.
590 * Pass a cache object as aParent1Cache if you expect to repeatedly
591 * call this function with the same value as aParent1.
593 static int32_t ComparePoints_Deprecated(
594 const nsINode* aParent1, uint32_t aOffset1, const nsINode* aParent2,
595 uint32_t aOffset2, bool* aDisconnected = nullptr,
596 ComparePointsCache* aParent1Cache = nullptr);
597 template <typename FPT, typename FRT, typename SPT, typename SRT>
598 static int32_t ComparePoints_Deprecated(
599 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
600 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary,
601 bool* aDisconnected = nullptr);
604 * DO NOT USE this method for comparing the points in new code. this method
605 * emulates same result as `ComparePoints` before bug 1741148.
606 * When the old `ComparePoints` was called with offset value over `INT32_MAX`
607 * or `-1` which is used as "not found" by some API, they were treated as-is
608 * without checking whether the negative value or valid value. Thus, this
609 * handles the negative offset cases in the special paths to keep the
610 * traditional behavior. If you want to use this in new code, it means that
611 * you **should** check the offset values and call `ComparePoints` instead.
613 static mozilla::Maybe<int32_t> ComparePoints_AllowNegativeOffsets(
614 const nsINode* aParent1, int64_t aOffset1, const nsINode* aParent2,
615 int64_t aOffset2) {
616 if (MOZ_UNLIKELY(aOffset1 < 0 || aOffset2 < 0)) {
617 // If in same container, just the offset is compared.
618 if (aParent1 == aParent2) {
619 const int32_t compOffsets =
620 aOffset1 == aOffset2 ? 0 : (aOffset1 < aOffset2 ? -1 : 1);
621 return mozilla::Some(compOffsets);
623 // Otherwise, aOffset1 is referred only when aParent2 is a descendant of
624 // aParent1.
625 if (aOffset1 < 0 && aParent2->IsInclusiveDescendantOf(aParent1)) {
626 return mozilla::Some(-1);
628 // And also aOffset2 is referred only when aParent1 is a descendant of
629 // aParent2.
630 if (aOffset2 < 0 && aParent1->IsInclusiveDescendantOf(aParent2)) {
631 return mozilla::Some(1);
633 // Otherwise, aOffset1 nor aOffset2 is referred so that any value is fine
634 // if negative.
635 return ComparePoints(
636 aParent1, aOffset1 < 0 ? UINT32_MAX : static_cast<uint32_t>(aOffset1),
637 aParent2,
638 aOffset2 < 0 ? UINT32_MAX : static_cast<uint32_t>(aOffset2));
640 return ComparePoints(aParent1, aOffset1, aParent2, aOffset2);
644 * Brute-force search of the element subtree rooted at aContent for
645 * an element with the given id. aId must be nonempty, otherwise
646 * this method may return nodes even if they have no id!
648 static Element* MatchElementId(nsIContent* aContent, const nsAString& aId);
651 * Similar to above, but to be used if one already has an atom for the ID
653 static Element* MatchElementId(nsIContent* aContent, const nsAtom* aId);
656 * Reverses the document position flags passed in.
658 * @param aDocumentPosition The document position flags to be reversed.
660 * @return The reversed document position flags.
662 * @see Node
664 static uint16_t ReverseDocumentPosition(uint16_t aDocumentPosition);
666 static const nsDependentSubstring TrimCharsInSet(const char* aSet,
667 const nsAString& aValue);
669 template <bool IsWhitespace(char16_t)>
670 static const nsDependentSubstring TrimWhitespace(const nsAString& aStr,
671 bool aTrimTrailing = true);
674 * Returns true if aChar is of class Ps, Pi, Po, Pf, or Pe.
676 static bool IsFirstLetterPunctuation(uint32_t aChar);
679 * Returns true if aChar is of class Lu, Ll, Lt, Lm, Lo, Nd, Nl or No
681 static bool IsAlphanumeric(uint32_t aChar);
683 * Returns true if aChar is of class L*, N* or S* (for first-letter).
685 static bool IsAlphanumericOrSymbol(uint32_t aChar);
688 * Is the character an HTML whitespace character?
690 * We define whitespace using the list in HTML5 and css3-selectors:
691 * U+0009, U+000A, U+000C, U+000D, U+0020
693 * HTML 4.01 also lists U+200B (zero-width space).
695 static bool IsHTMLWhitespace(char16_t aChar);
698 * Returns whether the character is an HTML whitespace (see IsHTMLWhitespace)
699 * or a nbsp character (U+00A0).
701 static bool IsHTMLWhitespaceOrNBSP(char16_t aChar);
704 * https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
706 static bool IsHTMLBlockLevelElement(nsIContent* aContent);
708 enum ParseHTMLIntegerResultFlags {
709 eParseHTMLInteger_NoFlags = 0,
710 // eParseHTMLInteger_NonStandard is set if the string representation of the
711 // integer was not the canonical one, but matches at least one of the
712 // following:
713 // * had leading whitespaces
714 // * had '+' sign
715 // * had leading '0'
716 // * was '-0'
717 eParseHTMLInteger_NonStandard = 1 << 0,
718 eParseHTMLInteger_DidNotConsumeAllInput = 1 << 1,
719 // Set if one or more error flags were set.
720 eParseHTMLInteger_Error = 1 << 2,
721 eParseHTMLInteger_ErrorNoValue = 1 << 3,
722 eParseHTMLInteger_ErrorOverflow = 1 << 4,
723 // Use this flag to detect the difference between overflow and underflow
724 eParseHTMLInteger_Negative = 1 << 5,
726 static int32_t ParseHTMLInteger(const nsAString& aValue,
727 ParseHTMLIntegerResultFlags* aResult) {
728 return ParseHTMLInteger(aValue.BeginReading(), aValue.EndReading(),
729 aResult);
731 static int32_t ParseHTMLInteger(const char16_t* aStart, const char16_t* aEnd,
732 ParseHTMLIntegerResultFlags* aResult);
733 static int32_t ParseHTMLInteger(const nsACString& aValue,
734 ParseHTMLIntegerResultFlags* aResult) {
735 return ParseHTMLInteger(aValue.BeginReading(), aValue.EndReading(),
736 aResult);
738 static int32_t ParseHTMLInteger(const char* aStart, const char* aEnd,
739 ParseHTMLIntegerResultFlags* aResult);
741 private:
742 template <class CharT>
743 static int32_t ParseHTMLIntegerImpl(const CharT* aStart, const CharT* aEnd,
744 ParseHTMLIntegerResultFlags* aResult);
746 public:
748 * Parse a margin string of format 'top, right, bottom, left' into
749 * an nsIntMargin.
751 * @param aString the string to parse
752 * @param aResult the resulting integer
753 * @return whether the value could be parsed
755 static bool ParseIntMarginValue(const nsAString& aString,
756 nsIntMargin& aResult);
759 * Parse the value of the <font size=""> attribute according to the HTML5
760 * spec as of April 16, 2012.
762 * @param aValue the value to parse
763 * @return 1 to 7, or 0 if the value couldn't be parsed
765 static int32_t ParseLegacyFontSize(const nsAString& aValue);
767 static void Shutdown();
770 * Checks whether two nodes come from the same origin.
772 static nsresult CheckSameOrigin(const nsINode* aTrustedNode,
773 const nsINode* unTrustedNode);
775 // Check if the (JS) caller can access aNode.
776 static bool CanCallerAccess(const nsINode* aNode);
778 // Check if the (JS) caller can access aWindow.
779 // aWindow can be either outer or inner window.
780 static bool CanCallerAccess(nsPIDOMWindowInner* aWindow);
782 // Check if the principal is chrome or an addon with the permission.
783 static bool PrincipalHasPermission(nsIPrincipal& aPrincipal,
784 const nsAtom* aPerm);
786 // Check if the JS caller is chrome or an addon with the permission.
787 static bool CallerHasPermission(JSContext* aCx, const nsAtom* aPerm);
790 * Returns the triggering principal which should be used for the given URL
791 * attribute value with the given subject principal.
793 * If the attribute value is not an absolute URL, the subject principal will
794 * be ignored, and the node principal of aContent will be used instead.
795 * If aContent is non-null, this function will always return a principal.
796 * Otherewise, it may return null if aSubjectPrincipal is null or is rejected
797 * based on the attribute value.
799 * @param aContent The content on which the attribute is being set.
800 * @param aAttrValue The URL value of the attribute. For parsed attribute
801 * values, such as `srcset`, this function should be called separately
802 * for each URL value it contains.
803 * @param aSubjectPrincipal The subject principal of the scripted caller
804 * responsible for setting the attribute, or null if no scripted caller
805 * can be determined.
807 static nsIPrincipal* GetAttrTriggeringPrincipal(
808 nsIContent* aContent, const nsAString& aAttrValue,
809 nsIPrincipal* aSubjectPrincipal);
812 * Returns true if the given string is guaranteed to be treated as an absolute
813 * URL, rather than a relative URL. In practice, this means any complete URL
814 * as supported by nsStandardURL, or any string beginning with a valid scheme
815 * which is known to the IO service, and has the URI_NORELATIVE flag.
817 * If the URL may be treated as absolute in some cases, but relative in others
818 * (for instance, "http:foo", which can be either an absolute or relative URL,
819 * depending on the context), this function returns false.
821 static bool IsAbsoluteURL(const nsACString& aURL);
823 // Check if a node is in the document prolog, i.e. before the document
824 // element.
825 static bool InProlog(nsINode* aNode);
827 static nsIBidiKeyboard* GetBidiKeyboard();
830 * Get the cache security manager service. Can return null if the layout
831 * module has been shut down.
833 static nsIScriptSecurityManager* GetSecurityManager() {
834 return sSecurityManager;
837 // Returns the subject principal from the JSContext. May only be called
838 // from the main thread and assumes an existing compartment.
839 static nsIPrincipal* SubjectPrincipal(JSContext* aCx);
841 // Returns the subject principal. Guaranteed to return non-null. May only
842 // be called when nsContentUtils is initialized.
843 static nsIPrincipal* SubjectPrincipal();
845 // Returns the prinipal of the given JS object. This may only be called on
846 // the main thread for objects from the main thread's JSRuntime. The object
847 // must not be a cross-compartment wrapper, because CCWs are not associated
848 // with a single realm.
849 static nsIPrincipal* ObjectPrincipal(JSObject* aObj);
851 static void GenerateStateKey(nsIContent* aContent, Document* aDocument,
852 nsACString& aKey);
855 * Create a new nsIURI from aSpec, using aBaseURI as the base. The
856 * origin charset of the new nsIURI will be the document charset of
857 * aDocument.
859 static nsresult NewURIWithDocumentCharset(nsIURI** aResult,
860 const nsAString& aSpec,
861 Document* aDocument,
862 nsIURI* aBaseURI);
865 * Returns true if |aName| is a name with dashes.
867 static bool IsNameWithDash(nsAtom* aName);
870 * Returns true if |aName| is a valid name to be registered via
871 * customElements.define.
873 static bool IsCustomElementName(nsAtom* aName, uint32_t aNameSpaceID);
875 static nsresult CheckQName(const nsAString& aQualifiedName,
876 bool aNamespaceAware = true,
877 const char16_t** aColon = nullptr);
879 static nsresult SplitQName(const nsIContent* aNamespaceResolver,
880 const nsString& aQName, int32_t* aNamespace,
881 nsAtom** aLocalName);
883 static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI,
884 const nsAString& aQualifiedName,
885 nsNodeInfoManager* aNodeInfoManager,
886 uint16_t aNodeType,
887 mozilla::dom::NodeInfo** aNodeInfo);
889 static void SplitExpatName(const char16_t* aExpatName, nsAtom** aPrefix,
890 nsAtom** aTagName, int32_t* aNameSpaceID);
892 // Get a permission-manager setting for the given principal and type.
893 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
894 // returned, otherwise true is returned. Always returns true for the
895 // system principal, and false for a null principal.
896 static bool IsSitePermAllow(nsIPrincipal* aPrincipal,
897 const nsACString& aType);
899 // Get a permission-manager setting for the given principal and type.
900 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
901 // returned, otherwise true is returned. Always returns false for the
902 // system principal, and true for a null principal.
903 static bool IsSitePermDeny(nsIPrincipal* aPrincipal, const nsACString& aType);
905 // Get a permission-manager setting for the given principal and type.
906 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
907 // returned, otherwise true is returned. Always returns true for the
908 // system principal, and false for a null principal.
909 // This version checks the permission for an exact host match on
910 // the principal
911 static bool IsExactSitePermAllow(nsIPrincipal* aPrincipal,
912 const nsACString& aType);
914 // Get a permission-manager setting for the given principal and type.
915 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
916 // returned, otherwise true is returned. Always returns false for the
917 // system principal, and true for a null principal.
918 // This version checks the permission for an exact host match on
919 // the principal
920 static bool IsExactSitePermDeny(nsIPrincipal* aPrincipal,
921 const nsACString& aType);
923 // Returns true if the pref exists and is not UNKNOWN_ACTION.
924 static bool HasSitePerm(nsIPrincipal* aPrincipal, const nsACString& aType);
926 // Returns true if aDoc1 and aDoc2 have equal NodePrincipal()s.
927 static bool HaveEqualPrincipals(Document* aDoc1, Document* aDoc2);
930 * Regster aObserver as a shutdown observer. A strong reference is held
931 * to aObserver until UnregisterShutdownObserver is called.
933 static void RegisterShutdownObserver(nsIObserver* aObserver);
934 static void UnregisterShutdownObserver(nsIObserver* aObserver);
937 * @return true if aContent has an attribute aName in namespace aNameSpaceID,
938 * and the attribute value is non-empty.
940 static bool HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID,
941 nsAtom* aName);
944 * Method that gets the primary presContext for the node.
946 * @param aContent The content node.
947 * @return the presContext, or nullptr if the content is not in a document
948 * (if GetComposedDoc returns nullptr)
950 static nsPresContext* GetContextForContent(const nsIContent* aContent);
953 * Method that gets the pres shell for the node.
955 * @param aContent The content node.
956 * @return the pres shell, or nullptr if the content is not in a document
957 * (if GetComposedDoc returns nullptr)
959 static mozilla::PresShell* GetPresShellForContent(const nsIContent* aContent);
962 * Method to do security and content policy checks on the image URI
964 * @param aURI uri of the image to be loaded
965 * @param aNode, the context the image is loaded in (eg an element)
966 * @param aLoadingDocument the document we belong to
967 * @param aLoadingPrincipal the principal doing the load
968 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
969 * (Optional) The CP content type to use
970 * @param aImageBlockingStatus the nsIContentPolicy blocking status for this
971 * image. This will be set even if a security check fails for the
972 * image, to some reasonable REJECT_* value. This out param will only
973 * be set if it's non-null.
974 * @return true if the load can proceed, or false if it is blocked.
975 * Note that aImageBlockingStatus, if set will always be an ACCEPT
976 * status if true is returned and always be a REJECT_* status if
977 * false is returned.
979 static bool CanLoadImage(nsIURI* aURI, nsINode* aNode,
980 Document* aLoadingDocument,
981 nsIPrincipal* aLoadingPrincipal);
984 * Returns true if objects in aDocument shouldn't initiate image loads.
986 static bool DocumentInactiveForImageLoads(Document* aDocument);
989 * Convert a CORSMode into the corresponding imgILoader flags for
990 * passing to LoadImage.
991 * @param aMode CORS mode to convert
992 * @return a bitfield suitable to bitwise OR with other nsIRequest flags
994 static int32_t CORSModeToLoadImageFlags(mozilla::CORSMode aMode);
997 * Method to start an image load. This does not do any security checks.
998 * This method will attempt to make aURI immutable; a caller that wants to
999 * keep a mutable version around should pass in a clone.
1001 * @param aURI uri of the image to be loaded
1002 * @param aContext element of document where the result of this request
1003 * will be used.
1004 * @param aLoadingDocument the document we belong to
1005 * @param aLoadingPrincipal the principal doing the load
1006 * @param aReferrerInfo the referrerInfo use on channel creation
1007 * @param aObserver the observer for the image load
1008 * @param aLoadFlags the load flags to use. See nsIRequest
1009 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
1010 * (Optional) The CP content type to use
1011 * @param aUseUrgentStartForChannel,(Optional) a flag to mark on channel if it
1012 * is triggered by user input events.
1013 * @return the imgIRequest for the image load
1015 static nsresult LoadImage(
1016 nsIURI* aURI, nsINode* aContext, Document* aLoadingDocument,
1017 nsIPrincipal* aLoadingPrincipal, uint64_t aRequestContextID,
1018 nsIReferrerInfo* aReferrerInfo, imgINotificationObserver* aObserver,
1019 int32_t aLoadFlags, const nsAString& initiatorType,
1020 imgRequestProxy** aRequest,
1021 nsContentPolicyType aContentPolicyType =
1022 nsIContentPolicy::TYPE_INTERNAL_IMAGE,
1023 bool aUseUrgentStartForChannel = false, bool aLinkPreload = false,
1024 uint64_t aEarlyHintPreloaderId = 0);
1027 * Obtain an image loader that respects the given document/channel's privacy
1028 * status. Null document/channel arguments return the public image loader.
1030 static imgLoader* GetImgLoaderForDocument(Document* aDoc);
1031 static imgLoader* GetImgLoaderForChannel(nsIChannel* aChannel,
1032 Document* aContext);
1035 * Method to get an imgIContainer from an image loading content
1037 * @param aContent The image loading content. Must not be null.
1038 * @param aRequest The image request [out]
1039 * @return the imgIContainer corresponding to the first frame of the image
1041 static already_AddRefed<imgIContainer> GetImageFromContent(
1042 nsIImageLoadingContent* aContent, imgIRequest** aRequest = nullptr);
1045 * Method that decides whether a content node is draggable
1047 * @param aContent The content node to test.
1048 * @return whether it's draggable
1050 static bool ContentIsDraggable(nsIContent* aContent);
1053 * Method that decides whether a content node is a draggable image
1055 * @param aContent The content node to test.
1056 * @return whether it's a draggable image
1058 static bool IsDraggableImage(nsIContent* aContent);
1061 * Method that decides whether a content node is a draggable link
1063 * @param aContent The content node to test.
1064 * @return whether it's a draggable link
1066 static bool IsDraggableLink(const nsIContent* aContent);
1069 * Convenience method to create a new nodeinfo that differs only by prefix and
1070 * name from aNodeInfo. The new nodeinfo's name is set to aName, and prefix is
1071 * set to null.
1073 static nsresult QNameChanged(mozilla::dom::NodeInfo* aNodeInfo, nsAtom* aName,
1074 mozilla::dom::NodeInfo** aResult);
1077 * Returns the appropriate event argument names for the specified
1078 * namespace and event name. Added because we need to switch between
1079 * SVG's "evt" and the rest of the world's "event", and because onerror
1080 * on window takes 5 args.
1082 static void GetEventArgNames(int32_t aNameSpaceID, nsAtom* aEventName,
1083 bool aIsForWindow, uint32_t* aArgCount,
1084 const char*** aArgNames);
1087 * Returns true if this document is in a Private Browsing window.
1089 static bool IsInPrivateBrowsing(Document* aDoc);
1092 * Returns true if this loadGroup uses Private Browsing.
1094 static bool IsInPrivateBrowsing(nsILoadGroup* aLoadGroup);
1097 * Returns whether a node is in the same tree as another one, accounting for
1098 * anonymous roots.
1100 * This method is particularly useful for callers who are trying to ensure
1101 * that they are working with a non-anonymous descendant of a given node. If
1102 * aContent is a descendant of aNode, a return value of false from this
1103 * method means that it's an anonymous descendant from aNode's point of view.
1105 * Both arguments to this method must be non-null.
1107 static bool IsInSameAnonymousTree(const nsINode* aNode,
1108 const nsINode* aOtherNode);
1111 * Traverse the parent chain from aElement up to aStop, and return true if
1112 * there's an interactive html content; false otherwise.
1114 * Note: This crosses shadow boundaries but not document boundaries.
1116 static bool IsInInteractiveHTMLContent(const Element* aElement,
1117 const Element* aStop);
1120 * Return the nsIXPConnect service.
1122 static nsIXPConnect* XPConnect() { return sXPConnect; }
1125 * Report simple error message to the browser console
1126 * @param aErrorText the error message
1127 * @param aCategory Name of the module reporting error
1128 * @param aFromPrivateWindow Whether from private window or not
1129 * @param aFromChromeContext Whether from chrome context or not
1130 * @param [aErrorFlags] See nsIScriptError.
1132 static void LogSimpleConsoleError(
1133 const nsAString& aErrorText, const nsACString& aCategory,
1134 bool aFromPrivateWindow, bool aFromChromeContext,
1135 uint32_t aErrorFlags = nsIScriptError::errorFlag);
1138 * Report a non-localized error message to the error console.
1139 * @param aErrorText the error message
1140 * @param aErrorFlags See nsIScriptError.
1141 * @param aCategory Name of module reporting error.
1142 * @param aDocument Reference to the document which triggered the message.
1143 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1144 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1145 contains the error (may be empty).
1146 * @param [aLineNumber=0] (Optional) Line number within resource
1147 containing error.
1148 * @param [aColumnNumber=0] (Optional) Column number within resource
1149 containing error.
1150 If aURI is null, then aDocument->GetDocumentURI() is used.
1151 * @param [aLocationMode] (Optional) Specifies the behavior if
1152 error location information is omitted.
1154 enum MissingErrorLocationMode {
1155 // Don't show location information in the error console.
1156 eOMIT_LOCATION,
1157 // Get location information from the currently executing script.
1158 eUSE_CALLING_LOCATION
1160 static nsresult ReportToConsoleNonLocalized(
1161 const nsAString& aErrorText, uint32_t aErrorFlags,
1162 const nsACString& aCategory, const Document* aDocument,
1163 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1164 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0,
1165 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1168 * Report a non-localized error message to the error console base on the
1169 * innerWindowID.
1170 * @param aErrorText the error message
1171 * @param aErrorFlags See nsIScriptError.
1172 * @param aCategory Name of module reporting error.
1173 * @param [aInnerWindowID] Inner window ID for document which triggered the
1174 * message.
1175 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1176 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1177 contains the error (may be empty).
1178 * @param [aLineNumber=0] (Optional) Line number within resource
1179 containing error.
1180 * @param [aColumnNumber=1] (Optional) Column number within resource
1181 containing error.
1182 If aURI is null, then aDocument->GetDocumentURI() is used.
1183 * @param [aLocationMode] (Optional) Specifies the behavior if
1184 error location information is omitted.
1186 static nsresult ReportToConsoleByWindowID(
1187 const nsAString& aErrorText, uint32_t aErrorFlags,
1188 const nsACString& aCategory, uint64_t aInnerWindowID,
1189 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1190 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 1,
1191 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1194 * Report a localized error message to the error console.
1195 * @param aErrorFlags See nsIScriptError.
1196 * @param aCategory Name of module reporting error.
1197 * @param aDocument Reference to the document which triggered the message.
1198 * @param aFile Properties file containing localized message.
1199 * @param aMessageName Name of localized message.
1200 * @param [aParams=empty-array] (Optional) Parameters to be substituted into
1201 localized message.
1202 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1203 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1204 contains the error (may be empty).
1205 * @param [aLineNumber=0] (Optional) Line number within resource
1206 containing error.
1207 * @param [aColumnNumber=0] (Optional) Column number within resource
1208 containing error.
1209 If aURI is null, then aDocument->GetDocumentURI() is used.
1211 enum PropertiesFile {
1212 eCSS_PROPERTIES,
1213 eXUL_PROPERTIES,
1214 eLAYOUT_PROPERTIES,
1215 eFORMS_PROPERTIES,
1216 ePRINTING_PROPERTIES,
1217 eDOM_PROPERTIES,
1218 eHTMLPARSER_PROPERTIES,
1219 eSVG_PROPERTIES,
1220 eBRAND_PROPERTIES,
1221 eCOMMON_DIALOG_PROPERTIES,
1222 eMATHML_PROPERTIES,
1223 eSECURITY_PROPERTIES,
1224 eNECKO_PROPERTIES,
1225 eFORMS_PROPERTIES_en_US,
1226 eDOM_PROPERTIES_en_US,
1227 PropertiesFile_COUNT
1229 static nsresult ReportToConsole(
1230 uint32_t aErrorFlags, const nsACString& aCategory,
1231 const Document* aDocument, PropertiesFile aFile, const char* aMessageName,
1232 const nsTArray<nsString>& aParams = nsTArray<nsString>(),
1233 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1234 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0);
1236 static void ReportEmptyGetElementByIdArg(const Document* aDoc);
1238 static void LogMessageToConsole(const char* aMsg);
1240 static bool SpoofLocaleEnglish();
1243 * Get the localized string named |aKey| in properties file |aFile|.
1245 static nsresult GetLocalizedString(PropertiesFile aFile, const char* aKey,
1246 nsAString& aResult);
1249 * Same as GetLocalizedString, except that it might use en-US locale depending
1250 * on SpoofLocaleEnglish() and whether the document is a built-in browser
1251 * page.
1253 static nsresult GetMaybeLocalizedString(PropertiesFile aFile,
1254 const char* aKey, Document* aDocument,
1255 nsAString& aResult);
1258 * A helper function that parses a sandbox attribute (of an <iframe> or a CSP
1259 * directive) and converts it to the set of flags used internally.
1261 * @param aSandboxAttr the sandbox attribute
1262 * @return the set of flags (SANDBOXED_NONE if aSandboxAttr is
1263 * null)
1265 static uint32_t ParseSandboxAttributeToFlags(const nsAttrValue* aSandboxAttr);
1268 * A helper function that checks if a string matches a valid sandbox flag.
1270 * @param aFlag the potential sandbox flag.
1271 * @return true if the flag is a sandbox flag.
1273 static bool IsValidSandboxFlag(const nsAString& aFlag);
1276 * A helper function that returns a string attribute corresponding to the
1277 * sandbox flags.
1279 * @param aFlags the sandbox flags
1280 * @param aString the attribute corresponding to the flags (null if aFlags
1281 * is zero)
1283 static void SandboxFlagsToString(uint32_t aFlags, nsAString& aString);
1285 static bool PrefetchPreloadEnabled(nsIDocShell* aDocShell);
1287 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1288 nsAString& aSourceSpecOut, uint32_t* aLineOut,
1289 uint32_t* aColumnOut, nsString& aMessageOut);
1291 // Variant on `ExtractErrorValues` with a `nsACString`. This
1292 // method is provided for backwards compatibility. Prefer the
1293 // faster method above for your code.
1294 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1295 nsACString& aSourceSpecOut, uint32_t* aLineOut,
1296 uint32_t* aColumnOut, nsString& aMessageOut);
1298 static nsresult CalculateBufferSizeForImage(
1299 const uint32_t& aStride, const mozilla::gfx::IntSize& aImageSize,
1300 const mozilla::gfx::SurfaceFormat& aFormat, size_t* aMaxBufferSize,
1301 size_t* aUsedBufferSize);
1303 // Returns true if the URI's host is contained in a list which is a comma
1304 // separated domain list. Each item may start with "*.". If starts with
1305 // "*.", it matches any sub-domains.
1306 // The aList argument must be a lower-case string.
1307 static bool IsURIInList(nsIURI* aURI, const nsCString& aList);
1309 // Returns true if the URI's host is contained in a pref list which is a comma
1310 // separated domain list. Each item may start with "*.". If starts with
1311 // "*.", it matches any sub-domains.
1312 static bool IsURIInPrefList(nsIURI* aURI, const char* aPrefName);
1315 * A convenience version of FormatLocalizedString that can be used if all the
1316 * params are in same-typed strings. The variadic template args need to come
1317 * at the end, so we put aResult at the beginning to make sure it's clear
1318 * which is the output and which are the inputs.
1320 template <typename... T>
1321 static nsresult FormatLocalizedString(nsAString& aResult,
1322 PropertiesFile aFile, const char* aKey,
1323 const T&... aParams) {
1324 static_assert(sizeof...(aParams) != 0, "Use GetLocalizedString()");
1325 AutoTArray<nsString, sizeof...(aParams)> params = {
1326 aParams...,
1328 return FormatLocalizedString(aFile, aKey, params, aResult);
1332 * Same as FormatLocalizedString template version, except that it might use
1333 * en-US locale depending on SpoofLocaleEnglish() and whether the document is
1334 * a built-in browser page.
1336 template <typename... T>
1337 static nsresult FormatMaybeLocalizedString(nsAString& aResult,
1338 PropertiesFile aFile,
1339 const char* aKey,
1340 Document* aDocument,
1341 const T&... aParams) {
1342 static_assert(sizeof...(aParams) != 0, "Use GetMaybeLocalizedString()");
1343 AutoTArray<nsString, sizeof...(aParams)> params = {
1344 aParams...,
1346 return FormatMaybeLocalizedString(aFile, aKey, aDocument, params, aResult);
1350 * Fill (with the parameters given) the localized string named |aKey| in
1351 * properties file |aFile| consuming an nsTArray of nsString parameters rather
1352 * than a char16_t** for the sake of avoiding use-after-free errors involving
1353 * temporaries.
1355 static nsresult FormatLocalizedString(PropertiesFile aFile, const char* aKey,
1356 const nsTArray<nsString>& aParamArray,
1357 nsAString& aResult);
1360 * Same as FormatLocalizedString, except that it might use en-US locale
1361 * depending on SpoofLocaleEnglish() and whether the document is a built-in
1362 * browser page.
1364 static nsresult FormatMaybeLocalizedString(
1365 PropertiesFile aFile, const char* aKey, Document* aDocument,
1366 const nsTArray<nsString>& aParamArray, nsAString& aResult);
1369 * Returns true if aDocument is a chrome document
1371 static bool IsChromeDoc(const Document* aDocument);
1374 * Returns true if aDocument is in a docshell whose parent is the same type
1376 static bool IsChildOfSameType(Document* aDoc);
1379 * Returns true if the content-type will be rendered as plain-text.
1381 static bool IsPlainTextType(const nsACString& aContentType);
1384 * Returns true iff the type is rendered as plain text and doesn't support
1385 * non-UTF-8 encodings.
1387 static bool IsUtf8OnlyPlainTextType(const nsACString& aContentType);
1390 * Returns true if aDocument belongs to a chrome docshell for
1391 * display purposes. Returns false for null documents or documents
1392 * which do not belong to a docshell.
1394 static bool IsInChromeDocshell(const Document* aDocument);
1397 * Return the content policy service
1399 static nsIContentPolicy* GetContentPolicy();
1402 * Map internal content policy types to external ones.
1404 static inline ExtContentPolicyType InternalContentPolicyTypeToExternal(
1405 nsContentPolicyType aType);
1408 * check whether the Link header field applies to the context resource
1409 * see <http://tools.ietf.org/html/rfc5988#section-5.2>
1411 static bool LinkContextIsURI(const nsAString& aAnchor, nsIURI* aDocURI);
1414 * Returns true if the content policy type is any of:
1415 * * TYPE_INTERNAL_SCRIPT_PRELOAD
1416 * * TYPE_INTERNAL_IMAGE_PRELOAD
1417 * * TYPE_INTERNAL_STYLESHEET_PRELOAD
1419 static bool IsPreloadType(nsContentPolicyType aType);
1422 * Quick helper to determine whether there are any mutation listeners
1423 * of a given type that apply to this content or any of its ancestors.
1424 * The method has the side effect to call document's MayDispatchMutationEvent
1425 * using aTargetForSubtreeModified as the parameter.
1427 * @param aNode The node to search for listeners
1428 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1429 * @param aTargetForSubtreeModified The node which is the target of the
1430 * possible DOMSubtreeModified event.
1432 * @return true if there are mutation listeners of the specified type
1434 static bool HasMutationListeners(nsINode* aNode, uint32_t aType,
1435 nsINode* aTargetForSubtreeModified);
1438 * Quick helper to determine whether there are any mutation listeners
1439 * of a given type that apply to any content in this document. It is valid
1440 * to pass null for aDocument here, in which case this function always
1441 * returns true.
1443 * @param aDocument The document to search for listeners
1444 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1446 * @return true if there are mutation listeners of the specified type
1448 static bool HasMutationListeners(Document* aDocument, uint32_t aType);
1450 * Synchronously fire DOMNodeRemoved on aChild. Only fires the event if
1451 * there really are listeners by checking using the HasMutationListeners
1452 * function above. The function makes sure to hold the relevant objects alive
1453 * for the duration of the event firing. However there are no guarantees
1454 * that any of the objects are alive by the time the function returns.
1455 * If you depend on that you need to hold references yourself.
1457 * @param aChild The node to fire DOMNodeRemoved at.
1458 * @param aParent The parent of aChild.
1460 MOZ_CAN_RUN_SCRIPT static void MaybeFireNodeRemoved(nsINode* aChild,
1461 nsINode* aParent);
1464 * These methods create and dispatch a trusted event.
1465 * Works only with events which can be created by calling
1466 * Document::CreateEvent() with parameter "Events".
1467 * Note that don't use these methods for "input" event. Use
1468 * DispatchInputEvent() instead.
1470 * @param aDoc The document which will be used to create the event.
1471 * @param aTarget The target of the event.
1472 * @param aEventName The name of the event.
1473 * @param aCanBubble Whether the event can bubble.
1474 * @param aCancelable Is the event cancelable.
1475 * @param aCopmosed Is the event composed.
1476 * @param aDefaultAction Set to true if default action should be taken,
1477 * see EventTarget::DispatchEvent.
1479 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1480 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1481 static nsresult DispatchTrustedEvent(Document* aDoc,
1482 mozilla::dom::EventTarget* aTarget,
1483 const nsAString& aEventName, CanBubble,
1484 Cancelable,
1485 Composed aComposed = Composed::eDefault,
1486 bool* aDefaultAction = nullptr);
1488 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1489 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1490 static nsresult DispatchTrustedEvent(Document* aDoc,
1491 mozilla::dom::EventTarget* aTarget,
1492 const nsAString& aEventName,
1493 CanBubble aCanBubble,
1494 Cancelable aCancelable,
1495 bool* aDefaultAction) {
1496 return DispatchTrustedEvent(aDoc, aTarget, aEventName, aCanBubble,
1497 aCancelable, Composed::eDefault,
1498 aDefaultAction);
1502 * This method creates and dispatches a trusted event using an event message.
1503 * @param aDoc The document which will be used to create the event.
1504 * @param aTarget The target of the event.
1505 * @param aEventMessage The event message.
1506 * @param aCanBubble Whether the event can bubble.
1507 * @param aCancelable Is the event cancelable.
1508 * @param aDefaultAction Set to true if default action should be taken,
1509 * see EventTarget::DispatchEvent.
1511 template <class WidgetEventType>
1512 static nsresult DispatchTrustedEvent(
1513 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1514 EventMessage aEventMessage, CanBubble aCanBubble, Cancelable aCancelable,
1515 bool* aDefaultAction = nullptr,
1516 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1517 WidgetEventType event(true, aEventMessage);
1518 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1519 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1520 aCancelable, Trusted::eYes, aDefaultAction,
1521 aOnlyChromeDispatch);
1525 * This method dispatches "beforeinput" event with EditorInputEvent or
1526 * "input" event with proper event class. If it's unsafe to dispatch,
1527 * this put the event into the script runner queue. In such case, the
1528 * event becomes not cancelable even if it's defined as cancelable by
1529 * the spec.
1530 * Input Events spec defines as:
1531 * Input events are dispatched on elements that act as editing hosts,
1532 * including elements with the contenteditable attribute set, textarea
1533 * elements, and input elements that permit text input.
1535 * @param aEventTarget The event target element of the "beforeinput"
1536 * or "input" event. Must not be nullptr.
1537 * @param aEventMessage Muse be eEditorBeforeInput or eEditorInput.
1538 * @param aEditorInputType The inputType value of InputEvent.
1539 * If aEventTarget won't dispatch "input" event
1540 * with InputEvent, set EditorInputType::eUnknown.
1541 * @param aEditorBase Optional. If this is called by editor,
1542 * editor should set this. Otherwise, leave
1543 * nullptr.
1544 * @param aOptions Optional. If aEditorInputType value requires
1545 * some additional data, they should be properly
1546 * set with this argument.
1547 * @param aEventStatus Returns nsEventStatus_eConsumeNoDefault if
1548 * the dispatching event is cancelable and the
1549 * event was canceled by script (including
1550 * chrome script). Otherwise, returns given
1551 * value. Note that this can be nullptr only
1552 * when the dispatching event is not cancelable.
1554 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(Element* aEventTarget);
1555 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(
1556 Element* aEventTarget, mozilla::EventMessage aEventMessage,
1557 mozilla::EditorInputType aEditorInputType,
1558 mozilla::EditorBase* aEditorBase, mozilla::InputEventOptions&& aOptions,
1559 nsEventStatus* aEventStatus = nullptr);
1562 * This method creates and dispatches a untrusted event.
1563 * Works only with events which can be created by calling
1564 * Document::CreateEvent() with parameter "Events".
1565 * @param aDoc The document which will be used to create the event.
1566 * @param aTarget The target of the event.
1567 * @param aEventName The name of the event.
1568 * @param aCanBubble Whether the event can bubble.
1569 * @param aCancelable Is the event cancelable.
1570 * @param aDefaultAction Set to true if default action should be taken,
1571 * see EventTarget::DispatchEvent.
1573 static nsresult DispatchUntrustedEvent(Document* aDoc,
1574 mozilla::dom::EventTarget* aTarget,
1575 const nsAString& aEventName, CanBubble,
1576 Cancelable,
1577 bool* aDefaultAction = nullptr);
1580 * This method creates and dispatches a untrusted event using an event
1581 * message.
1582 * @param aDoc The document which will be used to create the event.
1583 * @param aTarget The target of the event.
1584 * @param aEventMessage The event message.
1585 * @param aCanBubble Whether the event can bubble.
1586 * @param aCancelable Is the event cancelable.
1587 * @param aDefaultAction Set to true if default action should be taken,
1588 * see EventTarget::DispatchEvent.
1590 template <class WidgetEventType>
1591 static nsresult DispatchUntrustedEvent(
1592 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1593 EventMessage aEventMessage, CanBubble aCanBubble, Cancelable aCancelable,
1594 bool* aDefaultAction = nullptr,
1595 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1596 WidgetEventType event(false, aEventMessage);
1597 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1598 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1599 aCancelable, Trusted::eNo, aDefaultAction,
1600 aOnlyChromeDispatch);
1604 * This method creates and dispatches a trusted event to the chrome
1605 * event handler (the parent object of the DOM Window in the event target
1606 * chain). Note, chrome event handler is used even if aTarget is a chrome
1607 * object. Use DispatchEventOnlyToChrome if the normal event dispatching is
1608 * wanted in case aTarget is a chrome object.
1609 * Works only with events which can be created by calling
1610 * Document::CreateEvent() with parameter "Events".
1611 * @param aDocument The document which will be used to create the event,
1612 * and whose window's chrome handler will be used to
1613 * dispatch the event.
1614 * @param aTarget The target of the event, used for event->SetTarget()
1615 * @param aEventName The name of the event.
1616 * @param aCanBubble Whether the event can bubble.
1617 * @param aCancelable Is the event cancelable.
1618 * @param aDefaultAction Set to true if default action should be taken,
1619 * see EventTarget::DispatchEvent.
1621 static nsresult DispatchChromeEvent(Document* aDoc,
1622 mozilla::dom::EventTarget* aTarget,
1623 const nsAString& aEventName, CanBubble,
1624 Cancelable,
1625 bool* aDefaultAction = nullptr);
1628 * Helper to dispatch a "framefocusrequested" event to chrome, which will only
1629 * bring the window to the foreground and switch tabs if aCanRaise is true.
1631 MOZ_CAN_RUN_SCRIPT_BOUNDARY static void RequestFrameFocus(
1632 Element& aFrameElement, bool aCanRaise,
1633 mozilla::dom::CallerType aCallerType);
1636 * This method creates and dispatches a trusted event.
1637 * If aTarget is not a chrome object, the nearest chrome object in the
1638 * propagation path will be used as the start of the event target chain.
1639 * This method is different than DispatchChromeEvent, which always dispatches
1640 * events to chrome event handler. DispatchEventOnlyToChrome works like
1641 * DispatchTrustedEvent in the case aTarget is a chrome object.
1642 * Works only with events which can be created by calling
1643 * Document::CreateEvent() with parameter "Events".
1644 * @param aDoc The document which will be used to create the event.
1645 * @param aTarget The target of the event.
1646 * @param aEventName The name of the event.
1647 * @param aCanBubble Whether the event can bubble.
1648 * @param aCancelable Is the event cancelable.
1649 * @param aComposed Is the event composed.
1650 * @param aDefaultAction Set to true if default action should be taken,
1651 * see EventTarget::DispatchEvent.
1653 static nsresult DispatchEventOnlyToChrome(
1654 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1655 const nsAString& aEventName, CanBubble, Cancelable,
1656 Composed aComposed = Composed::eDefault, bool* aDefaultAction = nullptr);
1658 static nsresult DispatchEventOnlyToChrome(Document* aDoc,
1659 mozilla::dom::EventTarget* aTarget,
1660 const nsAString& aEventName,
1661 CanBubble aCanBubble,
1662 Cancelable aCancelable,
1663 bool* aDefaultAction) {
1664 return DispatchEventOnlyToChrome(aDoc, aTarget, aEventName, aCanBubble,
1665 aCancelable, Composed::eDefault,
1666 aDefaultAction);
1670 * Determines if an event attribute name (such as onclick) is valid for
1671 * a given element type. Types are from the EventNameType enumeration
1672 * defined above.
1674 * @param aName the event name to look up
1675 * @param aType the type of content
1677 static bool IsEventAttributeName(nsAtom* aName, int32_t aType);
1680 * Return the event message for the event with the given name. The name is
1681 * the event name with the 'on' prefix. Returns eUnidentifiedEvent if the
1682 * event doesn't match a known event name.
1684 * @param aName the event name to look up
1686 static EventMessage GetEventMessage(nsAtom* aName);
1689 * Return the event type atom for a given event message.
1691 static nsAtom* GetEventTypeFromMessage(EventMessage aEventMessage);
1694 * Returns the EventMessage and nsAtom to be used for event listener
1695 * registration.
1697 static EventMessage GetEventMessageAndAtomForListener(const nsAString& aName,
1698 nsAtom** aOnName);
1701 * Return the EventClassID for the event with the given name. The name is the
1702 * event name *without* the 'on' prefix. Returns eBasicEventClass if the event
1703 * is not known to be of any particular event class.
1705 * @param aName the event name to look up
1707 static mozilla::EventClassID GetEventClassID(const nsAString& aName);
1710 * Return the event message and atom for the event with the given name.
1711 * The name is the event name *without* the 'on' prefix.
1712 * Returns eUnidentifiedEvent on the aEventID if the
1713 * event doesn't match a known event name in the category.
1715 * @param aName the event name to look up
1716 * @param aEventClassID only return event id for aEventClassID
1718 static nsAtom* GetEventMessageAndAtom(const nsAString& aName,
1719 mozilla::EventClassID aEventClassID,
1720 EventMessage* aEventMessage);
1723 * Used only during traversal of the XPCOM graph by the cycle
1724 * collector: push a pointer to the listener manager onto the
1725 * children deque, if it exists. Do nothing if there is no listener
1726 * manager.
1728 * Crucially: does not perform any refcounting operations.
1730 * @param aNode The node to traverse.
1731 * @param children The buffer to push a listener manager pointer into.
1733 static void TraverseListenerManager(nsINode* aNode,
1734 nsCycleCollectionTraversalCallback& cb);
1737 * Get the eventlistener manager for aNode, creating it if it does not
1738 * already exist.
1740 * @param aNode The node for which to get the eventlistener manager.
1742 static mozilla::EventListenerManager* GetListenerManagerForNode(
1743 nsINode* aNode);
1745 * Get the eventlistener manager for aNode, returning null if it does not
1746 * already exist.
1748 * @param aNode The node for which to get the eventlistener manager.
1750 static mozilla::EventListenerManager* GetExistingListenerManagerForNode(
1751 const nsINode* aNode);
1753 static void AddEntryToDOMArenaTable(nsINode* aNode,
1754 mozilla::dom::DOMArena* aDOMArena);
1756 static already_AddRefed<mozilla::dom::DOMArena> TakeEntryFromDOMArenaTable(
1757 const nsINode* aNode);
1759 static void UnmarkGrayJSListenersInCCGenerationDocuments();
1762 * Remove the eventlistener manager for aNode.
1764 * @param aNode The node for which to remove the eventlistener manager.
1766 static void RemoveListenerManager(nsINode* aNode);
1768 static bool IsInitialized() { return sInitialized; }
1771 * Checks if the localname/prefix/namespace triple is valid wrt prefix
1772 * and namespace according to the Namespaces in XML and DOM Code
1773 * specfications.
1775 * @param aLocalname localname of the node
1776 * @param aPrefix prefix of the node
1777 * @param aNamespaceID namespace of the node
1779 static bool IsValidNodeName(nsAtom* aLocalName, nsAtom* aPrefix,
1780 int32_t aNamespaceID);
1783 * Creates a DocumentFragment from text using a context node to resolve
1784 * namespaces.
1786 * Please note that for safety reasons, if the node principal of
1787 * aContextNode is the system principal, this function will automatically
1788 * sanitize its input using nsTreeSanitizer.
1790 * Note! In the HTML case with the HTML5 parser enabled, this is only called
1791 * from Range.createContextualFragment() and the implementation here is
1792 * quirky accordingly (html context node behaves like a body context node).
1793 * If you don't want that quirky behavior, don't use this method as-is!
1795 * @param aContextNode the node which is used to resolve namespaces
1796 * @param aFragment the string which is parsed to a DocumentFragment
1797 * @param aReturn the resulting fragment
1798 * @param aPreventScriptExecution whether to mark scripts as already started
1800 static already_AddRefed<mozilla::dom::DocumentFragment>
1801 CreateContextualFragment(nsINode* aContextNode, const nsAString& aFragment,
1802 bool aPreventScriptExecution,
1803 mozilla::ErrorResult& aRv);
1806 * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
1808 * Please note that for safety reasons, if the node principal of aTargetNode
1809 * is the system principal, this function will automatically sanitize its
1810 * input using nsTreeSanitizer.
1812 * @param aSourceBuffer the string being set as innerHTML
1813 * @param aTargetNode the target container
1814 * @param aContextLocalName local name of context node
1815 * @param aContextNamespace namespace of context node
1816 * @param aQuirks true to make <table> not close <p>
1817 * @param aPreventScriptExecution true to prevent scripts from executing;
1818 * don't set to false when parsing into a target node that has been
1819 * bound to tree.
1820 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1821 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1822 * long and NS_OK otherwise.
1823 * @param aFlags defaults to -1 indicating that ParseFragmentHTML will do
1824 * default sanitization for system privileged calls to it. Only
1825 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1826 * which will then used for sanitization of the fragment.
1827 * To pass explicit aFlags use any of the sanitization flags
1828 * listed in nsIParserUtils.idl.
1830 static nsresult ParseFragmentHTML(const nsAString& aSourceBuffer,
1831 nsIContent* aTargetNode,
1832 nsAtom* aContextLocalName,
1833 int32_t aContextNamespace, bool aQuirks,
1834 bool aPreventScriptExecution,
1835 int32_t aFlags = -1);
1838 * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
1840 * Please note that for safety reasons, if the node principal of aDocument
1841 * is the system principal, this function will automatically sanitize its
1842 * input using nsTreeSanitizer.
1844 * @param aSourceBuffer the string being set as innerHTML
1845 * @param aDocument the target document
1846 * @param aTagStack the namespace mapping context
1847 * @param aPreventExecution whether to mark scripts as already started
1848 * @param aFlags, pass -1 and ParseFragmentXML will do default
1849 * sanitization for system privileged calls to it. Only
1850 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1851 * which will then used for sanitization of the fragment.
1852 * To pass explicit aFlags use any of the sanitization flags
1853 * listed in nsIParserUtils.idl.
1854 * @param aReturn the result fragment
1855 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1856 * fragments is made, a return code from the XML parser.
1858 static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
1859 Document* aDocument,
1860 nsTArray<nsString>& aTagStack,
1861 bool aPreventScriptExecution, int32_t aFlags,
1862 mozilla::dom::DocumentFragment** aReturn);
1865 * Parse a string into a document using the HTML parser.
1866 * Script elements are marked unexecutable.
1868 * @param aSourceBuffer the string to parse as an HTML document
1869 * @param aTargetDocument the document object to parse into. Must not have
1870 * child nodes.
1871 * @param aScriptingEnabledForNoscriptParsing whether <noscript> is parsed
1872 * as if scripting was enabled
1873 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1874 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1875 * long and NS_OK otherwise.
1877 static nsresult ParseDocumentHTML(const nsAString& aSourceBuffer,
1878 Document* aTargetDocument,
1879 bool aScriptingEnabledForNoscriptParsing);
1882 * Converts HTML source to plain text by parsing the source and using the
1883 * plain text serializer on the resulting tree.
1885 * @param aSourceBuffer the string to parse as an HTML document
1886 * @param aResultBuffer the string where the plain text result appears;
1887 * may be the same string as aSourceBuffer
1888 * @param aFlags Flags from nsIDocumentEncoder.
1889 * @param aWrapCol Number of columns after which to line wrap; 0 for no
1890 * auto-wrapping
1891 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1892 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1893 * long and NS_OK otherwise.
1895 static nsresult ConvertToPlainText(const nsAString& aSourceBuffer,
1896 nsAString& aResultBuffer, uint32_t aFlags,
1897 uint32_t aWrapCol);
1900 * Creates a 'loaded-as-data' HTML document that takes that principal,
1901 * script global, and URL from the argument, which may be null.
1903 static already_AddRefed<Document> CreateInertHTMLDocument(
1904 const Document* aTemplate);
1907 * Creates a 'loaded-as-data' XML document that takes that principal,
1908 * script global, and URL from the argument, which may be null.
1910 static already_AddRefed<Document> CreateInertXMLDocument(
1911 const Document* aTemplate);
1913 public:
1915 * Sets the text contents of a node by replacing all existing children
1916 * with a single text child.
1918 * The function always notifies.
1920 * Will reuse the first text child if one is available. Will not reuse
1921 * existing cdata children.
1923 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1925 * @param aContent Node to set contents of.
1926 * @param aValue Value to set contents to.
1927 * @param aTryReuse When true, the function will try to reuse an existing
1928 * textnodes rather than always creating a new one.
1930 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult SetNodeTextContent(
1931 nsIContent* aContent, const nsAString& aValue, bool aTryReuse);
1934 * Get the textual contents of a node. This is a concatenation of all
1935 * textnodes that are direct or (depending on aDeep) indirect children
1936 * of the node.
1938 * NOTE! No serialization takes place and <br> elements
1939 * are not converted into newlines. Only textnodes and cdata nodes are
1940 * added to the result.
1942 * @see nsLayoutUtils::GetFrameTextContent
1944 * @param aNode Node to get textual contents of.
1945 * @param aDeep If true child elements of aNode are recursivly descended
1946 * into to find text children.
1947 * @param aResult the result. Out param.
1948 * @return false on out of memory errors, true otherwise.
1950 [[nodiscard]] static bool GetNodeTextContent(const nsINode* aNode, bool aDeep,
1951 nsAString& aResult,
1952 const mozilla::fallible_t&);
1954 static void GetNodeTextContent(const nsINode* aNode, bool aDeep,
1955 nsAString& aResult);
1958 * Same as GetNodeTextContents but appends the result rather than sets it.
1960 static bool AppendNodeTextContent(const nsINode* aNode, bool aDeep,
1961 nsAString& aResult,
1962 const mozilla::fallible_t&);
1965 * Utility method that checks if a given node has any non-empty children. This
1966 * method does not descend recursively into children by default.
1968 * @param aDiscoverMode Set to eRecurseIntoChildren to descend recursively
1969 * into children.
1971 enum TextContentDiscoverMode : uint8_t {
1972 eRecurseIntoChildren,
1973 eDontRecurseIntoChildren
1976 static bool HasNonEmptyTextContent(
1977 nsINode* aNode,
1978 TextContentDiscoverMode aDiscoverMode = eDontRecurseIntoChildren);
1981 * Delete strings allocated for nsContentList matches
1983 static void DestroyMatchString(void* aData);
1986 * Notify when the first XUL menu is opened and when the all XUL menus are
1987 * closed. At opening, aInstalling should be TRUE, otherwise, it should be
1988 * FALSE.
1990 MOZ_CAN_RUN_SCRIPT static void NotifyInstalledMenuKeyboardListener(
1991 bool aInstalling);
1994 * Check whether the nsIURI uses the given scheme.
1996 * Note that this will check the innermost URI rather than that of
1997 * the nsIURI itself.
1999 static bool SchemeIs(nsIURI* aURI, const char* aScheme);
2002 * Returns true if aPrincipal is an ExpandedPrincipal.
2004 static bool IsExpandedPrincipal(nsIPrincipal* aPrincipal);
2007 * Returns true if aPrincipal is the system or an ExpandedPrincipal.
2009 static bool IsSystemOrExpandedPrincipal(nsIPrincipal* aPrincipal);
2012 * Gets the system principal from the security manager.
2014 static nsIPrincipal* GetSystemPrincipal();
2017 * Gets the null subject principal singleton. This is only useful for
2018 * assertions.
2020 static nsIPrincipal* GetNullSubjectPrincipal() {
2021 return sNullSubjectPrincipal;
2025 * *aResourcePrincipal is a principal describing who may access the contents
2026 * of a resource. The resource can only be consumed by a principal that
2027 * subsumes *aResourcePrincipal. MAKE SURE THAT NOTHING EVER ACTS WITH THE
2028 * AUTHORITY OF *aResourcePrincipal.
2029 * It may be null to indicate that the resource has no data from any origin
2030 * in it yet and anything may access the resource.
2031 * Additional data is being mixed into the resource from aExtraPrincipal
2032 * (which may be null; if null, no data is being mixed in and this function
2033 * will do nothing). Update *aResourcePrincipal to reflect the new data.
2034 * If *aResourcePrincipal subsumes aExtraPrincipal, nothing needs to change,
2035 * otherwise *aResourcePrincipal is replaced with the system principal.
2036 * Returns true if *aResourcePrincipal changed.
2038 static bool CombineResourcePrincipals(
2039 nsCOMPtr<nsIPrincipal>* aResourcePrincipal,
2040 nsIPrincipal* aExtraPrincipal);
2043 * Trigger a link with uri aLinkURI. If aClick is false, this triggers a
2044 * mouseover on the link, otherwise it triggers a load after doing a
2045 * security check using aContent's principal.
2047 * @param aContent the node on which a link was triggered.
2048 * @param aLinkURI the URI of the link, must be non-null.
2049 * @param aTargetSpec the target (like target=, may be empty).
2050 * @param aClick whether this was a click or not (if false, this method
2051 * assumes you just hovered over the link).
2052 * @param aIsTrusted If false, JS Context will be pushed to stack
2053 * when the link is triggered.
2055 static void TriggerLink(nsIContent* aContent, nsIURI* aLinkURI,
2056 const nsString& aTargetSpec, bool aClick,
2057 bool aIsTrusted);
2060 * Get the link location.
2062 static void GetLinkLocation(mozilla::dom::Element* aElement,
2063 nsString& aLocationString);
2066 * Return top-level widget in the parent chain.
2068 static nsIWidget* GetTopLevelWidget(nsIWidget* aWidget);
2071 * Return the localized ellipsis for UI.
2073 static const nsDependentString GetLocalizedEllipsis();
2076 * Hide any XUL popups associated with aDocument, including any documents
2077 * displayed in child frames. Does nothing if aDocument is null.
2079 MOZ_CAN_RUN_SCRIPT_BOUNDARY static void HidePopupsInDocument(
2080 Document* aDocument);
2083 * Retrieve the current drag session, or null if no drag is currently occuring
2085 static already_AddRefed<nsIDragSession> GetDragSession();
2088 * Initialize and set the dataTransfer field of an WidgetDragEvent.
2090 static nsresult SetDataTransferInEvent(mozilla::WidgetDragEvent* aDragEvent);
2092 // filters the drag and drop action to fit within the effects allowed and
2093 // returns it.
2094 static uint32_t FilterDropEffect(uint32_t aAction, uint32_t aEffectAllowed);
2097 * Return true if the target of a drop event is a content document that is
2098 * an ancestor of the document for the source of the drag.
2100 static bool CheckForSubFrameDrop(nsIDragSession* aDragSession,
2101 mozilla::WidgetDragEvent* aDropEvent);
2104 * Return true if aURI is a local file URI (i.e. file://).
2106 static bool URIIsLocalFile(nsIURI* aURI);
2109 * Get the application manifest URI for this document. The manifest URI
2110 * is specified in the manifest= attribute of the root element of the
2111 * document.
2113 * @param aDocument The document that lists the manifest.
2114 * @param aURI The manifest URI.
2116 static void GetOfflineAppManifest(Document* aDocument, nsIURI** aURI);
2119 * Check whether an application should be allowed to use offline APIs.
2121 static bool OfflineAppAllowed(nsIURI* aURI);
2124 * Check whether an application should be allowed to use offline APIs.
2126 static bool OfflineAppAllowed(nsIPrincipal* aPrincipal);
2129 * Increases the count of blockers preventing scripts from running.
2130 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2131 * this directly
2133 static void AddScriptBlocker();
2136 * Decreases the count of blockers preventing scripts from running.
2137 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2138 * this directly
2140 * WARNING! Calling this function could synchronously execute scripts.
2142 static void RemoveScriptBlocker();
2145 * Add a runnable that is to be executed as soon as it's safe to execute
2146 * scripts.
2147 * NOTE: If it's currently safe to execute scripts, aRunnable will be run
2148 * synchronously before the function returns.
2150 * @param aRunnable The nsIRunnable to run as soon as it's safe to execute
2151 * scripts. Passing null is allowed and results in nothing
2152 * happening. It is also allowed to pass an object that
2153 * has not yet been AddRefed.
2155 static void AddScriptRunner(already_AddRefed<nsIRunnable> aRunnable);
2156 static void AddScriptRunner(nsIRunnable* aRunnable);
2159 * Returns true if it's safe to execute content script and false otherwise.
2161 * The only known case where this lies is mutation events. They run, and can
2162 * run anything else, when this function returns false, but this is ok.
2164 static bool IsSafeToRunScript();
2166 // Returns the browser window with the most recent time stamp that is
2167 // not in private browsing mode.
2168 static already_AddRefed<nsPIDOMWindowOuter> GetMostRecentNonPBWindow();
2171 * Call this function if !IsSafeToRunScript() and we fail to run the script
2172 * (rather than using AddScriptRunner as we usually do). |aDocument| is
2173 * optional as it is only used for showing the URL in the console.
2175 static void WarnScriptWasIgnored(Document* aDocument);
2178 * Add a "synchronous section", in the form of an nsIRunnable run once the
2179 * event loop has reached a "stable state". |aRunnable| must not cause any
2180 * queued events to be processed (i.e. must not spin the event loop).
2181 * We've reached a stable state when the currently executing task/event has
2182 * finished, see
2183 * http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#synchronous-section
2184 * In practice this runs aRunnable once the currently executing event
2185 * finishes. If called multiple times per task/event, all the runnables will
2186 * be executed, in the order in which RunInStableState() was called.
2188 static void RunInStableState(already_AddRefed<nsIRunnable> aRunnable);
2190 /* Add a pending IDBTransaction to be cleaned up at the end of performing a
2191 * microtask checkpoint.
2192 * See the step of "Cleanup Indexed Database Transactions" in
2193 * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
2195 static void AddPendingIDBTransaction(
2196 already_AddRefed<nsIRunnable> aTransaction);
2199 * Returns true if we are doing StableState/MetastableState.
2201 static bool IsInStableOrMetaStableState();
2203 static JSContext* GetCurrentJSContext();
2206 * Case insensitive comparison between two atoms.
2208 static bool EqualsIgnoreASCIICase(nsAtom* aAtom1, nsAtom* aAtom2);
2211 * Case insensitive comparison between two strings. However it only ignores
2212 * case for ASCII characters a-z.
2214 static bool EqualsIgnoreASCIICase(const nsAString& aStr1,
2215 const nsAString& aStr2);
2218 * Convert ASCII A-Z to a-z.
2220 static void ASCIIToLower(nsAString& aStr);
2221 static void ASCIIToLower(nsACString& aStr);
2222 static void ASCIIToLower(const nsAString& aSource, nsAString& aDest);
2223 static void ASCIIToLower(const nsACString& aSource, nsACString& aDest);
2226 * Convert ASCII a-z to A-Z.
2228 static void ASCIIToUpper(nsAString& aStr);
2229 static void ASCIIToUpper(nsACString& aStr);
2230 static void ASCIIToUpper(const nsAString& aSource, nsAString& aDest);
2231 static void ASCIIToUpper(const nsACString& aSource, nsACString& aDest);
2234 * Return whether aStr contains an ASCII uppercase character.
2236 static bool StringContainsASCIIUpper(const nsAString& aStr);
2238 // Returns NS_OK for same origin, error (NS_ERROR_DOM_BAD_URI) if not.
2239 static nsresult CheckSameOrigin(nsIChannel* aOldChannel,
2240 nsIChannel* aNewChannel);
2241 static nsIInterfaceRequestor* SameOriginChecker();
2244 * Returns an ASCII compatible serialization of the nsIPrincipal or nsIURI's
2245 * origin, as specified by the whatwg HTML specification. If the principal
2246 * does not have a host, the origin will be "null".
2248 * https://html.spec.whatwg.org/multipage/browsers.html#ascii-serialisation-of-an-origin
2250 * Note that this is different from nsIPrincipal::GetOrigin, does not contain
2251 * gecko-specific metadata like origin attributes, and should not be used for
2252 * permissions or security checks.
2254 * See also `nsIPrincipal::GetWebExposedOriginSerialization`.
2256 * These methods are thread-safe.
2258 * @pre aPrincipal/aURI must not be null.
2260 * @note this should be used for HTML5 origin determination.
2262 static nsresult GetWebExposedOriginSerialization(nsIURI* aURI,
2263 nsACString& aOrigin);
2264 static nsresult GetWebExposedOriginSerialization(nsIPrincipal* aPrincipal,
2265 nsAString& aOrigin);
2266 static nsresult GetWebExposedOriginSerialization(nsIURI* aURI,
2267 nsAString& aOrigin);
2270 * This method creates and dispatches "command" event, which implements
2271 * XULCommandEvent.
2272 * If aPresShell is not null, dispatching goes via
2273 * PresShell::HandleDOMEventWithTarget().
2275 MOZ_CAN_RUN_SCRIPT
2276 static nsresult DispatchXULCommand(
2277 nsIContent* aTarget, bool aTrusted,
2278 mozilla::dom::Event* aSourceEvent = nullptr,
2279 mozilla::PresShell* aPresShell = nullptr, bool aCtrl = false,
2280 bool aAlt = false, bool aShift = false, bool aMeta = false,
2281 // Including MouseEventBinding here leads
2282 // to incude loops, unfortunately.
2283 uint16_t inputSource = 0 /* MouseEvent_Binding::MOZ_SOURCE_UNKNOWN */,
2284 int16_t aButton = 0);
2286 static bool CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel,
2287 bool aAllowIfInheritsPrincipal);
2290 * The method checks whether the caller can access native anonymous content.
2291 * If there is no JS in the stack or privileged JS is running, this
2292 * method returns true, otherwise false.
2294 static bool CanAccessNativeAnon();
2296 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2297 const nsIID* aIID,
2298 JS::MutableHandle<JS::Value> vp,
2299 bool aAllowWrapping = true) {
2300 return WrapNative(cx, native, nullptr, aIID, vp, aAllowWrapping);
2303 // Same as the WrapNative above, but use this one if aIID is nsISupports' IID.
2304 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2305 JS::MutableHandle<JS::Value> vp,
2306 bool aAllowWrapping = true) {
2307 return WrapNative(cx, native, nullptr, nullptr, vp, aAllowWrapping);
2310 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2311 nsWrapperCache* cache,
2312 JS::MutableHandle<JS::Value> vp,
2313 bool aAllowWrapping = true) {
2314 return WrapNative(cx, native, cache, nullptr, vp, aAllowWrapping);
2317 static void StripNullChars(const nsAString& aInStr, nsAString& aOutStr);
2320 * Strip all \n, \r and nulls from the given string
2321 * @param aString the string to remove newlines from [in/out]
2323 static void RemoveNewlines(nsString& aString);
2326 * Convert Windows and Mac platform linebreaks to \n.
2327 * @param aString the string to convert the newlines inside [in/out]
2329 static void PlatformToDOMLineBreaks(nsString& aString);
2330 [[nodiscard]] static bool PlatformToDOMLineBreaks(nsString& aString,
2331 const mozilla::fallible_t&);
2334 * Populates aResultString with the contents of the string-buffer aBuf, up
2335 * to aBuf's null-terminator. aBuf must not be null. Ownership of the string
2336 * is not transferred.
2338 static void PopulateStringFromStringBuffer(nsStringBuffer* aBuf,
2339 nsAString& aResultString);
2341 static bool IsHandlingKeyBoardEvent() { return sIsHandlingKeyBoardEvent; }
2343 static void SetIsHandlingKeyBoardEvent(bool aHandling) {
2344 sIsHandlingKeyBoardEvent = aHandling;
2348 * Utility method for getElementsByClassName. aRootNode is the node (either
2349 * document or element), which getElementsByClassName was called on.
2351 static already_AddRefed<nsContentList> GetElementsByClassName(
2352 nsINode* aRootNode, const nsAString& aClasses);
2355 * Returns a presshell for this document, if there is one. This will be
2356 * aDoc's direct presshell if there is one, otherwise we'll look at all
2357 * ancestor documents to try to find a presshell, so for example this can
2358 * still find a presshell for documents in display:none frames that have
2359 * no presentation. So you have to be careful how you use this presshell ---
2360 * getting generic data like a device context or widget from it is OK, but it
2361 * might not be this document's actual presentation.
2363 static mozilla::PresShell* FindPresShellForDocument(
2364 const Document* aDocument);
2367 * Like FindPresShellForDocument, but returns the shell's PresContext instead.
2369 static nsPresContext* FindPresContextForDocument(const Document* aDocument);
2372 * Returns the widget for this document if there is one. Looks at all ancestor
2373 * documents to try to find a widget, so for example this can still find a
2374 * widget for documents in display:none frames that have no presentation.
2376 * You should probably use WidgetForContent() instead of this, unless you have
2377 * a good reason to do otherwise.
2379 static nsIWidget* WidgetForDocument(const Document* aDocument);
2382 * Returns the appropriate widget for this element, if there is one. Unlike
2383 * WidgetForDocument(), this returns the correct widget for content in popups.
2385 * You should probably use this instead of WidgetForDocument().
2387 static nsIWidget* WidgetForContent(const nsIContent* aContent);
2390 * Returns a window renderer to use for the given document. Basically we
2391 * look up the document hierarchy for the first document which has
2392 * a presentation with an associated widget, and use that widget's
2393 * window renderer.
2395 * You should probably use WindowRendererForContent() instead of this, unless
2396 * you have a good reason to do otherwise.
2398 * @param aDoc the document for which to return a window renderer.
2399 * @param aAllowRetaining an outparam that states whether the returned
2400 * layer manager should be used for retained layers
2402 static mozilla::WindowRenderer* WindowRendererForDocument(
2403 const Document* aDoc);
2406 * Returns a window renderer to use for the given content. Unlike
2407 * WindowRendererForDocument(), this returns the correct window renderer for
2408 * content in popups.
2410 * You should probably use this instead of WindowRendererForDocument().
2412 static mozilla::WindowRenderer* WindowRendererForContent(
2413 const nsIContent* aContent);
2416 * Determine whether a content node is focused or not,
2418 * @param aContent the content node to check
2419 * @return true if the content node is focused, false otherwise.
2421 static bool IsFocusedContent(const nsIContent* aContent);
2424 * Returns true if calling execCommand with 'cut' or 'copy' arguments is
2425 * allowed for the given subject principal. These are only allowed if the user
2426 * initiated them (like with a mouse-click or key press).
2428 static bool IsCutCopyAllowed(Document* aDocument,
2429 nsIPrincipal& aSubjectPrincipal);
2432 * Returns true if CSSOM origin check should be skipped for WebDriver
2433 * based crawl to be able to collect data from cross-origin CSS style
2434 * sheets. This can be enabled by setting environment variable
2435 * MOZ_BYPASS_CSSOM_ORIGIN_CHECK.
2437 static bool BypassCSSOMOriginCheck() {
2438 #ifdef RELEASE_OR_BETA
2439 return false;
2440 #else
2441 return sBypassCSSOMOriginCheck;
2442 #endif
2446 * Fire mutation events for changes caused by parsing directly into a
2447 * context node.
2449 * @param aDoc the document of the node
2450 * @param aDest the destination node that got stuff appended to it
2451 * @param aOldChildCount the number of children the node had before parsing
2453 static void FireMutationEventsForDirectParsing(Document* aDoc,
2454 nsIContent* aDest,
2455 int32_t aOldChildCount);
2458 * Returns the in-process subtree root document in a document hierarchy.
2459 * This could be a chrome document.
2461 static Document* GetInProcessSubtreeRootDocument(Document* aDoc) {
2462 return const_cast<Document*>(
2463 GetInProcessSubtreeRootDocument(const_cast<const Document*>(aDoc)));
2465 static const Document* GetInProcessSubtreeRootDocument(const Document* aDoc);
2467 static void GetShiftText(nsAString& text);
2468 static void GetControlText(nsAString& text);
2469 static void GetCommandOrWinText(nsAString& text);
2470 static void GetAltText(nsAString& text);
2471 static void GetModifierSeparatorText(nsAString& text);
2474 * Returns if aContent has the 'scrollgrab' property.
2475 * aContent may be null (in this case false is returned).
2477 static bool HasScrollgrab(nsIContent* aContent);
2480 * Flushes the layout tree (recursively)
2482 * @param aWindow the window the flush should start at
2485 static void FlushLayoutForTree(nsPIDOMWindowOuter* aWindow);
2488 * Returns true if content with the given principal is allowed to use XUL
2489 * and XBL and false otherwise.
2491 static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
2494 * Perform cleanup that's appropriate for XPCOM shutdown.
2496 static void XPCOMShutdown();
2499 * Checks if internal PDF viewer is enabled.
2501 static bool IsPDFJSEnabled();
2504 * Checks to see whether the given principal is the internal PDF
2505 * viewer principal.
2507 static bool IsPDFJS(nsIPrincipal* aPrincipal);
2509 * Same, but from WebIDL bindings. Checks whether the subject principal is for
2510 * the internal PDF viewer or system JS.
2512 static bool IsSystemOrPDFJS(JSContext*, JSObject*);
2515 * Checks if internal SWF player is enabled.
2517 static bool IsSWFPlayerEnabled();
2519 enum DocumentViewerType {
2520 TYPE_UNSUPPORTED,
2521 TYPE_CONTENT,
2522 TYPE_FALLBACK,
2523 TYPE_UNKNOWN
2526 static already_AddRefed<nsIDocumentLoaderFactory> FindInternalDocumentViewer(
2527 const nsACString& aType, DocumentViewerType* aLoaderType = nullptr);
2530 * This helper method returns true if the aPattern pattern matches aValue.
2531 * aPattern should not contain leading and trailing slashes (/).
2532 * The pattern has to match the entire value not just a subset.
2533 * aDocument must be a valid pointer (not null).
2535 * This is following the HTML5 specification:
2536 * http://dev.w3.org/html5/spec/forms.html#attr-input-pattern
2538 * WARNING: This method mutates aPattern!
2540 * @param aValue the string to check.
2541 * @param aPattern the string defining the pattern.
2542 * @param aDocument the owner document of the element.
2543 * @param aHasMultiple whether or not there are multiple values.
2544 * @param aFlags the flags to use for creating the regexp object.
2545 * @result whether the given string is matches the pattern, or
2546 * Nothing() if the pattern couldn't be evaluated.
2548 static mozilla::Maybe<bool> IsPatternMatching(
2549 const nsAString& aValue, nsString&& aPattern, const Document* aDocument,
2550 bool aHasMultiple = false,
2551 JS::RegExpFlags aFlags = JS::RegExpFlag::UnicodeSets);
2554 * Calling this adds support for
2555 * ontouch* event handler DOM attributes.
2557 static void InitializeTouchEventTable();
2560 * Test whether the given URI always inherits a security context
2561 * from the document it comes from.
2563 static nsresult URIInheritsSecurityContext(nsIURI* aURI, bool* aResult);
2566 * Called before a channel is created to query whether the new
2567 * channel should inherit the principal.
2569 * The argument aLoadingPrincipal must not be null. The argument
2570 * aURI must be the URI of the new channel. If aInheritForAboutBlank
2571 * is true, then about:blank will be told to inherit the principal.
2572 * If aForceInherit is true, the new channel will be told to inherit
2573 * the principal no matter what.
2575 * The return value is whether the new channel should inherit
2576 * the principal.
2578 static bool ChannelShouldInheritPrincipal(nsIPrincipal* aLoadingPrincipal,
2579 nsIURI* aURI,
2580 bool aInheritForAboutBlank,
2581 bool aForceInherit);
2583 static nsresult Btoa(const nsAString& aBinaryData,
2584 nsAString& aAsciiBase64String);
2586 static nsresult Atob(const nsAString& aAsciiString, nsAString& aBinaryData);
2589 * Returns whether the input element passed in parameter has the autocomplete
2590 * functionality enabled. It is taking into account the form owner.
2591 * NOTE: the caller has to make sure autocomplete makes sense for the
2592 * element's type.
2594 * @param aInput the input element to check. NOTE: aInput can't be null.
2595 * @return whether the input element has autocomplete enabled.
2597 static bool IsAutocompleteEnabled(mozilla::dom::HTMLInputElement* aInput);
2599 enum AutocompleteAttrState : uint8_t {
2600 eAutocompleteAttrState_Unknown = 1,
2601 eAutocompleteAttrState_Invalid,
2602 eAutocompleteAttrState_Valid,
2605 * Parses the value of the autocomplete attribute into aResult, ensuring it's
2606 * composed of valid tokens, otherwise the value "" is used.
2607 * Note that this method is used for form fields, not on a <form> itself.
2609 * @return whether aAttr was valid and can be cached.
2611 static AutocompleteAttrState SerializeAutocompleteAttribute(
2612 const nsAttrValue* aAttr, nsAString& aResult,
2613 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown);
2615 /* Variation that is used to retrieve a dictionary of the parts of the
2616 * autocomplete attribute.
2618 * @return whether aAttr was valid and can be cached.
2620 static AutocompleteAttrState SerializeAutocompleteAttribute(
2621 const nsAttrValue* aAttr, mozilla::dom::AutocompleteInfo& aInfo,
2622 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown,
2623 bool aGrantAllValidValue = false);
2626 * This will parse aSource, to extract the value of the pseudo attribute
2627 * with the name specified in aName. See
2628 * http://www.w3.org/TR/xml-stylesheet/#NT-StyleSheetPI for the specification
2629 * which is used to parse aSource.
2631 * @param aSource the string to parse
2632 * @param aName the name of the attribute to get the value for
2633 * @param aValue [out] the value for the attribute with name specified in
2634 * aAttribute. Empty if the attribute isn't present.
2635 * @return true if the attribute exists and was successfully parsed.
2636 * false if the attribute doesn't exist, or has a malformed
2637 * value, such as an unknown or unterminated entity.
2639 static bool GetPseudoAttributeValue(const nsString& aSource, nsAtom* aName,
2640 nsAString& aValue);
2643 * Returns true if the language name is a version of JavaScript and
2644 * false otherwise
2646 static bool IsJavaScriptLanguage(const nsString& aName);
2648 static bool IsJavascriptMIMEType(const nsAString& aMIMEType);
2650 static void SplitMimeType(const nsAString& aValue, nsString& aType,
2651 nsString& aParams);
2654 * Check whether aContent and aOffsetInContent points in a selection range of
2655 * one of ranges in aSelection. If aSelection is collapsed, this always
2656 * return false even if aContent and aOffsetInContent is same as the collapsed
2657 * position.
2659 * @param aSelection The selection you want to check whether point is in a
2660 * range of it.
2661 * @param aNode The container node of the point which you want to check.
2662 * @param aOffset The offset in aNode of the point which you want to
2663 * check. aNode and aOffset can be computed with
2664 * UIEvent::GetRangeParentContentAndOffset() if you want to
2665 * check the click point.
2667 static bool IsPointInSelection(const mozilla::dom::Selection& aSelection,
2668 const nsINode& aNode, const uint32_t aOffset);
2671 * Takes a selection, and a text control element (<input> or <textarea>), and
2672 * returns the offsets in the text content corresponding to the selection.
2673 * The selection's anchor and focus must both be in the root node passed or a
2674 * descendant.
2676 * @param aSelection Selection to check
2677 * @param aRoot Root <input> or <textarea> element
2678 * @param aOutStartOffset Output start offset
2679 * @param aOutEndOffset Output end offset
2681 static void GetSelectionInTextControl(mozilla::dom::Selection* aSelection,
2682 Element* aRoot,
2683 uint32_t& aOutStartOffset,
2684 uint32_t& aOutEndOffset);
2687 * Takes a frame for anonymous content within a text control (<input> or
2688 * <textarea>), and returns an offset in the text content, adjusted for a
2689 * trailing <br> frame.
2691 * @param aOffsetFrame Frame for the text content in which the offset
2692 * lies
2693 * @param aOffset Offset as calculated by GetContentOffsetsFromPoint
2694 * @param aOutOffset Output adjusted offset
2696 * @see GetSelectionInTextControl for the original basis of this function.
2698 static int32_t GetAdjustedOffsetInTextControl(nsIFrame* aOffsetFrame,
2699 int32_t aOffset);
2702 * Returns pointer to HTML editor instance for the aPresContext when there is.
2703 * The HTML editor is shared by contenteditable elements or used in
2704 * designMode. When there are no contenteditable elements and the document
2705 * is not in designMode, this returns nullptr.
2707 static mozilla::HTMLEditor* GetHTMLEditor(nsPresContext* aPresContext);
2708 static mozilla::HTMLEditor* GetHTMLEditor(nsDocShell* aDocShell);
2711 * Returns pointer to a text editor if <input> or <textarea> element is
2712 * active element in the document for aPresContext, or pointer to HTML
2713 * editor if there is (i.e., even if non-editable element has focus or
2714 * nobody has focus). The reason is, HTML editor may handle some input
2715 * even if there is no active editing host.
2716 * Note that this does not return editor in descendant documents.
2718 static mozilla::EditorBase* GetActiveEditor(nsPresContext* aPresContext);
2719 static mozilla::EditorBase* GetActiveEditor(nsPIDOMWindowOuter* aWindow);
2722 * Returns `TextEditor` which manages `aAnonymousContent` if there is.
2723 * Note that this method returns `nullptr` if `TextEditor` for the
2724 * `aAnonymousContent` hasn't been created yet.
2726 static mozilla::TextEditor* GetTextEditorFromAnonymousNodeWithoutCreation(
2727 const nsIContent* aAnonymousContent);
2730 * Returns whether a node has an editable ancestor.
2732 * @param aNode The node to test.
2734 static bool IsNodeInEditableRegion(nsINode* aNode);
2737 * Returns a LogModule that logs debugging info from RFP functions.
2739 static mozilla::LogModule* ResistFingerprintingLog();
2742 * Returns a LogModule that dump calls from content script are logged to.
2743 * This can be enabled with the 'Dump' module, and is useful for synchronizing
2744 * content JS to other logging modules.
2746 static mozilla::LogModule* DOMDumpLog();
2749 * Returns whether a given header is forbidden for an XHR or fetch
2750 * request.
2752 static bool IsForbiddenRequestHeader(const nsACString& aHeader,
2753 const nsACString& aValue);
2756 * Returns whether a given header is forbidden for a system XHR
2757 * request.
2759 static bool IsForbiddenSystemRequestHeader(const nsACString& aHeader);
2762 * Checks whether the header overrides any http methods
2764 static bool IsOverrideMethodHeader(const nsACString& headerName);
2766 * Checks whether the header value contains any forbidden method
2768 static bool ContainsForbiddenMethod(const nsACString& headerValue);
2770 class ParsedRange {
2771 public:
2772 explicit ParsedRange(mozilla::Maybe<uint64_t> aStart,
2773 mozilla::Maybe<uint64_t> aEnd)
2774 : mStart(aStart), mEnd(aEnd) {}
2776 mozilla::Maybe<uint64_t> Start() const { return mStart; }
2777 mozilla::Maybe<uint64_t> End() const { return mEnd; }
2779 bool operator==(const ParsedRange& aOther) const {
2780 return Start() == aOther.Start() && End() == aOther.End();
2783 private:
2784 mozilla::Maybe<uint64_t> mStart;
2785 mozilla::Maybe<uint64_t> mEnd;
2789 * Parse a single range request and return a pair containing the resulting
2790 * start and end of the range.
2792 * See https://fetch.spec.whatwg.org/#simple-range-header-value
2794 static mozilla::Maybe<ParsedRange> ParseSingleRangeRequest(
2795 const nsACString& aHeaderValue, bool aAllowWhitespace);
2798 * Returns whether a given header has characters that aren't permitted
2800 static bool IsCorsUnsafeRequestHeaderValue(const nsACString& aHeaderValue);
2803 * Returns whether a given Accept header value is allowed
2804 * for a non-CORS XHR or fetch request.
2806 static bool IsAllowedNonCorsAccept(const nsACString& aHeaderValue);
2809 * Returns whether a given Content-Type header value is allowed
2810 * for a non-CORS XHR or fetch request.
2812 static bool IsAllowedNonCorsContentType(const nsACString& aHeaderValue);
2815 * Returns whether a given Content-Language or accept-language header value is
2816 * allowed for a non-CORS XHR or fetch request.
2818 static bool IsAllowedNonCorsLanguage(const nsACString& aHeaderValue);
2821 * Returns whether a given Range header value is allowed for a non-CORS XHR or
2822 * fetch request.
2824 static bool IsAllowedNonCorsRange(const nsACString& aHeaderValue);
2827 * Returns whether a given header and value is a CORS-safelisted request
2828 * header per https://fetch.spec.whatwg.org/#cors-safelisted-request-header
2830 static bool IsCORSSafelistedRequestHeader(const nsACString& aName,
2831 const nsACString& aValue);
2834 * Returns whether a given header is forbidden for an XHR or fetch
2835 * response.
2837 static bool IsForbiddenResponseHeader(const nsACString& aHeader);
2840 * Returns the inner window ID for the window associated with a request.
2842 static uint64_t GetInnerWindowID(nsIRequest* aRequest);
2845 * Returns the inner window ID for the window associated with a load group.
2847 static uint64_t GetInnerWindowID(nsILoadGroup* aLoadGroup);
2850 * Encloses aHost in brackets if it is an IPv6 address.
2852 static void MaybeFixIPv6Host(nsACString& aHost);
2855 * If the hostname for aURI is an IPv6 it encloses it in brackets,
2856 * otherwise it just outputs the hostname in aHost.
2858 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsAString& aHost);
2859 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsACString& aHost);
2860 static nsresult GetHostOrIPv6WithBrackets(nsIPrincipal* aPrincipal,
2861 nsACString& aHost);
2864 * Call the given callback on all remote children of the given top-level
2865 * window. Return Callstate::Stop from the callback to stop calling further
2866 * children.
2868 static void CallOnAllRemoteChildren(
2869 nsPIDOMWindowOuter* aWindow,
2870 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
2871 aCallback);
2874 * Given an IPCDataTransferImageContainer construct an imgIContainer for the
2875 * image encoded by the transfer item.
2877 static nsresult DeserializeTransferableDataImageContainer(
2878 const mozilla::dom::IPCTransferableDataImageContainer& aData,
2879 imgIContainer** aContainer);
2882 * Given a flavor obtained from an IPCDataTransferItem or nsITransferable,
2883 * returns true if we should treat the data as an image.
2885 static bool IsFlavorImage(const nsACString& aFlavor);
2887 static bool IPCTransferableDataItemHasKnownFlavor(
2888 const mozilla::dom::IPCTransferableDataItem& aItem);
2890 static nsresult IPCTransferableDataToTransferable(
2891 const mozilla::dom::IPCTransferableData& aTransferableData,
2892 bool aAddDataFlavor, nsITransferable* aTransferable,
2893 const bool aFilterUnknownFlavors);
2895 static nsresult IPCTransferableDataToTransferable(
2896 const mozilla::dom::IPCTransferableData& aTransferableData,
2897 const bool& aIsPrivateData, nsIPrincipal* aRequestingPrincipal,
2898 const nsContentPolicyType& aContentPolicyType, bool aAddDataFlavor,
2899 nsITransferable* aTransferable, const bool aFilterUnknownFlavors);
2901 static nsresult IPCTransferableToTransferable(
2902 const mozilla::dom::IPCTransferable& aIPCTransferable,
2903 bool aAddDataFlavor, nsITransferable* aTransferable,
2904 const bool aFilterUnknownFlavors);
2906 static nsresult IPCTransferableDataItemToVariant(
2907 const mozilla::dom::IPCTransferableDataItem& aItem,
2908 nsIWritableVariant* aVariant);
2910 static void TransferablesToIPCTransferableDatas(
2911 nsIArray* aTransferables,
2912 nsTArray<mozilla::dom::IPCTransferableData>& aIPC, bool aInSyncMessage,
2913 mozilla::dom::ContentParent* aParent);
2915 static void TransferableToIPCTransferableData(
2916 nsITransferable* aTransferable,
2917 mozilla::dom::IPCTransferableData* aTransferableData, bool aInSyncMessage,
2918 mozilla::dom::ContentParent* aParent);
2920 static void TransferableToIPCTransferable(
2921 nsITransferable* aTransferable,
2922 mozilla::dom::IPCTransferable* aIPCTransferable, bool aInSyncMessage,
2923 mozilla::dom::ContentParent* aParent);
2926 * Get the pixel data from the given source surface and return it as a
2927 * BigBuffer. The length and stride will be assigned from the surface.
2929 static mozilla::Maybe<mozilla::ipc::BigBuffer> GetSurfaceData(
2930 mozilla::gfx::DataSourceSurface&, size_t* aLength, int32_t* aStride);
2932 static mozilla::Maybe<mozilla::dom::IPCImage> SurfaceToIPCImage(
2933 mozilla::gfx::DataSourceSurface&);
2934 static already_AddRefed<mozilla::gfx::DataSourceSurface> IPCImageToSurface(
2935 mozilla::dom::IPCImage&&);
2937 // Helpers shared by the implementations of nsContentUtils methods and
2938 // nsIDOMWindowUtils methods.
2939 static mozilla::Modifiers GetWidgetModifiers(int32_t aModifiers);
2940 static nsIWidget* GetWidget(mozilla::PresShell* aPresShell, nsPoint* aOffset);
2941 static int16_t GetButtonsFlagForButton(int32_t aButton);
2942 static mozilla::LayoutDeviceIntPoint ToWidgetPoint(
2943 const mozilla::CSSPoint& aPoint, const nsPoint& aOffset,
2944 nsPresContext* aPresContext);
2945 static nsView* GetViewToDispatchEvent(nsPresContext* aPresContext,
2946 mozilla::PresShell** aPresShell);
2949 * Synthesize a mouse event to the given widget
2950 * (see nsIDOMWindowUtils.sendMouseEvent).
2952 MOZ_CAN_RUN_SCRIPT
2953 static nsresult SendMouseEvent(
2954 mozilla::PresShell* aPresShell, const nsAString& aType, float aX,
2955 float aY, int32_t aButton, int32_t aButtons, int32_t aClickCount,
2956 int32_t aModifiers, bool aIgnoreRootScrollFrame, float aPressure,
2957 unsigned short aInputSourceArg, uint32_t aIdentifier, bool aToWindow,
2958 mozilla::PreventDefaultResult* aPreventDefault,
2959 bool aIsDOMEventSynthesized, bool aIsWidgetEventSynthesized);
2961 static void FirePageShowEventForFrameLoaderSwap(
2962 nsIDocShellTreeItem* aItem,
2963 mozilla::dom::EventTarget* aChromeEventHandler, bool aFireIfShowing,
2964 bool aOnlySystemGroup = false);
2966 static void FirePageHideEventForFrameLoaderSwap(
2967 nsIDocShellTreeItem* aItem,
2968 mozilla::dom::EventTarget* aChromeEventHandler,
2969 bool aOnlySystemGroup = false);
2971 static already_AddRefed<nsPIWindowRoot> GetWindowRoot(Document* aDoc);
2974 * If there is a Referrer-Policy response header in |aChannel|, parse a
2975 * referrer policy from the header.
2977 * @param the channel from which to get the Referrer-Policy header
2978 * @return referrer policy from the response header in aChannel
2980 static mozilla::dom::ReferrerPolicy GetReferrerPolicyFromChannel(
2981 nsIChannel* aChannel);
2983 static bool IsNonSubresourceRequest(nsIChannel* aChannel);
2985 static bool IsNonSubresourceInternalPolicyType(nsContentPolicyType aType);
2987 public:
2989 * Returns true if this window's channel has been marked as a third-party
2990 * tracking resource.
2992 static bool IsThirdPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
2995 * Returns true if this window's channel has been marked as a first-party
2996 * tracking resource.
2998 static bool IsFirstPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
3001 * Serializes a HTML nsINode into its markup representation.
3003 static bool SerializeNodeToMarkup(nsINode* aRoot, bool aDescendentsOnly,
3004 nsAString& aOut);
3007 * Returns true iff the provided JSObject is a global, and its URI matches
3008 * the provided about: URI.
3009 * @param aGlobal the JSObject whose URI to check, if it is a global.
3010 * @param aUri the URI to match, e.g. "about:feeds"
3012 static bool IsSpecificAboutPage(JSObject* aGlobal, const char* aUri);
3014 static void SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible);
3017 * Try to find the docshell corresponding to the given event target.
3019 static nsIDocShell* GetDocShellForEventTarget(
3020 mozilla::dom::EventTarget* aTarget);
3023 * Returns true if the "HTTPS state" of the document should be "modern". See:
3025 * https://html.spec.whatwg.org/#concept-document-https-state
3026 * https://fetch.spec.whatwg.org/#concept-response-https-state
3028 static bool HttpsStateIsModern(Document* aDocument);
3031 * Returns true if the channel is for top-level window and is over secure
3032 * context.
3033 * https://github.com/whatwg/html/issues/4930 tracks the spec side of this.
3035 static bool ComputeIsSecureContext(nsIChannel* aChannel);
3038 * Try to upgrade an element.
3039 * https://html.spec.whatwg.org/multipage/custom-elements.html#concept-try-upgrade
3041 static void TryToUpgradeElement(Element* aElement);
3044 * Creates a new XUL or XHTML element applying any appropriate custom element
3045 * definition.
3047 * If aFromParser != FROM_PARSER_FRAGMENT, a nested event loop permits
3048 * arbitrary changes to the world before this function returns. This should
3049 * probably just be MOZ_CAN_RUN_SCRIPT - bug 1543259.
3051 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult NewXULOrHTMLElement(
3052 Element** aResult, mozilla::dom::NodeInfo* aNodeInfo,
3053 mozilla::dom::FromParser aFromParser, nsAtom* aIsAtom,
3054 mozilla::dom::CustomElementDefinition* aDefinition);
3056 static mozilla::dom::CustomElementRegistry* GetCustomElementRegistry(
3057 Document*);
3060 * Looking up a custom element definition.
3061 * https://html.spec.whatwg.org/#look-up-a-custom-element-definition
3063 static mozilla::dom::CustomElementDefinition* LookupCustomElementDefinition(
3064 Document* aDoc, nsAtom* aNameAtom, uint32_t aNameSpaceID,
3065 nsAtom* aTypeAtom);
3067 static void RegisterCallbackUpgradeElement(Element* aElement,
3068 nsAtom* aTypeName);
3070 static void RegisterUnresolvedElement(Element* aElement, nsAtom* aTypeName);
3071 static void UnregisterUnresolvedElement(Element* aElement);
3073 static void EnqueueUpgradeReaction(
3074 Element* aElement, mozilla::dom::CustomElementDefinition* aDefinition);
3076 static void EnqueueLifecycleCallback(
3077 mozilla::dom::ElementCallbackType aType, Element* aCustomElement,
3078 const mozilla::dom::LifecycleCallbackArgs& aArgs,
3079 mozilla::dom::CustomElementDefinition* aDefinition = nullptr);
3081 static mozilla::dom::CustomElementFormValue ConvertToCustomElementFormValue(
3082 const mozilla::dom::Nullable<
3083 mozilla::dom::OwningFileOrUSVStringOrFormData>& aState);
3085 static mozilla::dom::Nullable<mozilla::dom::OwningFileOrUSVStringOrFormData>
3086 ExtractFormAssociatedCustomElementValue(
3087 nsIGlobalObject* aGlobal,
3088 const mozilla::dom::CustomElementFormValue& aCEValue);
3091 * Appends all "document level" native anonymous content subtree roots for
3092 * aDocument to aElements. Document level NAC subtrees are those created
3093 * by ancestor frames of the document element's primary frame, such as
3094 * the scrollbar elements created by the root scroll frame.
3096 static void AppendDocumentLevelNativeAnonymousContentTo(
3097 Document* aDocument, nsTArray<nsIContent*>& aElements);
3100 * Appends all native anonymous content subtree roots generated by `aContent`
3101 * to `aKids`.
3103 * See `AllChildrenIterator` for the description of the `aFlags` parameter.
3105 static void AppendNativeAnonymousChildren(const nsIContent* aContent,
3106 nsTArray<nsIContent*>& aKids,
3107 uint32_t aFlags);
3110 * Query triggeringPrincipal if there's a 'triggeringprincipal' attribute on
3111 * aLoadingNode, if no such attribute is specified, aDefaultPrincipal is
3112 * returned if it is provided, otherwise the NodePrincipal of aLoadingNode is
3113 * returned.
3115 * Return true if aLoadingNode has a 'triggeringprincipal' attribute, and
3116 * the value 'triggeringprincipal' is also successfully deserialized,
3117 * otherwise return false.
3119 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3120 nsIPrincipal* aDefaultPrincipal,
3121 nsIPrincipal** aTriggeringPrincipal);
3123 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3124 nsIPrincipal** aTriggeringPrincipal) {
3125 return QueryTriggeringPrincipal(aLoadingNode, nullptr,
3126 aTriggeringPrincipal);
3129 // Returns whether the image for the given URI and triggering principal is
3130 // already available. Ideally this should exactly match the "list of available
3131 // images" in the HTML spec, but our implementation of that at best only
3132 // resembles it.
3133 static bool IsImageAvailable(nsIContent*, nsIURI*,
3134 nsIPrincipal* aDefaultTriggeringPrincipal,
3135 mozilla::CORSMode);
3136 static bool IsImageAvailable(nsIURI*, nsIPrincipal* aTriggeringPrincipal,
3137 mozilla::CORSMode, Document*);
3140 * Returns the content policy type that should be used for loading images
3141 * for displaying in the UI. The sources of such images can be <xul:image>,
3142 * <xul:menuitem> on OSX where we load the image through nsMenuItemIconX, etc.
3144 static void GetContentPolicyTypeForUIImageLoading(
3145 nsIContent* aLoadingNode, nsIPrincipal** aTriggeringPrincipal,
3146 nsContentPolicyType& aContentPolicyType, uint64_t* aRequestContextID);
3148 static nsresult CreateJSValueFromSequenceOfObject(
3149 JSContext* aCx, const mozilla::dom::Sequence<JSObject*>& aTransfer,
3150 JS::MutableHandle<JS::Value> aValue);
3153 * This implements the structured cloning algorithm as described by
3154 * https://html.spec.whatwg.org/#structured-cloning.
3156 static void StructuredClone(
3157 JSContext* aCx, nsIGlobalObject* aGlobal, JS::Handle<JS::Value> aValue,
3158 const mozilla::dom::StructuredSerializeOptions& aOptions,
3159 JS::MutableHandle<JS::Value> aRetval, mozilla::ErrorResult& aError);
3162 * Returns true if reserved key events should be prevented from being sent
3163 * to their target. Instead, the key event should be handled by chrome only.
3165 static bool ShouldBlockReservedKeys(mozilla::WidgetKeyboardEvent* aKeyEvent);
3168 * Returns one of the nsIObjectLoadingContent::TYPE_ values describing the
3169 * content type which will be used for the given MIME type when loaded within
3170 * an nsObjectLoadingContent.
3172 * NOTE: This method doesn't take capabilities into account. The caller must
3173 * take that into account.
3175 * @param aMIMEType The MIME type of the document being loaded.
3176 * @param aNoFakePlugin If false then this method should consider JS plugins.
3178 static uint32_t HtmlObjectContentTypeForMIMEType(const nsCString& aMIMEType,
3179 bool aNoFakePlugin);
3182 * Detect whether a string is a local-url.
3183 * https://drafts.csswg.org/css-values/#local-urls
3185 static bool IsLocalRefURL(const nsAString& aString);
3188 * Compose a tab id with process id and a serial number.
3190 static uint64_t GenerateTabId();
3193 * Compose a browser id with process id and a serial number.
3195 static uint64_t GenerateBrowserId();
3198 * Generate an id for a BrowsingContext using a range of serial
3199 * numbers reserved for the current process.
3201 static uint64_t GenerateBrowsingContextId();
3204 * Generate an id using a range of serial numbers reserved for the current
3205 * process. aId should be a counter that's incremented every time
3206 * GenerateProcessSpecificId is called.
3208 static uint64_t GenerateProcessSpecificId(uint64_t aId);
3210 static std::tuple<uint64_t, uint64_t> SplitProcessSpecificId(uint64_t aId);
3213 * Generate a window ID which is unique across processes and will never be
3214 * recycled.
3216 static uint64_t GenerateWindowId();
3219 * Generate an ID for a load which is unique across processes and will never
3220 * be recycled.
3222 static uint64_t GenerateLoadIdentifier();
3225 * Determine whether or not the user is currently interacting with the web
3226 * browser. This method is safe to call from off of the main thread.
3228 static bool GetUserIsInteracting();
3230 // Alternate data MIME type used by the ScriptLoader to register and read
3231 // bytecode out of the nsCacheInfoChannel.
3232 [[nodiscard]] static bool InitJSBytecodeMimeType();
3233 static nsCString& JSScriptBytecodeMimeType() {
3234 MOZ_ASSERT(sJSScriptBytecodeMimeType);
3235 return *sJSScriptBytecodeMimeType;
3237 static nsCString& JSModuleBytecodeMimeType() {
3238 MOZ_ASSERT(sJSModuleBytecodeMimeType);
3239 return *sJSModuleBytecodeMimeType;
3243 * Checks if the passed-in name is one of the special names: "_blank", "_top",
3244 * "_parent" or "_self".
3246 static bool IsSpecialName(const nsAString& aName);
3249 * Checks if the passed-in name should override an existing name on the
3250 * window. Values which should not override include: "", "_blank", "_top",
3251 * "_parent" and "_self".
3253 static bool IsOverridingWindowName(const nsAString& aName);
3256 * If there is a SourceMap (higher precedence) or X-SourceMap (lower
3257 * precedence) response header in |aChannel|, set |aResult| to the
3258 * header's value and return true. Otherwise, return false.
3260 * @param aChannel The HTTP channel
3261 * @param aResult The string result.
3263 static bool GetSourceMapURL(nsIHttpChannel* aChannel, nsACString& aResult);
3266 * Returns true if the passed-in mesasge is a pending InputEvent.
3268 * @param aMsg The message to check
3270 static bool IsMessageInputEvent(const IPC::Message& aMsg);
3273 * Returns true if the passed-in message is a critical InputEvent.
3275 * @param aMsg The message to check
3277 static bool IsMessageCriticalInputEvent(const IPC::Message& aMsg);
3279 static void AsyncPrecreateStringBundles();
3281 static bool ContentIsLink(nsIContent* aContent);
3283 static already_AddRefed<mozilla::dom::ContentFrameMessageManager>
3284 TryGetBrowserChildGlobal(nsISupports* aFrom);
3286 // Get a serial number for a newly created inner or outer window.
3287 static uint32_t InnerOrOuterWindowCreated();
3288 // Record that an inner or outer window has been destroyed.
3289 static void InnerOrOuterWindowDestroyed();
3290 // Get the current number of inner or outer windows.
3291 static int32_t GetCurrentInnerOrOuterWindowCount() {
3292 return sInnerOrOuterWindowCount;
3295 // Return an anonymized URI so that it can be safely exposed publicly.
3296 static nsresult AnonymizeURI(nsIURI* aURI, nsCString& aAnonymizedURI);
3299 * Serializes a JSON-like JS::Value into a string.
3300 * Cases where JSON.stringify would return undefined are handled according to
3301 * the |aBehavior| argument:
3303 * - If it is |UndefinedIsNullStringLiteral|, the string "null" is returned.
3304 * - If it is |UndefinedIsVoidString|, the void string is returned.
3306 * The |UndefinedIsNullStringLiteral| case is likely not desirable, but is
3307 * retained for now for historical reasons.
3308 * Usage:
3309 * nsAutoString serializedValue;
3310 * nsContentUtils::StringifyJSON(cx, value, serializedValue, behavior);
3312 static bool StringifyJSON(JSContext* aCx, JS::Handle<JS::Value> aValue,
3313 nsAString& aOutStr, JSONBehavior aBehavior);
3316 * Returns true if the top level ancestor content document of aDocument hasn't
3317 * yet had the first contentful paint and there is a high priority event
3318 * pending in the main thread.
3320 static bool HighPriorityEventPendingForTopLevelDocumentBeforeContentfulPaint(
3321 Document* aDocument);
3324 * Get the inner window corresponding to the incumbent global, including
3325 * mapping extension content script globals to the attached window.
3327 * Returns null if the incumbent global doesn't correspond to an inner window.
3329 static nsGlobalWindowInner* IncumbentInnerWindow();
3332 * Get the inner window corresponding to the entry global, including mapping
3333 * extension content script globals to the attached window.
3335 * Returns null if the entry global doesn't correspond to an inner window.
3337 static nsGlobalWindowInner* EntryInnerWindow();
3340 * Return safe area insets of window that defines as
3341 * https://drafts.csswg.org/css-env-1/#safe-area-insets.
3343 static mozilla::ScreenIntMargin GetWindowSafeAreaInsets(
3344 nsIScreen* aScreen, const mozilla::ScreenIntMargin& aSafeareaInsets,
3345 const mozilla::LayoutDeviceIntRect& aWindowRect);
3347 struct SubresourceCacheValidationInfo {
3348 // The expiration time, in seconds, if known.
3349 mozilla::Maybe<uint32_t> mExpirationTime;
3350 bool mMustRevalidate = false;
3354 * Gets cache validation info for subresources such as images or CSS
3355 * stylesheets.
3357 static SubresourceCacheValidationInfo GetSubresourceCacheValidationInfo(
3358 nsIRequest*, nsIURI*);
3360 static uint32_t SecondsFromPRTime(PRTime aTime) {
3361 return uint32_t(int64_t(aTime) / int64_t(PR_USEC_PER_SEC));
3365 * Converts the given URL to a string and truncates it to the given length.
3367 * Returns an empty string if aURL is null.
3369 static nsCString TruncatedURLForDisplay(nsIURI* aURL, size_t aMaxLen = 128);
3372 * Anonymize the given id by hashing it with the provided origin. The
3373 * resulting id will have the same length as the one that was passed in.
3375 enum class OriginFormat {
3376 Base64,
3377 Plain,
3380 static nsresult AnonymizeId(nsAString& aId, const nsACString& aOriginKey,
3381 OriginFormat aFormat = OriginFormat::Base64);
3384 * Return true if we should hide the synthetic browsing context for <object>
3385 * or <embed> images in synthetic documents.
3387 static bool ShouldHideObjectOrEmbedImageDocument();
3390 * Returns the object type that the object loading content will actually use
3391 * to load the resource. Used for ORB and loading images into synthetic
3392 * documents.
3394 static uint32_t ResolveObjectType(uint32_t aType);
3397 * Create and load the string bundle for the 'aFile'.
3398 * This API is used to preload the string bundle on the main thread so later
3399 * other thread could access it.
3401 static nsresult EnsureAndLoadStringBundle(PropertiesFile aFile);
3404 * The method asks nsIAppShell to prioritize Gecko's internal tasks over
3405 * the OS level tasks for a short period of time.
3407 static void RequestGeckoTaskBurst();
3409 static void SetMayHaveFormCheckboxStateChangeListeners() {
3410 sMayHaveFormCheckboxStateChangeListeners = true;
3413 static bool MayHaveFormCheckboxStateChangeListeners() {
3414 return sMayHaveFormCheckboxStateChangeListeners;
3417 static void SetMayHaveFormRadioStateChangeListeners() {
3418 sMayHaveFormRadioStateChangeListeners = true;
3421 static bool MayHaveFormRadioStateChangeListeners() {
3422 return sMayHaveFormRadioStateChangeListeners;
3426 * Returns the closest link element in the flat tree of aContent if there's
3427 * one, otherwise returns nullptr.
3429 static nsIContent* GetClosestLinkInFlatTree(nsIContent* aContent);
3431 static bool IsExternalProtocol(nsIURI* aURI);
3434 * Add an element to a list, keeping the list sorted by tree order.
3435 * Can take a potential ancestor of the elements in order to speed up
3436 * tree-order comparisons, if such an ancestor exists.
3437 * Returns true if the element is appended to the end of the list.
3439 template <typename ElementType, typename ElementPtr>
3440 static bool AddElementToListByTreeOrder(nsTArray<ElementType>& aList,
3441 ElementPtr aChild,
3442 nsIContent* aCommonAncestor);
3445 * Compares the position of aContent1 and aContent2 in the document
3446 * @param aContent1 First content to compare.
3447 * @param aContent2 Second content to compare.
3448 * @param aCommonAncestor Potential ancestor of the contents, if one exists.
3449 * This is only a hint; if it's not an ancestor of
3450 * aContent1 or aContent2, this function will still
3451 * work, but it will be slower than normal.
3452 * @return < 0 if aContent1 is before aContent2,
3453 * > 0 if aContent1 is after aContent2,
3454 * 0 otherwise
3456 static int32_t CompareTreePosition(nsIContent* aContent1,
3457 nsIContent* aContent2,
3458 const nsIContent* aCommonAncestor);
3460 private:
3461 static bool InitializeEventTable();
3463 static nsresult EnsureStringBundle(PropertiesFile aFile);
3465 static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
3466 nsIPrincipal* aPrincipal);
3468 static nsresult WrapNative(JSContext* cx, nsISupports* native,
3469 nsWrapperCache* cache, const nsIID* aIID,
3470 JS::MutableHandle<JS::Value> vp,
3471 bool aAllowWrapping);
3473 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3474 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult DispatchEvent(
3475 Document* aDoc, mozilla::dom::EventTarget* aTarget,
3476 const nsAString& aEventName, CanBubble, Cancelable, Composed, Trusted,
3477 bool* aDefaultAction = nullptr,
3478 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3480 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3481 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult DispatchEvent(
3482 Document* aDoc, mozilla::dom::EventTarget* aTarget,
3483 mozilla::WidgetEvent& aWidgetEvent, EventMessage aEventMessage, CanBubble,
3484 Cancelable, Trusted, bool* aDefaultAction = nullptr,
3485 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3487 static void InitializeModifierStrings();
3489 static void DropFragmentParsers();
3491 static bool MatchClassNames(mozilla::dom::Element* aElement,
3492 int32_t aNamespaceID, nsAtom* aAtom, void* aData);
3493 static void DestroyClassNameArray(void* aData);
3494 static void* AllocClassMatchingInfo(nsINode* aRootNode,
3495 const nsString* aClasses);
3497 static mozilla::EventClassID GetEventClassIDFromMessage(
3498 EventMessage aEventMessage);
3500 // Fills in aInfo with the tokens from the supplied autocomplete attribute.
3501 static AutocompleteAttrState InternalSerializeAutocompleteAttribute(
3502 const nsAttrValue* aAttrVal, mozilla::dom::AutocompleteInfo& aInfo,
3503 bool aGrantAllValidValue = false);
3505 static mozilla::CallState CallOnAllRemoteChildren(
3506 mozilla::dom::MessageBroadcaster* aManager,
3507 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
3508 aCallback);
3510 static nsINode* GetCommonAncestorHelper(nsINode* aNode1, nsINode* aNode2);
3511 static nsIContent* GetCommonFlattenedTreeAncestorHelper(
3512 nsIContent* aContent1, nsIContent* aContent2);
3514 static nsIXPConnect* sXPConnect;
3516 static nsIScriptSecurityManager* sSecurityManager;
3517 static nsIPrincipal* sSystemPrincipal;
3518 static nsIPrincipal* sNullSubjectPrincipal;
3520 static nsIConsoleService* sConsoleService;
3522 static nsIStringBundleService* sStringBundleService;
3523 class nsContentUtilsReporter;
3525 static nsIContentPolicy* sContentPolicyService;
3526 static bool sTriedToGetContentPolicy;
3528 static mozilla::StaticRefPtr<nsIBidiKeyboard> sBidiKeyboard;
3530 static bool sInitialized;
3531 static uint32_t sScriptBlockerCount;
3532 static uint32_t sDOMNodeRemovedSuppressCount;
3534 // Not an nsCOMArray because removing elements from those is slower
3535 static AutoTArray<nsCOMPtr<nsIRunnable>, 8>* sBlockedScriptRunners;
3536 static uint32_t sRunnersCountAtFirstBlocker;
3537 static uint32_t sScriptBlockerCountWhereRunnersPrevented;
3539 static nsIInterfaceRequestor* sSameOriginChecker;
3541 static bool sIsHandlingKeyBoardEvent;
3542 #ifndef RELEASE_OR_BETA
3543 static bool sBypassCSSOMOriginCheck;
3544 #endif
3546 class UserInteractionObserver;
3547 static UserInteractionObserver* sUserInteractionObserver;
3549 static nsHtml5StringParser* sHTMLFragmentParser;
3550 static nsParser* sXMLFragmentParser;
3551 static nsIFragmentContentSink* sXMLFragmentSink;
3554 * True if there's a fragment parser activation on the stack.
3556 static bool sFragmentParsingActive;
3558 static nsString* sShiftText;
3559 static nsString* sControlText;
3560 static nsString* sCommandOrWinText;
3561 static nsString* sAltText;
3562 static nsString* sModifierSeparator;
3564 // Alternate data mime types, used by the ScriptLoader to register and read
3565 // the bytecode out of the nsCacheInfoChannel.
3566 static nsCString* sJSScriptBytecodeMimeType;
3567 static nsCString* sJSModuleBytecodeMimeType;
3569 static mozilla::LazyLogModule gResistFingerprintingLog;
3570 static mozilla::LazyLogModule sDOMDumpLog;
3572 static int32_t sInnerOrOuterWindowCount;
3573 static uint32_t sInnerOrOuterWindowSerialCounter;
3575 static bool sMayHaveFormCheckboxStateChangeListeners;
3576 static bool sMayHaveFormRadioStateChangeListeners;
3579 /* static */ inline ExtContentPolicyType
3580 nsContentUtils::InternalContentPolicyTypeToExternal(nsContentPolicyType aType) {
3581 switch (aType) {
3582 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
3583 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
3584 case nsIContentPolicy::TYPE_INTERNAL_MODULE:
3585 case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD:
3586 case nsIContentPolicy::TYPE_INTERNAL_WORKER:
3587 case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
3588 case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
3589 case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS:
3590 case nsIContentPolicy::TYPE_INTERNAL_WORKER_STATIC_MODULE:
3591 case nsIContentPolicy::TYPE_INTERNAL_AUDIOWORKLET:
3592 case nsIContentPolicy::TYPE_INTERNAL_PAINTWORKLET:
3593 case nsIContentPolicy::TYPE_INTERNAL_CHROMEUTILS_COMPILED_SCRIPT:
3594 case nsIContentPolicy::TYPE_INTERNAL_FRAME_MESSAGEMANAGER_SCRIPT:
3595 return ExtContentPolicy::TYPE_SCRIPT;
3597 case nsIContentPolicy::TYPE_INTERNAL_EMBED:
3598 case nsIContentPolicy::TYPE_INTERNAL_OBJECT:
3599 return ExtContentPolicy::TYPE_OBJECT;
3601 case nsIContentPolicy::TYPE_INTERNAL_FRAME:
3602 case nsIContentPolicy::TYPE_INTERNAL_IFRAME:
3603 return ExtContentPolicy::TYPE_SUBDOCUMENT;
3605 case nsIContentPolicy::TYPE_INTERNAL_AUDIO:
3606 case nsIContentPolicy::TYPE_INTERNAL_VIDEO:
3607 case nsIContentPolicy::TYPE_INTERNAL_TRACK:
3608 return ExtContentPolicy::TYPE_MEDIA;
3610 case nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST:
3611 case nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE:
3612 return ExtContentPolicy::TYPE_XMLHTTPREQUEST;
3614 case nsIContentPolicy::TYPE_INTERNAL_IMAGE:
3615 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD:
3616 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON:
3617 return ExtContentPolicy::TYPE_IMAGE;
3619 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
3620 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
3621 return ExtContentPolicy::TYPE_STYLESHEET;
3623 case nsIContentPolicy::TYPE_INTERNAL_DTD:
3624 case nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD:
3625 return ExtContentPolicy::TYPE_DTD;
3627 case nsIContentPolicy::TYPE_INTERNAL_FONT_PRELOAD:
3628 return ExtContentPolicy::TYPE_FONT;
3630 case nsIContentPolicy::TYPE_INTERNAL_FETCH_PRELOAD:
3631 return ExtContentPolicy::TYPE_FETCH;
3633 default:
3634 return static_cast<ExtContentPolicyType>(aType);
3638 namespace mozilla {
3639 std::ostream& operator<<(
3640 std::ostream& aOut,
3641 const mozilla::PreventDefaultResult aPreventDefaultResult);
3642 } // namespace mozilla
3644 class MOZ_RAII nsAutoScriptBlocker {
3645 public:
3646 explicit nsAutoScriptBlocker() { nsContentUtils::AddScriptBlocker(); }
3647 ~nsAutoScriptBlocker() { nsContentUtils::RemoveScriptBlocker(); }
3649 private:
3652 class MOZ_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved
3653 : public nsAutoScriptBlocker {
3654 public:
3655 nsAutoScriptBlockerSuppressNodeRemoved() {
3656 ++nsContentUtils::sDOMNodeRemovedSuppressCount;
3658 ~nsAutoScriptBlockerSuppressNodeRemoved() {
3659 --nsContentUtils::sDOMNodeRemovedSuppressCount;
3663 namespace mozilla::dom {
3665 class TreeOrderComparator {
3666 public:
3667 bool Equals(nsINode* aElem1, nsINode* aElem2) const {
3668 return aElem1 == aElem2;
3670 bool LessThan(nsINode* aElem1, nsINode* aElem2) const {
3671 return nsContentUtils::PositionIsBefore(aElem1, aElem2);
3675 } // namespace mozilla::dom
3677 #define NS_INTERFACE_MAP_ENTRY_TEAROFF(_interface, _allocator) \
3678 NS_INTERFACE_MAP_ENTRY_TEAROFF_AMBIGUOUS(_interface, _interface, _allocator)
3680 #define NS_INTERFACE_MAP_ENTRY_TEAROFF_AMBIGUOUS(_interface, _implClass, \
3681 _allocator) \
3682 if (aIID.Equals(NS_GET_IID(_interface))) { \
3683 foundInterface = static_cast<_implClass*>(_allocator); \
3684 if (!foundInterface) { \
3685 *aInstancePtr = nullptr; \
3686 return NS_ERROR_OUT_OF_MEMORY; \
3688 } else
3691 * In the following helper macros we exploit the fact that the result of a
3692 * series of additions will not be finite if any one of the operands in the
3693 * series is not finite.
3695 #define NS_ENSURE_FINITE(f, rv) \
3696 if (!std::isfinite(f)) { \
3697 return (rv); \
3700 #define NS_ENSURE_FINITE2(f1, f2, rv) \
3701 if (!std::isfinite((f1) + (f2))) { \
3702 return (rv); \
3705 #define NS_ENSURE_FINITE4(f1, f2, f3, f4, rv) \
3706 if (!std::isfinite((f1) + (f2) + (f3) + (f4))) { \
3707 return (rv); \
3710 #define NS_ENSURE_FINITE5(f1, f2, f3, f4, f5, rv) \
3711 if (!std::isfinite((f1) + (f2) + (f3) + (f4) + (f5))) { \
3712 return (rv); \
3715 #define NS_ENSURE_FINITE6(f1, f2, f3, f4, f5, f6, rv) \
3716 if (!std::isfinite((f1) + (f2) + (f3) + (f4) + (f5) + (f6))) { \
3717 return (rv); \
3720 // Deletes a linked list iteratively to avoid blowing up the stack (bug 460444).
3721 #define NS_CONTENT_DELETE_LIST_MEMBER(type_, ptr_, member_) \
3723 type_* cur = (ptr_)->member_; \
3724 (ptr_)->member_ = nullptr; \
3725 while (cur) { \
3726 type_* next = cur->member_; \
3727 cur->member_ = nullptr; \
3728 delete cur; \
3729 cur = next; \
3733 #endif /* nsContentUtils_h___ */