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/. */
6 
7 /* A namespace class for static content utilities. */
8 
9 #ifndef nsContentUtils_h___
10 #define nsContentUtils_h___
11 
12 #if defined(XP_WIN)
13 #include <float.h>
14 #endif
15 
16 #if defined(SOLARIS)
17 #include <ieeefp.h>
18 #endif
19 
20 #include "js/TypeDecls.h"
21 #include "js/Value.h"
22 #include "js/RootingAPI.h"
23 #include "mozilla/EventForwards.h"
24 #include "mozilla/GuardObjects.h"
25 #include "mozilla/TimeStamp.h"
26 #include "nsContentListDeclarations.h"
27 #include "nsMathUtils.h"
28 #include "nsTArrayForwardDeclare.h"
29 #include "Units.h"
30 #include "mozilla/dom/AutocompleteInfoBinding.h"
31 #include "mozilla/dom/BindingDeclarations.h" // For CallerType
32 #include "mozilla/dom/ScriptSettings.h"
33 #include "mozilla/FloatingPoint.h"
34 #include "mozilla/net/ReferrerPolicy.h"
35 #include "mozilla/Logging.h"
36 #include "mozilla/NotNull.h"
37 #include "nsIContentPolicy.h"
38 #include "nsIDocument.h"
39 #include "nsPIDOMWindow.h"
40 
41 #if defined(XP_WIN)
42 // Undefine LoadImage to prevent naming conflict with Windows.
43 #undef LoadImage
44 #endif
45 
46 class imgICache;
47 class imgIContainer;
48 class imgINotificationObserver;
49 class imgIRequest;
50 class imgLoader;
51 class imgRequestProxy;
52 class nsAutoScriptBlockerSuppressNodeRemoved;
53 class nsHtml5StringParser;
54 class nsIChannel;
55 class nsIConsoleService;
56 class nsIContent;
57 class nsIContentPolicy;
58 class nsIContentSecurityPolicy;
59 class nsIDocShellTreeItem;
60 class nsIDocumentLoaderFactory;
61 class nsIDOMDocument;
62 class nsIDOMDocumentFragment;
63 class nsIDOMEvent;
64 class nsIDOMHTMLInputElement;
65 class nsIDOMKeyEvent;
66 class nsIDOMNode;
67 class nsIDragSession;
68 class nsIEditor;
69 class nsIFragmentContentSink;
70 class nsIFrame;
71 class nsIImageLoadingContent;
72 class nsIInterfaceRequestor;
73 class nsIIOService;
74 class nsILineBreaker;
75 class nsILoadGroup;
76 class nsIMessageBroadcaster;
77 class nsNameSpaceManager;
78 class nsIObserver;
79 class nsIParser;
80 class nsIParserService;
81 class nsIPresShell;
82 class nsIPrincipal;
83 class nsIRequest;
84 class nsIRunnable;
85 class nsIScriptContext;
86 class nsIScriptSecurityManager;
87 class nsIStringBundle;
88 class nsIStringBundleService;
89 class nsISupportsHashKey;
90 class nsIURI;
91 class nsIUUIDGenerator;
92 class nsIWidget;
93 class nsIWordBreaker;
94 class nsIXPConnect;
95 class nsNodeInfoManager;
96 class nsPIDOMWindowInner;
97 class nsPIDOMWindowOuter;
98 class nsPresContext;
99 class nsStringBuffer;
100 class nsStringHashKey;
101 class nsTextFragment;
102 class nsView;
103 class nsViewportInfo;
104 class nsWrapperCache;
105 class nsAttrValue;
106 class nsITransferable;
107 class nsPIWindowRoot;
108 class nsIWindowProvider;
109 
110 struct JSRuntime;
111 
112 template<class E> class nsCOMArray;
113 template<class K, class V> class nsDataHashtable;
114 template<class K, class V> class nsRefPtrHashtable;
115 template<class T> class nsReadingIterator;
116 
117 namespace mozilla {
118 class ErrorResult;
119 class EventListenerManager;
120 
121 namespace dom {
122 struct CustomElementDefinition;
123 class DocumentFragment;
124 class Element;
125 class EventTarget;
126 class IPCDataTransfer;
127 class IPCDataTransferItem;
128 struct LifecycleCallbackArgs;
129 class NodeInfo;
130 class nsIContentChild;
131 class nsIContentParent;
132 class TabChild;
133 class Selection;
134 class TabParent;
135 } // namespace dom
136 
137 namespace ipc {
138 class Shmem;
139 class IShmemAllocator;
140 }
141 
142 namespace gfx {
143 class DataSourceSurface;
144 } // namespace gfx
145 
146 namespace layers {
147 class LayerManager;
148 } // namespace layers
149 
150 } // namespace mozilla
151 
152 class nsIBidiKeyboard;
153 
154 extern const char kLoadAsData[];
155 
156 // Stolen from nsReadableUtils, but that's OK, since we can declare the same
157 // name multiple times.
158 const nsAFlatString& EmptyString();
159 const nsAFlatCString& EmptyCString();
160 
161 enum EventNameType {
162   EventNameType_None = 0x0000,
163   EventNameType_HTML = 0x0001,
164   EventNameType_XUL = 0x0002,
165   EventNameType_SVGGraphic = 0x0004, // svg graphic elements
166   EventNameType_SVGSVG = 0x0008, // the svg element
167   EventNameType_SMIL = 0x0010, // smil elements
168   EventNameType_HTMLBodyOrFramesetOnly = 0x0020,
169 
170   EventNameType_HTMLXUL = 0x0003,
171   EventNameType_All = 0xFFFF
172 };
173 
174 struct EventNameMapping
175 {
176   // This holds pointers to nsGkAtoms members, and is therefore safe as a
177   // non-owning reference.
178   nsIAtom* MOZ_NON_OWNING_REF mAtom;
179   int32_t  mType;
180   mozilla::EventMessage mMessage;
181   mozilla::EventClassID mEventClassID;
182   // True if mAtom is possibly used by special SVG/SMIL events, but
183   // mMessage is eUnidentifiedEvent. See EventNameList.h
184   bool mMaybeSpecialSVGorSMILEvent;
185 };
186 
187 typedef bool (*CallOnRemoteChildFunction) (mozilla::dom::TabParent* aTabParent,
188                                            void* aArg);
189 
190 class nsContentUtils
191 {
192   friend class nsAutoScriptBlockerSuppressNodeRemoved;
193   typedef mozilla::dom::Element Element;
194   typedef mozilla::TimeDuration TimeDuration;
195 
196 public:
197   static nsresult Init();
198 
199   static bool     IsCallerChrome();
200   static bool     ThreadsafeIsCallerChrome();
201   static bool     IsCallerContentXBL();
202 
203   // In the traditional Gecko architecture, both C++ code and untrusted JS code
204   // needed to rely on the same XPCOM method/getter/setter to get work done.
205   // This required lots of security checks in the various exposed methods, which
206   // in turn created difficulty in determining whether the caller was script
207   // (whose access needed to be checked) and internal C++ platform code (whose
208   // access did not need to be checked). To address this problem, Gecko had a
209   // convention whereby the absence of script on the stack was interpretted as
210   // "System Caller" and always granted unfettered access.
211   //
212   // Unfortunately, this created a bunch of footguns. For example, when the
213   // implementation of a DOM method wanted to perform a privileged
214   // sub-operation, it needed to "hide" the presence of script on the stack in
215   // order for that sub-operation to be allowed. Additionally, if script could
216   // trigger an API entry point to be invoked in some asynchronous way without
217   // script on the stack, it could potentially perform privilege escalation.
218   //
219   // In the modern world, untrusted script should interact with the platform
220   // exclusively over WebIDL APIs, and platform code has a lot more flexibility
221   // in deciding whether or not to use XPCOM. This gives us the flexibility to
222   // do something better.
223   //
224   // Going forward, APIs should be designed such that any security checks that
225   // ask the question "is my caller allowed to do this?" should live in WebIDL
226   // API entry points, with a separate method provided for internal callers
227   // that just want to get the job done.
228   //
229   // To enforce this and catch bugs, nsContentUtils::SubjectPrincipal will crash
230   // if it is invoked without script on the stack. To land that transition, it
231   // was necessary to go through and whitelist a bunch of callers that were
232   // depending on the old behavior. Those callers should be fixed up, and these
233   // methods should not be used by new code without review from bholley or bz.
LegacyIsCallerNativeCode()234   static bool     LegacyIsCallerNativeCode() { return !GetCurrentJSContext(); }
LegacyIsCallerChromeOrNativeCode()235   static bool     LegacyIsCallerChromeOrNativeCode() { return LegacyIsCallerNativeCode() || IsCallerChrome(); }
SubjectPrincipalOrSystemIfNativeCaller()236   static nsIPrincipal* SubjectPrincipalOrSystemIfNativeCaller()
237   {
238     if (!GetCurrentJSContext()) {
239       return GetSystemPrincipal();
240     }
241     return SubjectPrincipal();
242   }
243 
244   static bool LookupBindingMember(JSContext* aCx, nsIContent *aContent,
245                                   JS::Handle<jsid> aId,
246                                   JS::MutableHandle<JS::PropertyDescriptor> aDesc);
247 
248   // Check whether we should avoid leaking distinguishing information to JS/CSS.
249   static bool ShouldResistFingerprinting(nsIDocShell* aDocShell);
250 
251   /**
252    * Returns the parent node of aChild crossing document boundaries.
253    * Uses the parent node in the composed document.
254    */
255   static nsINode* GetCrossDocParentNode(nsINode* aChild);
256 
257   /**
258    * Do not ever pass null pointers to this method.  If one of your
259    * nsIContents is null, you have to decide for yourself what
260    * "IsDescendantOf" really means.
261    *
262    * @param  aPossibleDescendant node to test for being a descendant of
263    *         aPossibleAncestor
264    * @param  aPossibleAncestor node to test for being an ancestor of
265    *         aPossibleDescendant
266    * @return true if aPossibleDescendant is a descendant of
267    *         aPossibleAncestor (or is aPossibleAncestor).  false
268    *         otherwise.
269    */
270   static bool ContentIsDescendantOf(const nsINode* aPossibleDescendant,
271                                       const nsINode* aPossibleAncestor);
272 
273   /**
274    * Similar to ContentIsDescendantOf, except will treat an HTMLTemplateElement
275    * or ShadowRoot as an ancestor of things in the corresponding DocumentFragment.
276    * See the concept of "host-including inclusive ancestor" in the DOM
277    * specification.
278    */
279   static bool ContentIsHostIncludingDescendantOf(
280     const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
281 
282   /**
283    * Similar to ContentIsDescendantOf except it crosses document boundaries,
284    * this function uses ancestor/descendant relations in the composed document
285    * (see shadow DOM spec).
286    */
287   static bool ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant,
288                                               nsINode* aPossibleAncestor);
289 
290   /*
291    * This method fills the |aArray| with all ancestor nodes of |aNode|
292    * including |aNode| at the zero index.
293    */
294   static nsresult GetAncestors(nsINode* aNode,
295                                nsTArray<nsINode*>& aArray);
296 
297   /*
298    * This method fills |aAncestorNodes| with all ancestor nodes of |aNode|
299    * including |aNode| (QI'd to nsIContent) at the zero index.
300    * For each ancestor, there is a corresponding element in |aAncestorOffsets|
301    * which is the IndexOf the child in relation to its parent.
302    *
303    * This method just sucks.
304    */
305   static nsresult GetAncestorsAndOffsets(nsIDOMNode* aNode,
306                                          int32_t aOffset,
307                                          nsTArray<nsIContent*>* aAncestorNodes,
308                                          nsTArray<int32_t>* aAncestorOffsets);
309 
310   /*
311    * The out parameter, |aCommonAncestor| will be the closest node, if any,
312    * to both |aNode| and |aOther| which is also an ancestor of each.
313    * Returns an error if the two nodes are disconnected and don't have
314    * a common ancestor.
315    */
316   static nsresult GetCommonAncestor(nsIDOMNode *aNode,
317                                     nsIDOMNode *aOther,
318                                     nsIDOMNode** aCommonAncestor);
319 
320   /**
321    * Returns the common ancestor, if any, for two nodes. Returns null if the
322    * nodes are disconnected.
323    */
324   static nsINode* GetCommonAncestor(nsINode* aNode1,
325                                     nsINode* aNode2);
326 
327   /**
328    * Returns true if aNode1 is before aNode2 in the same connected
329    * tree.
330    */
331   static bool PositionIsBefore(nsINode* aNode1, nsINode* aNode2);
332 
333   /**
334    *  Utility routine to compare two "points", where a point is a
335    *  node/offset pair
336    *  Returns -1 if point1 < point2, 1, if point1 > point2,
337    *  0 if error or if point1 == point2.
338    *  NOTE! If the two nodes aren't in the same connected subtree,
339    *  the result is 1, and the optional aDisconnected parameter
340    *  is set to true.
341    */
342   static int32_t ComparePoints(nsINode* aParent1, int32_t aOffset1,
343                                nsINode* aParent2, int32_t aOffset2,
344                                bool* aDisconnected = nullptr);
345   static int32_t ComparePoints(nsIDOMNode* aParent1, int32_t aOffset1,
346                                nsIDOMNode* aParent2, int32_t aOffset2,
347                                bool* aDisconnected = nullptr);
348 
349   /**
350    * Brute-force search of the element subtree rooted at aContent for
351    * an element with the given id.  aId must be nonempty, otherwise
352    * this method may return nodes even if they have no id!
353    */
354   static Element* MatchElementId(nsIContent *aContent, const nsAString& aId);
355 
356   /**
357    * Similar to above, but to be used if one already has an atom for the ID
358    */
359   static Element* MatchElementId(nsIContent *aContent, const nsIAtom* aId);
360 
361   /**
362    * Reverses the document position flags passed in.
363    *
364    * @param   aDocumentPosition   The document position flags to be reversed.
365    *
366    * @return  The reversed document position flags.
367    *
368    * @see nsIDOMNode
369    */
370   static uint16_t ReverseDocumentPosition(uint16_t aDocumentPosition);
371 
372   /**
373    * Returns a subdocument for aDocument with a particular outer window ID.
374    *
375    * @param aDocument
376    *        The document whose subdocuments will be searched.
377    * @param aOuterWindowID
378    *        The outer window ID for the subdocument to be found. This must
379    *        be a value greater than 0.
380    * @return nsIDocument*
381    *        A pointer to the found nsIDocument. nullptr if the subdocument
382    *        cannot be found, or if either aDocument or aOuterWindowId were
383    *        invalid. If the outer window ID belongs to aDocument itself, this
384    *        will return a pointer to aDocument.
385    */
386   static nsIDocument* GetSubdocumentWithOuterWindowId(nsIDocument *aDocument,
387                                                       uint64_t aOuterWindowId);
388 
389   static uint32_t CopyNewlineNormalizedUnicodeTo(const nsAString& aSource,
390                                                  uint32_t aSrcOffset,
391                                                  char16_t* aDest,
392                                                  uint32_t aLength,
393                                                  bool& aLastCharCR);
394 
395   static uint32_t CopyNewlineNormalizedUnicodeTo(nsReadingIterator<char16_t>& aSrcStart, const nsReadingIterator<char16_t>& aSrcEnd, nsAString& aDest);
396 
397   static const nsDependentSubstring TrimCharsInSet(const char* aSet,
398                                                    const nsAString& aValue);
399 
400   template<bool IsWhitespace(char16_t)>
401   static const nsDependentSubstring TrimWhitespace(const nsAString& aStr,
402                                                    bool aTrimTrailing = true);
403 
404   /**
405    * Returns true if aChar is of class Ps, Pi, Po, Pf, or Pe.
406    */
407   static bool IsFirstLetterPunctuation(uint32_t aChar);
408   static bool IsFirstLetterPunctuationAt(const nsTextFragment* aFrag, uint32_t aOffset);
409 
410   /**
411    * Returns true if aChar is of class Lu, Ll, Lt, Lm, Lo, Nd, Nl or No
412    */
413   static bool IsAlphanumeric(uint32_t aChar);
414   static bool IsAlphanumericAt(const nsTextFragment* aFrag, uint32_t aOffset);
415 
416   /*
417    * Is the character an HTML whitespace character?
418    *
419    * We define whitespace using the list in HTML5 and css3-selectors:
420    * U+0009, U+000A, U+000C, U+000D, U+0020
421    *
422    * HTML 4.01 also lists U+200B (zero-width space).
423    */
424   static bool IsHTMLWhitespace(char16_t aChar);
425 
426   /*
427    * Returns whether the character is an HTML whitespace (see IsHTMLWhitespace)
428    * or a nbsp character (U+00A0).
429    */
430   static bool IsHTMLWhitespaceOrNBSP(char16_t aChar);
431 
432   /**
433    * Is the HTML local name a block element?
434    */
435   static bool IsHTMLBlock(nsIContent* aContent);
436 
437   enum ParseHTMLIntegerResultFlags {
438     eParseHTMLInteger_NoFlags               = 0,
439     eParseHTMLInteger_IsPercent             = 1 << 0,
440     // eParseHTMLInteger_NonStandard is set if the string representation of the
441     // integer was not the canonical one (e.g. had extra leading '+' or '0').
442     eParseHTMLInteger_NonStandard           = 1 << 1,
443     eParseHTMLInteger_DidNotConsumeAllInput = 1 << 2,
444     // Set if one or more error flags were set.
445     eParseHTMLInteger_Error                 = 1 << 3,
446     eParseHTMLInteger_ErrorNoValue          = 1 << 4,
447     eParseHTMLInteger_ErrorOverflow         = 1 << 5
448   };
449   static int32_t ParseHTMLInteger(const nsAString& aValue,
450                                   ParseHTMLIntegerResultFlags *aResult);
451 
452   /**
453    * Parse a margin string of format 'top, right, bottom, left' into
454    * an nsIntMargin.
455    *
456    * @param aString the string to parse
457    * @param aResult the resulting integer
458    * @return whether the value could be parsed
459    */
460   static bool ParseIntMarginValue(const nsAString& aString, nsIntMargin& aResult);
461 
462   /**
463    * Parse the value of the <font size=""> attribute according to the HTML5
464    * spec as of April 16, 2012.
465    *
466    * @param aValue the value to parse
467    * @return 1 to 7, or 0 if the value couldn't be parsed
468    */
469   static int32_t ParseLegacyFontSize(const nsAString& aValue);
470 
471   static void Shutdown();
472 
473   /**
474    * Checks whether two nodes come from the same origin.
475    */
476   static nsresult CheckSameOrigin(const nsINode* aTrustedNode,
477                                   nsIDOMNode* aUnTrustedNode);
478   static nsresult CheckSameOrigin(const nsINode* aTrustedNode,
479                                   const nsINode* unTrustedNode);
480 
481   // Check if the (JS) caller can access aNode.
482   static bool CanCallerAccess(nsIDOMNode *aNode);
483   static bool CanCallerAccess(nsINode* aNode);
484 
485   // Check if the (JS) caller can access aWindow.
486   // aWindow can be either outer or inner window.
487   static bool CanCallerAccess(nsPIDOMWindowInner* aWindow);
488 
489   /**
490    * GetDocumentFromCaller gets its document by looking at the last called
491    * function and finding the document that the function itself relates to.
492    * For example, consider two windows A and B in the same origin. B has a
493    * function which does something that ends up needing the current document.
494    * If a script in window A were to call B's function, GetDocumentFromCaller
495    * would find that function (in B) and return B's document.
496    *
497    * @return The document or null if no JS Context.
498    */
499   static nsIDocument* GetDocumentFromCaller();
500 
501   // Check if a node is in the document prolog, i.e. before the document
502   // element.
503   static bool InProlog(nsINode *aNode);
504 
505   static nsIParserService* GetParserService();
506 
NameSpaceManager()507   static nsNameSpaceManager* NameSpaceManager()
508   {
509     return sNameSpaceManager;
510   }
511 
GetIOService()512   static nsIIOService* GetIOService()
513   {
514     return sIOService;
515   }
516 
517   static nsIBidiKeyboard* GetBidiKeyboard();
518 
519   /**
520    * Get the cache security manager service. Can return null if the layout
521    * module has been shut down.
522    */
GetSecurityManager()523   static nsIScriptSecurityManager* GetSecurityManager()
524   {
525     return sSecurityManager;
526   }
527 
528   // Returns the subject principal. Guaranteed to return non-null. May only
529   // be called when nsContentUtils is initialized.
530   static nsIPrincipal* SubjectPrincipal();
531 
532   // Returns the prinipal of the given JS object. This may only be called on
533   // the main thread for objects from the main thread's JSRuntime.
534   static nsIPrincipal* ObjectPrincipal(JSObject* aObj);
535 
536   static nsresult GenerateStateKey(nsIContent* aContent,
537                                    const nsIDocument* aDocument,
538                                    nsACString& aKey);
539 
540   /**
541    * Create a new nsIURI from aSpec, using aBaseURI as the base.  The
542    * origin charset of the new nsIURI will be the document charset of
543    * aDocument.
544    */
545   static nsresult NewURIWithDocumentCharset(nsIURI** aResult,
546                                             const nsAString& aSpec,
547                                             nsIDocument* aDocument,
548                                             nsIURI* aBaseURI);
549 
550   /**
551    * Convert aInput (in encoding aEncoding) to UTF16 in aOutput.
552    *
553    * @param aEncoding the Gecko-canonical name of the encoding or the empty
554    *                  string (meaning UTF-8)
555    */
556   static nsresult ConvertStringFromEncoding(const nsACString& aEncoding,
557                                             const nsACString& aInput,
558                                             nsAString& aOutput);
559 
560   /**
561    * Determine whether a buffer begins with a BOM for UTF-8, UTF-16LE,
562    * UTF-16BE
563    *
564    * @param aBuffer the buffer to check
565    * @param aLength the length of the buffer
566    * @param aCharset empty if not found
567    * @return boolean indicating whether a BOM was detected.
568    */
569   static bool CheckForBOM(const unsigned char* aBuffer, uint32_t aLength,
570                           nsACString& aCharset);
571 
572   /**
573    * Returns true if |aName| is a valid name to be registered via
574    * document.registerElement.
575    */
576   static bool IsCustomElementName(nsIAtom* aName);
577 
578   static nsresult CheckQName(const nsAString& aQualifiedName,
579                              bool aNamespaceAware = true,
580                              const char16_t** aColon = nullptr);
581 
582   static nsresult SplitQName(const nsIContent* aNamespaceResolver,
583                              const nsAFlatString& aQName,
584                              int32_t *aNamespace, nsIAtom **aLocalName);
585 
586   static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI,
587                                        const nsAString& aQualifiedName,
588                                        nsNodeInfoManager* aNodeInfoManager,
589                                        uint16_t aNodeType,
590                                        mozilla::dom::NodeInfo** aNodeInfo);
591 
592   static void SplitExpatName(const char16_t *aExpatName, nsIAtom **aPrefix,
593                              nsIAtom **aTagName, int32_t *aNameSpaceID);
594 
595   // Get a permission-manager setting for the given principal and type.
596   // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
597   // returned, otherwise true is returned. Always returns true for the
598   // system principal, and false for a null principal.
599   static bool IsSitePermAllow(nsIPrincipal* aPrincipal, const char* aType);
600 
601   // Get a permission-manager setting for the given principal and type.
602   // If the pref doesn't exist or if it isn't DENY_ACTION, false is
603   // returned, otherwise true is returned. Always returns false for the
604   // system principal, and true for a null principal.
605   static bool IsSitePermDeny(nsIPrincipal* aPrincipal, const char* aType);
606 
607   // Get a permission-manager setting for the given principal and type.
608   // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
609   // returned, otherwise true is returned. Always returns true for the
610   // system principal, and false for a null principal.
611   // This version checks the permission for an exact host match on
612   // the principal
613   static bool IsExactSitePermAllow(nsIPrincipal* aPrincipal, const char* aType);
614 
615   // Get a permission-manager setting for the given principal and type.
616   // If the pref doesn't exist or if it isn't DENY_ACTION, false is
617   // returned, otherwise true is returned. Always returns false for the
618   // system principal, and true for a null principal.
619   // This version checks the permission for an exact host match on
620   // the principal
621   static bool IsExactSitePermDeny(nsIPrincipal* aPrincipal, const char* aType);
622 
623   // Returns true if aDoc1 and aDoc2 have equal NodePrincipal()s.
624   static bool HaveEqualPrincipals(nsIDocument* aDoc1, nsIDocument* aDoc2);
625 
LineBreaker()626   static nsILineBreaker* LineBreaker()
627   {
628     return sLineBreaker;
629   }
630 
WordBreaker()631   static nsIWordBreaker* WordBreaker()
632   {
633     return sWordBreaker;
634   }
635 
636   /**
637    * Regster aObserver as a shutdown observer. A strong reference is held
638    * to aObserver until UnregisterShutdownObserver is called.
639    */
640   static void RegisterShutdownObserver(nsIObserver* aObserver);
641   static void UnregisterShutdownObserver(nsIObserver* aObserver);
642 
643   /**
644    * @return true if aContent has an attribute aName in namespace aNameSpaceID,
645    * and the attribute value is non-empty.
646    */
647   static bool HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID,
648                                 nsIAtom* aName);
649 
650   /**
651    * Method that gets the primary presContext for the node.
652    *
653    * @param aContent The content node.
654    * @return the presContext, or nullptr if the content is not in a document
655    *         (if GetCurrentDoc returns nullptr)
656    */
657   static nsPresContext* GetContextForContent(const nsIContent* aContent);
658 
659   /**
660    * Method to do security and content policy checks on the image URI
661    *
662    * @param aURI uri of the image to be loaded
663    * @param aContext the context the image is loaded in (eg an element)
664    * @param aLoadingDocument the document we belong to
665    * @param aLoadingPrincipal the principal doing the load
666    * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE] (Optional)
667    *        The CP content type to use
668    * @param aImageBlockingStatus the nsIContentPolicy blocking status for this
669    *        image.  This will be set even if a security check fails for the
670    *        image, to some reasonable REJECT_* value.  This out param will only
671    *        be set if it's non-null.
672    * @return true if the load can proceed, or false if it is blocked.
673    *         Note that aImageBlockingStatus, if set will always be an ACCEPT
674    *         status if true is returned and always be a REJECT_* status if
675    *         false is returned.
676    */
677   static bool CanLoadImage(nsIURI* aURI,
678                            nsISupports* aContext,
679                            nsIDocument* aLoadingDocument,
680                            nsIPrincipal* aLoadingPrincipal,
681                            int16_t* aImageBlockingStatus = nullptr,
682                            uint32_t aContentPolicyType = nsIContentPolicy::TYPE_INTERNAL_IMAGE);
683 
684   /**
685    * Returns true if objects in aDocument shouldn't initiate image loads.
686    */
687   static bool DocumentInactiveForImageLoads(nsIDocument* aDocument);
688 
689   /**
690    * Method to start an image load.  This does not do any security checks.
691    * This method will attempt to make aURI immutable; a caller that wants to
692    * keep a mutable version around should pass in a clone.
693    *
694    * @param aURI uri of the image to be loaded
695    * @param aContext element of document where the result of this request
696    *                 will be used.
697    * @param aLoadingDocument the document we belong to
698    * @param aLoadingPrincipal the principal doing the load
699    * @param aReferrer the referrer URI
700    * @param aReferrerPolicy the referrer-sending policy to use on channel
701    *         creation
702    * @param aObserver the observer for the image load
703    * @param aLoadFlags the load flags to use.  See nsIRequest
704    * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE] (Optional)
705    *        The CP content type to use
706    * @return the imgIRequest for the image load
707    */
708   static nsresult LoadImage(nsIURI* aURI,
709                             nsINode* aContext,
710                             nsIDocument* aLoadingDocument,
711                             nsIPrincipal* aLoadingPrincipal,
712                             nsIURI* aReferrer,
713                             mozilla::net::ReferrerPolicy aReferrerPolicy,
714                             imgINotificationObserver* aObserver,
715                             int32_t aLoadFlags,
716                             const nsAString& initiatorType,
717                             imgRequestProxy** aRequest,
718                             uint32_t aContentPolicyType = nsIContentPolicy::TYPE_INTERNAL_IMAGE);
719 
720   /**
721    * Obtain an image loader that respects the given document/channel's privacy status.
722    * Null document/channel arguments return the public image loader.
723    */
724   static imgLoader* GetImgLoaderForDocument(nsIDocument* aDoc);
725   static imgLoader* GetImgLoaderForChannel(nsIChannel* aChannel,
726                                            nsIDocument* aContext);
727 
728   /**
729    * Returns whether the given URI is in the image cache.
730    */
731   static bool IsImageInCache(nsIURI* aURI, nsIDocument* aDocument);
732 
733   /**
734    * Method to get an imgIContainer from an image loading content
735    *
736    * @param aContent The image loading content.  Must not be null.
737    * @param aRequest The image request [out]
738    * @return the imgIContainer corresponding to the first frame of the image
739    */
740   static already_AddRefed<imgIContainer> GetImageFromContent(nsIImageLoadingContent* aContent, imgIRequest **aRequest = nullptr);
741 
742   /**
743    * Helper method to call imgIRequest::GetStaticRequest.
744    */
745   static already_AddRefed<imgRequestProxy> GetStaticRequest(imgRequestProxy* aRequest);
746 
747   /**
748    * Method that decides whether a content node is draggable
749    *
750    * @param aContent The content node to test.
751    * @return whether it's draggable
752    */
753   static bool ContentIsDraggable(nsIContent* aContent);
754 
755   /**
756    * Method that decides whether a content node is a draggable image
757    *
758    * @param aContent The content node to test.
759    * @return whether it's a draggable image
760    */
761   static bool IsDraggableImage(nsIContent* aContent);
762 
763   /**
764    * Method that decides whether a content node is a draggable link
765    *
766    * @param aContent The content node to test.
767    * @return whether it's a draggable link
768    */
769   static bool IsDraggableLink(const nsIContent* aContent);
770 
771   /**
772    * Convenience method to create a new nodeinfo that differs only by name
773    * from aNodeInfo.
774    */
775   static nsresult NameChanged(mozilla::dom::NodeInfo* aNodeInfo, nsIAtom* aName,
776                               mozilla::dom::NodeInfo** aResult);
777 
778   /**
779    * Returns the appropriate event argument names for the specified
780    * namespace and event name.  Added because we need to switch between
781    * SVG's "evt" and the rest of the world's "event", and because onerror
782    * on window takes 5 args.
783    */
784   static void GetEventArgNames(int32_t aNameSpaceID, nsIAtom *aEventName,
785                                bool aIsForWindow,
786                                uint32_t *aArgCount, const char*** aArgNames);
787 
788   /**
789    * Returns origin attributes of the document.
790    **/
791   static mozilla::PrincipalOriginAttributes
792   GetOriginAttributes(nsIDocument* aDoc);
793 
794   /**
795    * Returns origin attributes of the load group.
796    **/
797   static mozilla::PrincipalOriginAttributes
798   GetOriginAttributes(nsILoadGroup* aLoadGroup);
799 
800   /**
801    * Returns true if this document is in a Private Browsing window.
802    */
803   static bool IsInPrivateBrowsing(nsIDocument* aDoc);
804 
805   /**
806    * Returns true if this loadGroup uses Private Browsing.
807    */
808   static bool IsInPrivateBrowsing(nsILoadGroup* aLoadGroup);
809 
810   /**
811    * If aNode is not an element, return true exactly when aContent's binding
812    * parent is null.
813    *
814    * If aNode is an element, return true exactly when aContent's binding parent
815    * is the same as aNode's.
816    *
817    * This method is particularly useful for callers who are trying to ensure
818    * that they are working with a non-anonymous descendant of a given node.  If
819    * aContent is a descendant of aNode, a return value of false from this
820    * method means that it's an anonymous descendant from aNode's point of view.
821    *
822    * Both arguments to this method must be non-null.
823    */
824   static bool IsInSameAnonymousTree(const nsINode* aNode, const nsIContent* aContent);
825 
826   /**
827    * Return the nsIXPConnect service.
828    */
XPConnect()829   static nsIXPConnect *XPConnect()
830   {
831     return sXPConnect;
832   }
833 
834   /**
835    * Report simple error message to the browser console
836    *   @param aErrorText the error message
837    *   @param classification Name of the module reporting error
838    */
839   static void LogSimpleConsoleError(const nsAString& aErrorText,
840                                     const char * classification);
841 
842   /**
843    * Report a non-localized error message to the error console.
844    *   @param aErrorText the error message
845    *   @param aErrorFlags See nsIScriptError.
846    *   @param aCategory Name of module reporting error.
847    *   @param aDocument Reference to the document which triggered the message.
848    *   @param [aURI=nullptr] (Optional) URI of resource containing error.
849    *   @param [aSourceLine=EmptyString()] (Optional) The text of the line that
850               contains the error (may be empty).
851    *   @param [aLineNumber=0] (Optional) Line number within resource
852               containing error.
853    *   @param [aColumnNumber=0] (Optional) Column number within resource
854               containing error.
855               If aURI is null, then aDocument->GetDocumentURI() is used.
856    *   @param [aLocationMode] (Optional) Specifies the behavior if
857               error location information is omitted.
858    */
859   enum MissingErrorLocationMode {
860     // Don't show location information in the error console.
861     eOMIT_LOCATION,
862     // Get location information from the currently executing script.
863     eUSE_CALLING_LOCATION
864   };
865   static nsresult ReportToConsoleNonLocalized(const nsAString& aErrorText,
866                                               uint32_t aErrorFlags,
867                                               const nsACString& aCategory,
868                                               const nsIDocument* aDocument,
869                                               nsIURI* aURI = nullptr,
870                                               const nsAFlatString& aSourceLine
871                                                 = EmptyString(),
872                                               uint32_t aLineNumber = 0,
873                                               uint32_t aColumnNumber = 0,
874                                               MissingErrorLocationMode aLocationMode
875                                                 = eUSE_CALLING_LOCATION);
876 
877   /**
878    * Report a localized error message to the error console.
879    *   @param aErrorFlags See nsIScriptError.
880    *   @param aCategory Name of module reporting error.
881    *   @param aDocument Reference to the document which triggered the message.
882    *   @param aFile Properties file containing localized message.
883    *   @param aMessageName Name of localized message.
884    *   @param [aParams=nullptr] (Optional) Parameters to be substituted into
885               localized message.
886    *   @param [aParamsLength=0] (Optional) Length of aParams.
887    *   @param [aURI=nullptr] (Optional) URI of resource containing error.
888    *   @param [aSourceLine=EmptyString()] (Optional) The text of the line that
889               contains the error (may be empty).
890    *   @param [aLineNumber=0] (Optional) Line number within resource
891               containing error.
892    *   @param [aColumnNumber=0] (Optional) Column number within resource
893               containing error.
894               If aURI is null, then aDocument->GetDocumentURI() is used.
895    */
896   enum PropertiesFile {
897     eCSS_PROPERTIES,
898     eXBL_PROPERTIES,
899     eXUL_PROPERTIES,
900     eLAYOUT_PROPERTIES,
901     eFORMS_PROPERTIES,
902     ePRINTING_PROPERTIES,
903     eDOM_PROPERTIES,
904     eHTMLPARSER_PROPERTIES,
905     eSVG_PROPERTIES,
906     eBRAND_PROPERTIES,
907     eCOMMON_DIALOG_PROPERTIES,
908     eMATHML_PROPERTIES,
909     eSECURITY_PROPERTIES,
910     eNECKO_PROPERTIES,
911     PropertiesFile_COUNT
912   };
913   static nsresult ReportToConsole(uint32_t aErrorFlags,
914                                   const nsACString& aCategory,
915                                   const nsIDocument* aDocument,
916                                   PropertiesFile aFile,
917                                   const char *aMessageName,
918                                   const char16_t **aParams = nullptr,
919                                   uint32_t aParamsLength = 0,
920                                   nsIURI* aURI = nullptr,
921                                   const nsAFlatString& aSourceLine
922                                     = EmptyString(),
923                                   uint32_t aLineNumber = 0,
924                                   uint32_t aColumnNumber = 0);
925 
926   static void LogMessageToConsole(const char* aMsg);
927 
928   /**
929    * Get the localized string named |aKey| in properties file |aFile|.
930    */
931   static nsresult GetLocalizedString(PropertiesFile aFile,
932                                      const char* aKey,
933                                      nsXPIDLString& aResult);
934 
935   /**
936    * A helper function that parses a sandbox attribute (of an <iframe> or a CSP
937    * directive) and converts it to the set of flags used internally.
938    *
939    * @param aSandboxAttr  the sandbox attribute
940    * @return              the set of flags (SANDBOXED_NONE if aSandboxAttr is
941    *                      null)
942    */
943   static uint32_t ParseSandboxAttributeToFlags(const nsAttrValue* aSandboxAttr);
944 
945   /**
946    * A helper function that checks if a string matches a valid sandbox flag.
947    *
948    * @param aFlag   the potential sandbox flag.
949    * @return        true if the flag is a sandbox flag.
950    */
951   static bool IsValidSandboxFlag(const nsAString& aFlag);
952 
953   /**
954    * A helper function that returns a string attribute corresponding to the
955    * sandbox flags.
956    *
957    * @param aFlags    the sandbox flags
958    * @param aString   the attribute corresponding to the flags (null if aFlags
959    *                  is zero)
960    */
961   static void SandboxFlagsToString(uint32_t aFlags, nsAString& aString);
962 
963   /**
964    * Helper function that generates a UUID.
965    */
966   static nsresult GenerateUUIDInPlace(nsID& aUUID);
967 
968   static bool PrefetchEnabled(nsIDocShell* aDocShell);
969 
970   /**
971    * Fill (with the parameters given) the localized string named |aKey| in
972    * properties file |aFile|.
973    */
974 private:
975   static nsresult FormatLocalizedString(PropertiesFile aFile,
976                                         const char* aKey,
977                                         const char16_t** aParams,
978                                         uint32_t aParamsLength,
979                                         nsXPIDLString& aResult);
980 
981 public:
982   template<uint32_t N>
FormatLocalizedString(PropertiesFile aFile,const char * aKey,const char16_t * (& aParams)[N],nsXPIDLString & aResult)983   static nsresult FormatLocalizedString(PropertiesFile aFile,
984                                         const char* aKey,
985                                         const char16_t* (&aParams)[N],
986                                         nsXPIDLString& aResult)
987   {
988     return FormatLocalizedString(aFile, aKey, aParams, N, aResult);
989   }
990 
991   /**
992    * Fill (with the parameters given) the localized string named |aKey| in
993    * properties file |aFile| consuming an nsTArray of nsString parameters rather
994    * than a char16_t** for the sake of avoiding use-after-free errors involving
995    * temporaries.
996    */
997   static nsresult FormatLocalizedString(PropertiesFile aFile,
998                                         const char* aKey,
999                                         const nsTArray<nsString>& aParamArray,
1000                                         nsXPIDLString& aResult);
1001 
1002   /**
1003    * Returns true if aDocument is a chrome document
1004    */
1005   static bool IsChromeDoc(nsIDocument *aDocument);
1006 
1007   /**
1008    * Returns true if aDocument is in a docshell whose parent is the same type
1009    */
1010   static bool IsChildOfSameType(nsIDocument* aDoc);
1011 
1012   /**
1013   '* Returns true if the content-type is any of the supported script types.
1014    */
1015   static bool IsScriptType(const nsACString& aContentType);
1016 
1017   /**
1018   '* Returns true if the content-type will be rendered as plain-text.
1019    */
1020   static bool IsPlainTextType(const nsACString& aContentType);
1021 
1022   /**
1023    * Get the script file name to use when compiling the script
1024    * referenced by aURI. In cases where there's no need for any extra
1025    * security wrapper automation the script file name that's returned
1026    * will be the spec in aURI, else it will be the spec in aDocument's
1027    * URI followed by aURI's spec, separated by " -> ". Returns true
1028    * if the script file name was modified, false if it's aURI's
1029    * spec.
1030    */
1031   static bool GetWrapperSafeScriptFilename(nsIDocument *aDocument,
1032                                              nsIURI *aURI,
1033                                              nsACString& aScriptURI,
1034                                              nsresult* aRv);
1035 
1036 
1037   /**
1038    * Returns true if aDocument belongs to a chrome docshell for
1039    * display purposes.  Returns false for null documents or documents
1040    * which do not belong to a docshell.
1041    */
1042   static bool IsInChromeDocshell(nsIDocument *aDocument);
1043 
1044   /**
1045    * Return the content policy service
1046    */
1047   static nsIContentPolicy *GetContentPolicy();
1048 
1049   /**
1050    * Map internal content policy types to external ones.
1051    */
1052   static nsContentPolicyType InternalContentPolicyTypeToExternal(nsContentPolicyType aType);
1053 
1054   /**
1055    * Map internal content policy types to external ones or preload types:
1056    *   * TYPE_INTERNAL_SCRIPT_PRELOAD
1057    *   * TYPE_INTERNAL_IMAGE_PRELOAD
1058    *   * TYPE_INTERNAL_STYLESHEET_PRELOAD
1059    *
1060    * Note: DO NOT call this function unless you know what you're doing!
1061    */
1062   static nsContentPolicyType InternalContentPolicyTypeToExternalOrPreload(nsContentPolicyType aType);
1063 
1064   /**
1065    * Map internal content policy types to external ones, worker, or preload types:
1066    *   * TYPE_INTERNAL_WORKER
1067    *   * TYPE_INTERNAL_SHARED_WORKER
1068    *   * TYPE_INTERNAL_SERVICE_WORKER
1069    *
1070    * Note: DO NOT call this function unless you know what you're doing!
1071    */
1072   static nsContentPolicyType InternalContentPolicyTypeToExternalOrWorker(nsContentPolicyType aType);
1073 
1074   /**
1075    * Returns true if the content policy type is any of:
1076    *   * TYPE_INTERNAL_SCRIPT_PRELOAD
1077    *   * TYPE_INTERNAL_IMAGE_PRELOAD
1078    *   * TYPE_INTERNAL_STYLESHEET_PRELOAD
1079    */
1080   static bool IsPreloadType(nsContentPolicyType aType);
1081 
1082   /**
1083    * Quick helper to determine whether there are any mutation listeners
1084    * of a given type that apply to this content or any of its ancestors.
1085    * The method has the side effect to call document's MayDispatchMutationEvent
1086    * using aTargetForSubtreeModified as the parameter.
1087    *
1088    * @param aNode  The node to search for listeners
1089    * @param aType  The type of listener (NS_EVENT_BITS_MUTATION_*)
1090    * @param aTargetForSubtreeModified The node which is the target of the
1091    *                                  possible DOMSubtreeModified event.
1092    *
1093    * @return true if there are mutation listeners of the specified type
1094    */
1095   static bool HasMutationListeners(nsINode* aNode,
1096                                      uint32_t aType,
1097                                      nsINode* aTargetForSubtreeModified);
1098 
1099   /**
1100    * Quick helper to determine whether there are any mutation listeners
1101    * of a given type that apply to any content in this document. It is valid
1102    * to pass null for aDocument here, in which case this function always
1103    * returns true.
1104    *
1105    * @param aDocument The document to search for listeners
1106    * @param aType     The type of listener (NS_EVENT_BITS_MUTATION_*)
1107    *
1108    * @return true if there are mutation listeners of the specified type
1109    */
1110   static bool HasMutationListeners(nsIDocument* aDocument,
1111                                      uint32_t aType);
1112   /**
1113    * Synchronously fire DOMNodeRemoved on aChild. Only fires the event if
1114    * there really are listeners by checking using the HasMutationListeners
1115    * function above. The function makes sure to hold the relevant objects alive
1116    * for the duration of the event firing. However there are no guarantees
1117    * that any of the objects are alive by the time the function returns.
1118    * If you depend on that you need to hold references yourself.
1119    *
1120    * @param aChild    The node to fire DOMNodeRemoved at.
1121    * @param aParent   The parent of aChild.
1122    * @param aOwnerDoc The ownerDocument of aChild.
1123    */
1124   static void MaybeFireNodeRemoved(nsINode* aChild, nsINode* aParent,
1125                                    nsIDocument* aOwnerDoc);
1126 
1127   /**
1128    * This method creates and dispatches a trusted event.
1129    * Works only with events which can be created by calling
1130    * nsIDOMDocument::CreateEvent() with parameter "Events".
1131    * @param aDoc           The document which will be used to create the event.
1132    * @param aTarget        The target of the event, should be QIable to
1133    *                       nsIDOMEventTarget.
1134    * @param aEventName     The name of the event.
1135    * @param aCanBubble     Whether the event can bubble.
1136    * @param aCancelable    Is the event cancelable.
1137    * @param aDefaultAction Set to true if default action should be taken,
1138    *                       see nsIDOMEventTarget::DispatchEvent.
1139    */
1140   static nsresult DispatchTrustedEvent(nsIDocument* aDoc,
1141                                        nsISupports* aTarget,
1142                                        const nsAString& aEventName,
1143                                        bool aCanBubble,
1144                                        bool aCancelable,
1145                                        bool *aDefaultAction = nullptr);
1146 
1147   /**
1148    * This method creates and dispatches a untrusted event.
1149    * Works only with events which can be created by calling
1150    * nsIDOMDocument::CreateEvent() with parameter "Events".
1151    * @param aDoc           The document which will be used to create the event.
1152    * @param aTarget        The target of the event, should be QIable to
1153    *                       nsIDOMEventTarget.
1154    * @param aEventName     The name of the event.
1155    * @param aCanBubble     Whether the event can bubble.
1156    * @param aCancelable    Is the event cancelable.
1157    * @param aDefaultAction Set to true if default action should be taken,
1158    *                       see nsIDOMEventTarget::DispatchEvent.
1159    */
1160   static nsresult DispatchUntrustedEvent(nsIDocument* aDoc,
1161                                          nsISupports* aTarget,
1162                                          const nsAString& aEventName,
1163                                          bool aCanBubble,
1164                                          bool aCancelable,
1165                                          bool *aDefaultAction = nullptr);
1166 
1167   /**
1168    * This method creates and dispatches a trusted event to the chrome
1169    * event handler (the parent object of the DOM Window in the event target
1170    * chain). Note, chrome event handler is used even if aTarget is a chrome
1171    * object. Use DispatchEventOnlyToChrome if the normal event dispatching is
1172    * wanted in case aTarget is a chrome object.
1173    * Works only with events which can be created by calling
1174    * nsIDOMDocument::CreateEvent() with parameter "Events".
1175    * @param aDocument      The document which will be used to create the event,
1176    *                       and whose window's chrome handler will be used to
1177    *                       dispatch the event.
1178    * @param aTarget        The target of the event, used for event->SetTarget()
1179    * @param aEventName     The name of the event.
1180    * @param aCanBubble     Whether the event can bubble.
1181    * @param aCancelable    Is the event cancelable.
1182    * @param aDefaultAction Set to true if default action should be taken,
1183    *                       see nsIDOMEventTarget::DispatchEvent.
1184    */
1185   static nsresult DispatchChromeEvent(nsIDocument* aDoc,
1186                                       nsISupports* aTarget,
1187                                       const nsAString& aEventName,
1188                                       bool aCanBubble,
1189                                       bool aCancelable,
1190                                       bool *aDefaultAction = nullptr);
1191 
1192   /**
1193    * Helper function for dispatching a "DOMServiceWorkerFocusClient" event to
1194    * the chrome event handler of the given DOM Window. This has the effect
1195    * of focusing the corresponding tab and bringing the browser window
1196    * to the foreground.
1197    */
1198   static nsresult DispatchFocusChromeEvent(nsPIDOMWindowOuter* aWindow);
1199 
1200   /**
1201    * This method creates and dispatches a trusted event.
1202    * If aTarget is not a chrome object, the nearest chrome object in the
1203    * propagation path will be used as the start of the event target chain.
1204    * This method is different than DispatchChromeEvent, which always dispatches
1205    * events to chrome event handler. DispatchEventOnlyToChrome works like
1206    * DispatchTrustedEvent in the case aTarget is a chrome object.
1207    * Works only with events which can be created by calling
1208    * nsIDOMDocument::CreateEvent() with parameter "Events".
1209    * @param aDoc           The document which will be used to create the event.
1210    * @param aTarget        The target of the event, should be QIable to
1211    *                       nsIDOMEventTarget.
1212    * @param aEventName     The name of the event.
1213    * @param aCanBubble     Whether the event can bubble.
1214    * @param aCancelable    Is the event cancelable.
1215    * @param aDefaultAction Set to true if default action should be taken,
1216    *                       see nsIDOMEventTarget::DispatchEvent.
1217    */
1218   static nsresult DispatchEventOnlyToChrome(nsIDocument* aDoc,
1219                                             nsISupports* aTarget,
1220                                             const nsAString& aEventName,
1221                                             bool aCanBubble,
1222                                             bool aCancelable,
1223                                             bool *aDefaultAction = nullptr);
1224 
1225   /**
1226    * Determines if an event attribute name (such as onclick) is valid for
1227    * a given element type. Types are from the EventNameType enumeration
1228    * defined above.
1229    *
1230    * @param aName the event name to look up
1231    * @param aType the type of content
1232    */
1233   static bool IsEventAttributeName(nsIAtom* aName, int32_t aType);
1234 
1235   /**
1236    * Return the event message for the event with the given name. The name is
1237    * the event name with the 'on' prefix. Returns eUnidentifiedEvent if the
1238    * event doesn't match a known event name.
1239    *
1240    * @param aName the event name to look up
1241    */
1242   static mozilla::EventMessage GetEventMessage(nsIAtom* aName);
1243 
1244   /**
1245    * Returns the EventMessage and nsIAtom to be used for event listener
1246    * registration.
1247    */
1248   static mozilla::EventMessage
1249   GetEventMessageAndAtomForListener(const nsAString& aName, nsIAtom** aOnName);
1250 
1251   /**
1252    * Return the EventClassID for the event with the given name. The name is the
1253    * event name *without* the 'on' prefix. Returns eBasicEventClass if the event
1254    * is not known to be of any particular event class.
1255    *
1256    * @param aName the event name to look up
1257    */
1258   static mozilla::EventClassID GetEventClassID(const nsAString& aName);
1259 
1260   /**
1261    * Return the event message and atom for the event with the given name.
1262    * The name is the event name *without* the 'on' prefix.
1263    * Returns eUnidentifiedEvent on the aEventID if the
1264    * event doesn't match a known event name in the category.
1265    *
1266    * @param aName the event name to look up
1267    * @param aEventClassID only return event id for aEventClassID
1268    */
1269   static nsIAtom* GetEventMessageAndAtom(const nsAString& aName,
1270                                          mozilla::EventClassID aEventClassID,
1271                                          mozilla::EventMessage* aEventMessage);
1272 
1273   /**
1274    * Used only during traversal of the XPCOM graph by the cycle
1275    * collector: push a pointer to the listener manager onto the
1276    * children deque, if it exists. Do nothing if there is no listener
1277    * manager.
1278    *
1279    * Crucially: does not perform any refcounting operations.
1280    *
1281    * @param aNode The node to traverse.
1282    * @param children The buffer to push a listener manager pointer into.
1283    */
1284   static void TraverseListenerManager(nsINode *aNode,
1285                                       nsCycleCollectionTraversalCallback &cb);
1286 
1287   /**
1288    * Get the eventlistener manager for aNode, creating it if it does not
1289    * already exist.
1290    *
1291    * @param aNode The node for which to get the eventlistener manager.
1292    */
1293   static mozilla::EventListenerManager*
1294     GetListenerManagerForNode(nsINode* aNode);
1295   /**
1296    * Get the eventlistener manager for aNode, returning null if it does not
1297    * already exist.
1298    *
1299    * @param aNode The node for which to get the eventlistener manager.
1300    */
1301   static mozilla::EventListenerManager*
1302     GetExistingListenerManagerForNode(const nsINode* aNode);
1303 
1304   static void UnmarkGrayJSListenersInCCGenerationDocuments();
1305 
1306   /**
1307    * Remove the eventlistener manager for aNode.
1308    *
1309    * @param aNode The node for which to remove the eventlistener manager.
1310    */
1311   static void RemoveListenerManager(nsINode *aNode);
1312 
IsInitialized()1313   static bool IsInitialized()
1314   {
1315     return sInitialized;
1316   }
1317 
1318   /**
1319    * Checks if the localname/prefix/namespace triple is valid wrt prefix
1320    * and namespace according to the Namespaces in XML and DOM Code
1321    * specfications.
1322    *
1323    * @param aLocalname localname of the node
1324    * @param aPrefix prefix of the node
1325    * @param aNamespaceID namespace of the node
1326    */
1327   static bool IsValidNodeName(nsIAtom *aLocalName, nsIAtom *aPrefix,
1328                                 int32_t aNamespaceID);
1329 
1330   /**
1331    * Creates a DocumentFragment from text using a context node to resolve
1332    * namespaces.
1333    *
1334    * Note! In the HTML case with the HTML5 parser enabled, this is only called
1335    * from Range.createContextualFragment() and the implementation here is
1336    * quirky accordingly (html context node behaves like a body context node).
1337    * If you don't want that quirky behavior, don't use this method as-is!
1338    *
1339    * @param aContextNode the node which is used to resolve namespaces
1340    * @param aFragment the string which is parsed to a DocumentFragment
1341    * @param aReturn the resulting fragment
1342    * @param aPreventScriptExecution whether to mark scripts as already started
1343    */
1344   static nsresult CreateContextualFragment(nsINode* aContextNode,
1345                                            const nsAString& aFragment,
1346                                            bool aPreventScriptExecution,
1347                                            nsIDOMDocumentFragment** aReturn);
1348   static already_AddRefed<mozilla::dom::DocumentFragment>
1349   CreateContextualFragment(nsINode* aContextNode, const nsAString& aFragment,
1350                            bool aPreventScriptExecution,
1351                            mozilla::ErrorResult& aRv);
1352 
1353   /**
1354    * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
1355    *
1356    * @param aSourceBuffer the string being set as innerHTML
1357    * @param aTargetNode the target container
1358    * @param aContextLocalName local name of context node
1359    * @param aContextNamespace namespace of context node
1360    * @param aQuirks true to make <table> not close <p>
1361    * @param aPreventScriptExecution true to prevent scripts from executing;
1362    *        don't set to false when parsing into a target node that has been
1363    *        bound to tree.
1364    * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1365    *         fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1366    *         long and NS_OK otherwise.
1367    */
1368   static nsresult ParseFragmentHTML(const nsAString& aSourceBuffer,
1369                                     nsIContent* aTargetNode,
1370                                     nsIAtom* aContextLocalName,
1371                                     int32_t aContextNamespace,
1372                                     bool aQuirks,
1373                                     bool aPreventScriptExecution);
1374 
1375   /**
1376    * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
1377    *
1378    * @param aSourceBuffer the string being set as innerHTML
1379    * @param aTargetNode the target container
1380    * @param aTagStack the namespace mapping context
1381    * @param aPreventExecution whether to mark scripts as already started
1382    * @param aReturn the result fragment
1383    * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1384    *         fragments is made, a return code from the XML parser.
1385    */
1386   static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
1387                                    nsIDocument* aDocument,
1388                                    nsTArray<nsString>& aTagStack,
1389                                    bool aPreventScriptExecution,
1390                                    nsIDOMDocumentFragment** aReturn);
1391 
1392   /**
1393    * Parse a string into a document using the HTML parser.
1394    * Script elements are marked unexecutable.
1395    *
1396    * @param aSourceBuffer the string to parse as an HTML document
1397    * @param aTargetDocument the document object to parse into. Must not have
1398    *                        child nodes.
1399    * @param aScriptingEnabledForNoscriptParsing whether <noscript> is parsed
1400    *                                            as if scripting was enabled
1401    * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1402    *         fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1403    *         long and NS_OK otherwise.
1404    */
1405   static nsresult ParseDocumentHTML(const nsAString& aSourceBuffer,
1406                                     nsIDocument* aTargetDocument,
1407                                     bool aScriptingEnabledForNoscriptParsing);
1408 
1409   /**
1410    * Converts HTML source to plain text by parsing the source and using the
1411    * plain text serializer on the resulting tree.
1412    *
1413    * @param aSourceBuffer the string to parse as an HTML document
1414    * @param aResultBuffer the string where the plain text result appears;
1415    *                      may be the same string as aSourceBuffer
1416    * @param aFlags Flags from nsIDocumentEncoder.
1417    * @param aWrapCol Number of columns after which to line wrap; 0 for no
1418    *                 auto-wrapping
1419    * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1420    *         fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1421    *         long and NS_OK otherwise.
1422    */
1423   static nsresult ConvertToPlainText(const nsAString& aSourceBuffer,
1424                                      nsAString& aResultBuffer,
1425                                      uint32_t aFlags,
1426                                      uint32_t aWrapCol);
1427 
1428   /**
1429    * Sets the text contents of a node by replacing all existing children
1430    * with a single text child.
1431    *
1432    * The function always notifies.
1433    *
1434    * Will reuse the first text child if one is available. Will not reuse
1435    * existing cdata children.
1436    *
1437    * @param aContent Node to set contents of.
1438    * @param aValue   Value to set contents to.
1439    * @param aTryReuse When true, the function will try to reuse an existing
1440    *                  textnodes rather than always creating a new one.
1441    */
1442   static nsresult SetNodeTextContent(nsIContent* aContent,
1443                                      const nsAString& aValue,
1444                                      bool aTryReuse);
1445 
1446   /**
1447    * Get the textual contents of a node. This is a concatenation of all
1448    * textnodes that are direct or (depending on aDeep) indirect children
1449    * of the node.
1450    *
1451    * NOTE! No serialization takes place and <br> elements
1452    * are not converted into newlines. Only textnodes and cdata nodes are
1453    * added to the result.
1454    *
1455    * @see nsLayoutUtils::GetFrameTextContent
1456    *
1457    * @param aNode Node to get textual contents of.
1458    * @param aDeep If true child elements of aNode are recursivly descended
1459    *              into to find text children.
1460    * @param aResult the result. Out param.
1461    * @return false on out of memory errors, true otherwise.
1462    */
1463   MOZ_MUST_USE
1464   static bool GetNodeTextContent(nsINode* aNode, bool aDeep,
1465                                  nsAString& aResult, const mozilla::fallible_t&);
1466 
1467   static void GetNodeTextContent(nsINode* aNode, bool aDeep,
1468                                  nsAString& aResult);
1469 
1470   /**
1471    * Same as GetNodeTextContents but appends the result rather than sets it.
1472    */
1473   static bool AppendNodeTextContent(nsINode* aNode, bool aDeep,
1474                                     nsAString& aResult, const mozilla::fallible_t&);
1475 
1476   /**
1477    * Utility method that checks if a given node has any non-empty children. This
1478    * method does not descend recursively into children by default.
1479    *
1480    * @param aDiscoverMode Set to eRecurseIntoChildren to descend recursively
1481    * into children.
1482    */
1483   enum TextContentDiscoverMode : uint8_t {
1484     eRecurseIntoChildren, eDontRecurseIntoChildren
1485   };
1486 
1487   static bool HasNonEmptyTextContent(
1488     nsINode* aNode,
1489     TextContentDiscoverMode aDiscoverMode = eDontRecurseIntoChildren);
1490 
1491   /**
1492    * Delete strings allocated for nsContentList matches
1493    */
1494   static void DestroyMatchString(void* aData);
1495 
1496   /**
1497    * Unbinds the content from the tree and nulls it out if it's not null.
1498    */
1499   static void DestroyAnonymousContent(nsCOMPtr<nsIContent>* aContent);
1500   static void DestroyAnonymousContent(nsCOMPtr<Element>* aElement);
1501 
1502   /*
1503    * Notify when the first XUL menu is opened and when the all XUL menus are
1504    * closed. At opening, aInstalling should be TRUE, otherwise, it should be
1505    * FALSE.
1506    */
1507   static void NotifyInstalledMenuKeyboardListener(bool aInstalling);
1508 
1509   /**
1510    * Returns true if aPrincipal is the system principal.
1511    */
1512   static bool IsSystemPrincipal(nsIPrincipal* aPrincipal);
1513 
1514   /**
1515    * Returns true if aPrincipal is an nsExpandedPrincipal.
1516    */
1517   static bool IsExpandedPrincipal(nsIPrincipal* aPrincipal);
1518 
1519   /**
1520    * Returns true if aPrincipal is the system or an nsExpandedPrincipal.
1521    */
IsSystemOrExpandedPrincipal(nsIPrincipal * aPrincipal)1522   static bool IsSystemOrExpandedPrincipal(nsIPrincipal* aPrincipal)
1523   {
1524     return IsSystemPrincipal(aPrincipal) || IsExpandedPrincipal(aPrincipal);
1525   }
1526 
1527   /**
1528    * Gets the system principal from the security manager.
1529    */
1530   static nsIPrincipal* GetSystemPrincipal();
1531 
1532   /**
1533    * Gets the null subject principal singleton. This is only useful for
1534    * assertions.
1535    */
GetNullSubjectPrincipal()1536   static nsIPrincipal* GetNullSubjectPrincipal() { return sNullSubjectPrincipal; }
1537 
1538   /**
1539    * *aResourcePrincipal is a principal describing who may access the contents
1540    * of a resource. The resource can only be consumed by a principal that
1541    * subsumes *aResourcePrincipal. MAKE SURE THAT NOTHING EVER ACTS WITH THE
1542    * AUTHORITY OF *aResourcePrincipal.
1543    * It may be null to indicate that the resource has no data from any origin
1544    * in it yet and anything may access the resource.
1545    * Additional data is being mixed into the resource from aExtraPrincipal
1546    * (which may be null; if null, no data is being mixed in and this function
1547    * will do nothing). Update *aResourcePrincipal to reflect the new data.
1548    * If *aResourcePrincipal subsumes aExtraPrincipal, nothing needs to change,
1549    * otherwise *aResourcePrincipal is replaced with the system principal.
1550    * Returns true if *aResourcePrincipal changed.
1551    */
1552   static bool CombineResourcePrincipals(nsCOMPtr<nsIPrincipal>* aResourcePrincipal,
1553                                         nsIPrincipal* aExtraPrincipal);
1554 
1555   /**
1556    * Trigger a link with uri aLinkURI. If aClick is false, this triggers a
1557    * mouseover on the link, otherwise it triggers a load after doing a
1558    * security check using aContent's principal.
1559    *
1560    * @param aContent the node on which a link was triggered.
1561    * @param aPresContext the pres context, must be non-null.
1562    * @param aLinkURI the URI of the link, must be non-null.
1563    * @param aTargetSpec the target (like target=, may be empty).
1564    * @param aClick whether this was a click or not (if false, this method
1565    *               assumes you just hovered over the link).
1566    * @param aIsUserTriggered whether the user triggered the link. This would be
1567    *                         false for loads from auto XLinks or from the
1568    *                         click() method if we ever implement it.
1569    * @param aIsTrusted If false, JS Context will be pushed to stack
1570    *                   when the link is triggered.
1571    */
1572   static void TriggerLink(nsIContent *aContent, nsPresContext *aPresContext,
1573                           nsIURI *aLinkURI, const nsString& aTargetSpec,
1574                           bool aClick, bool aIsUserTriggered,
1575                           bool aIsTrusted);
1576 
1577   /**
1578    * Get the link location.
1579    */
1580   static void GetLinkLocation(mozilla::dom::Element* aElement,
1581                               nsString& aLocationString);
1582 
1583   /**
1584    * Return top-level widget in the parent chain.
1585    */
1586   static nsIWidget* GetTopLevelWidget(nsIWidget* aWidget);
1587 
1588   /**
1589    * Return the localized ellipsis for UI.
1590    */
1591   static const nsDependentString GetLocalizedEllipsis();
1592 
1593   /**
1594    * Hide any XUL popups associated with aDocument, including any documents
1595    * displayed in child frames. Does nothing if aDocument is null.
1596    */
1597   static void HidePopupsInDocument(nsIDocument* aDocument);
1598 
1599   /**
1600    * Retrieve the current drag session, or null if no drag is currently occuring
1601    */
1602   static already_AddRefed<nsIDragSession> GetDragSession();
1603 
1604   /*
1605    * Initialize and set the dataTransfer field of an WidgetDragEvent.
1606    */
1607   static nsresult SetDataTransferInEvent(mozilla::WidgetDragEvent* aDragEvent);
1608 
1609   // filters the drag and drop action to fit within the effects allowed and
1610   // returns it.
1611   static uint32_t FilterDropEffect(uint32_t aAction, uint32_t aEffectAllowed);
1612 
1613   /*
1614    * Return true if the target of a drop event is a content document that is
1615    * an ancestor of the document for the source of the drag.
1616    */
1617   static bool CheckForSubFrameDrop(nsIDragSession* aDragSession,
1618                                    mozilla::WidgetDragEvent* aDropEvent);
1619 
1620   /**
1621    * Return true if aURI is a local file URI (i.e. file://).
1622    */
1623   static bool URIIsLocalFile(nsIURI *aURI);
1624 
1625   /**
1626    * Get the application manifest URI for this document.  The manifest URI
1627    * is specified in the manifest= attribute of the root element of the
1628    * document.
1629    *
1630    * @param aDocument The document that lists the manifest.
1631    * @param aURI The manifest URI.
1632    */
1633   static void GetOfflineAppManifest(nsIDocument *aDocument, nsIURI **aURI);
1634 
1635   /**
1636    * Check whether an application should be allowed to use offline APIs.
1637    */
1638   static bool OfflineAppAllowed(nsIURI *aURI);
1639 
1640   /**
1641    * Check whether an application should be allowed to use offline APIs.
1642    */
1643   static bool OfflineAppAllowed(nsIPrincipal *aPrincipal);
1644 
1645   /**
1646    * If offline-apps.allow_by_default is true, we set offline-app permission
1647    * for the principal and return true.  Otherwise false.
1648    */
1649   static bool MaybeAllowOfflineAppByDefault(nsIPrincipal *aPrincipal);
1650 
1651   /**
1652    * Increases the count of blockers preventing scripts from running.
1653    * NOTE: You might want to use nsAutoScriptBlocker rather than calling
1654    * this directly
1655    */
1656   static void AddScriptBlocker();
1657 
1658   /**
1659    * Decreases the count of blockers preventing scripts from running.
1660    * NOTE: You might want to use nsAutoScriptBlocker rather than calling
1661    * this directly
1662    *
1663    * WARNING! Calling this function could synchronously execute scripts.
1664    */
1665   static void RemoveScriptBlocker();
1666 
1667   /**
1668    * Add a runnable that is to be executed as soon as it's safe to execute
1669    * scripts.
1670    * NOTE: If it's currently safe to execute scripts, aRunnable will be run
1671    *       synchronously before the function returns.
1672    *
1673    * @param aRunnable  The nsIRunnable to run as soon as it's safe to execute
1674    *                   scripts. Passing null is allowed and results in nothing
1675    *                   happening. It is also allowed to pass an object that
1676    *                   has not yet been AddRefed.
1677    */
1678   static void AddScriptRunner(already_AddRefed<nsIRunnable> aRunnable);
1679   static void AddScriptRunner(nsIRunnable* aRunnable);
1680 
1681   /**
1682    * Returns true if it's safe to execute content script and false otherwise.
1683    *
1684    * The only known case where this lies is mutation events. They run, and can
1685    * run anything else, when this function returns false, but this is ok.
1686    */
IsSafeToRunScript()1687   static bool IsSafeToRunScript() {
1688     return sScriptBlockerCount == 0;
1689   }
1690 
1691   // XXXcatalinb: workaround for weird include error when trying to reference
1692   // ipdl types in WindowWatcher.
1693   static nsIWindowProvider*
1694   GetWindowProviderForContentProcess();
1695 
1696   // Returns the browser window with the most recent time stamp that is
1697   // not in private browsing mode.
1698   static already_AddRefed<nsPIDOMWindowOuter>
1699   GetMostRecentNonPBWindow();
1700 
1701   /**
1702    * Call this function if !IsSafeToRunScript() and we fail to run the script
1703    * (rather than using AddScriptRunner as we usually do). |aDocument| is
1704    * optional as it is only used for showing the URL in the console.
1705    */
1706   static void WarnScriptWasIgnored(nsIDocument* aDocument);
1707 
1708   /**
1709    * Add a "synchronous section", in the form of an nsIRunnable run once the
1710    * event loop has reached a "stable state". |aRunnable| must not cause any
1711    * queued events to be processed (i.e. must not spin the event loop).
1712    * We've reached a stable state when the currently executing task/event has
1713    * finished, see
1714    * http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#synchronous-section
1715    * In practice this runs aRunnable once the currently executing event
1716    * finishes. If called multiple times per task/event, all the runnables will
1717    * be executed, in the order in which RunInStableState() was called.
1718    */
1719   static void RunInStableState(already_AddRefed<nsIRunnable> aRunnable);
1720 
1721   /* Add a "synchronous section", in the form of an nsIRunnable run once the
1722    * event loop has reached a "metastable state". |aRunnable| must not cause any
1723    * queued events to be processed (i.e. must not spin the event loop).
1724    * We've reached a metastable state when the currently executing task or
1725    * microtask has finished.  This is not specced at this time.
1726    * In practice this runs aRunnable once the currently executing task or
1727    * microtask finishes.  If called multiple times per microtask, all the
1728    * runnables will be executed, in the order in which RunInMetastableState()
1729    * was called
1730    */
1731   static void RunInMetastableState(already_AddRefed<nsIRunnable> aRunnable);
1732 
1733   // Call EnterMicroTask when you're entering JS execution.
1734   // Usually the best way to do this is to use nsAutoMicroTask.
1735   static void EnterMicroTask();
1736   static void LeaveMicroTask();
1737 
1738   static bool IsInMicroTask();
1739   static uint32_t MicroTaskLevel();
1740   static void SetMicroTaskLevel(uint32_t aLevel);
1741 
1742   static void PerformMainThreadMicroTaskCheckpoint();
1743 
1744   /* Process viewport META data. This gives us information for the scale
1745    * and zoom of a page on mobile devices. We stick the information in
1746    * the document header and use it later on after rendering.
1747    *
1748    * See Bug #436083
1749    */
1750   static nsresult ProcessViewportInfo(nsIDocument *aDocument,
1751                                       const nsAString &viewportInfo);
1752 
1753   static nsIScriptContext* GetContextForEventHandlers(nsINode* aNode,
1754                                                       nsresult* aRv);
1755 
1756   static JSContext *GetCurrentJSContext();
1757   static JSContext *GetCurrentJSContextForThread();
1758 
1759   /**
1760    * Case insensitive comparison between two strings. However it only ignores
1761    * case for ASCII characters a-z.
1762    */
1763   static bool EqualsIgnoreASCIICase(const nsAString& aStr1,
1764                                     const nsAString& aStr2);
1765 
1766   /**
1767    * Convert ASCII A-Z to a-z.
1768    */
1769   static void ASCIIToLower(nsAString& aStr);
1770   static void ASCIIToLower(nsACString& aStr);
1771   static void ASCIIToLower(const nsAString& aSource, nsAString& aDest);
1772   static void ASCIIToLower(const nsACString& aSource, nsACString& aDest);
1773 
1774   /**
1775    * Convert ASCII a-z to A-Z.
1776    */
1777   static void ASCIIToUpper(nsAString& aStr);
1778   static void ASCIIToUpper(nsACString& aStr);
1779   static void ASCIIToUpper(const nsAString& aSource, nsAString& aDest);
1780   static void ASCIIToUpper(const nsACString& aSource, nsACString& aDest);
1781 
1782   /**
1783    * Return whether aStr contains an ASCII uppercase character.
1784    */
1785   static bool StringContainsASCIIUpper(const nsAString& aStr);
1786 
1787   // Returns NS_OK for same origin, error (NS_ERROR_DOM_BAD_URI) if not.
1788   static nsresult CheckSameOrigin(nsIChannel *aOldChannel, nsIChannel *aNewChannel);
1789   static nsIInterfaceRequestor* SameOriginChecker();
1790 
1791   /**
1792    * Get the Origin of the passed in nsIPrincipal or nsIURI. If the passed in
1793    * nsIURI or the URI of the passed in nsIPrincipal does not have a host, the
1794    * origin is set to 'null'.
1795    *
1796    * The ASCII versions return a ASCII strings that are puny-code encoded,
1797    * suitable for, for example, header values. The UTF versions return strings
1798    * containing international characters.
1799    *
1800    * @pre aPrincipal/aOrigin must not be null.
1801    *
1802    * @note this should be used for HTML5 origin determination.
1803    */
1804   static nsresult GetASCIIOrigin(nsIPrincipal* aPrincipal,
1805                                  nsACString& aOrigin);
1806   static nsresult GetASCIIOrigin(nsIURI* aURI, nsACString& aOrigin);
1807   static nsresult GetUTFOrigin(nsIPrincipal* aPrincipal,
1808                                nsAString& aOrigin);
1809   static nsresult GetUTFOrigin(nsIURI* aURI, nsAString& aOrigin);
1810 
1811   /**
1812    * This method creates and dispatches "command" event, which implements
1813    * nsIDOMXULCommandEvent.
1814    * If aShell is not null, dispatching goes via
1815    * nsIPresShell::HandleDOMEventWithTarget.
1816    */
1817   static nsresult DispatchXULCommand(nsIContent* aTarget,
1818                                      bool aTrusted,
1819                                      nsIDOMEvent* aSourceEvent = nullptr,
1820                                      nsIPresShell* aShell = nullptr,
1821                                      bool aCtrl = false,
1822                                      bool aAlt = false,
1823                                      bool aShift = false,
1824                                      bool aMeta = false);
1825 
1826   static bool CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel, bool aAllowIfInheritsPrincipal);
1827 
1828   /**
1829    * The method checks whether the caller can access native anonymous content.
1830    * If there is no JS in the stack or privileged JS is running, this
1831    * method returns true, otherwise false.
1832    */
1833   static bool CanAccessNativeAnon();
1834 
1835   MOZ_MUST_USE
1836   static nsresult WrapNative(JSContext *cx, nsISupports *native,
1837                              const nsIID* aIID, JS::MutableHandle<JS::Value> vp,
1838                              bool aAllowWrapping = true)
1839   {
1840     return WrapNative(cx, native, nullptr, aIID, vp, aAllowWrapping);
1841   }
1842 
1843   // Same as the WrapNative above, but use this one if aIID is nsISupports' IID.
1844   MOZ_MUST_USE
1845   static nsresult WrapNative(JSContext *cx, nsISupports *native,
1846                              JS::MutableHandle<JS::Value> vp,
1847                              bool aAllowWrapping = true)
1848   {
1849     return WrapNative(cx, native, nullptr, nullptr, vp, aAllowWrapping);
1850   }
1851 
1852   MOZ_MUST_USE
1853   static nsresult WrapNative(JSContext *cx, nsISupports *native,
1854                              nsWrapperCache *cache,
1855                              JS::MutableHandle<JS::Value> vp,
1856                              bool aAllowWrapping = true)
1857   {
1858     return WrapNative(cx, native, cache, nullptr, vp, aAllowWrapping);
1859   }
1860 
1861   /**
1862    * Creates an arraybuffer from a binary string.
1863    */
1864   static nsresult CreateArrayBuffer(JSContext *aCx, const nsACString& aData,
1865                                     JSObject** aResult);
1866 
1867   static void StripNullChars(const nsAString& aInStr, nsAString& aOutStr);
1868 
1869   /**
1870    * Strip all \n, \r and nulls from the given string
1871    * @param aString the string to remove newlines from [in/out]
1872    */
1873   static void RemoveNewlines(nsString &aString);
1874 
1875   /**
1876    * Convert Windows and Mac platform linebreaks to \n.
1877    * @param aString the string to convert the newlines inside [in/out]
1878    */
1879   static void PlatformToDOMLineBreaks(nsString &aString);
1880   MOZ_MUST_USE
1881   static bool PlatformToDOMLineBreaks(nsString &aString,
1882                                       const mozilla::fallible_t&);
1883 
1884   /**
1885    * Populates aResultString with the contents of the string-buffer aBuf, up
1886    * to aBuf's null-terminator.  aBuf must not be null. Ownership of the string
1887    * is not transferred.
1888    */
1889   static void PopulateStringFromStringBuffer(nsStringBuffer* aBuf,
1890                                              nsAString& aResultString);
1891 
IsHandlingKeyBoardEvent()1892   static bool IsHandlingKeyBoardEvent()
1893   {
1894     return sIsHandlingKeyBoardEvent;
1895   }
1896 
SetIsHandlingKeyBoardEvent(bool aHandling)1897   static void SetIsHandlingKeyBoardEvent(bool aHandling)
1898   {
1899     sIsHandlingKeyBoardEvent = aHandling;
1900   }
1901 
1902   /**
1903    * Utility method for getElementsByClassName.  aRootNode is the node (either
1904    * document or element), which getElementsByClassName was called on.
1905    */
1906   static already_AddRefed<nsContentList>
GetElementsByClassName(nsINode * aRootNode,const nsAString & aClasses)1907   GetElementsByClassName(nsINode* aRootNode, const nsAString& aClasses)
1908   {
1909     NS_PRECONDITION(aRootNode, "Must have root node");
1910 
1911     return NS_GetFuncStringHTMLCollection(aRootNode, MatchClassNames,
1912                                           DestroyClassNameArray,
1913                                           AllocClassMatchingInfo,
1914                                           aClasses);
1915   }
1916 
1917   /**
1918    * Returns a presshell for this document, if there is one. This will be
1919    * aDoc's direct presshell if there is one, otherwise we'll look at all
1920    * ancestor documents to try to find a presshell, so for example this can
1921    * still find a presshell for documents in display:none frames that have
1922    * no presentation. So you have to be careful how you use this presshell ---
1923    * getting generic data like a device context or widget from it is OK, but it
1924    * might not be this document's actual presentation.
1925    */
1926   static nsIPresShell* FindPresShellForDocument(const nsIDocument* aDoc);
1927 
1928   /**
1929    * Returns the widget for this document if there is one. Looks at all ancestor
1930    * documents to try to find a widget, so for example this can still find a
1931    * widget for documents in display:none frames that have no presentation.
1932    */
1933   static nsIWidget* WidgetForDocument(const nsIDocument* aDoc);
1934 
1935   /**
1936    * Returns a layer manager to use for the given document. Basically we
1937    * look up the document hierarchy for the first document which has
1938    * a presentation with an associated widget, and use that widget's
1939    * layer manager.
1940    *
1941    * @param aDoc the document for which to return a layer manager.
1942    * @param aAllowRetaining an outparam that states whether the returned
1943    * layer manager should be used for retained layers
1944    */
1945   static already_AddRefed<mozilla::layers::LayerManager>
1946   LayerManagerForDocument(const nsIDocument *aDoc);
1947 
1948   /**
1949    * Returns a layer manager to use for the given document. Basically we
1950    * look up the document hierarchy for the first document which has
1951    * a presentation with an associated widget, and use that widget's
1952    * layer manager. In addition to the normal layer manager lookup this will
1953    * specifically request a persistent layer manager. This means that the layer
1954    * manager is expected to remain the layer manager for the document in the
1955    * forseeable future. This function should be used carefully as it may change
1956    * the document's layer manager.
1957    *
1958    * @param aDoc the document for which to return a layer manager.
1959    * @param aAllowRetaining an outparam that states whether the returned
1960    * layer manager should be used for retained layers
1961    */
1962   static already_AddRefed<mozilla::layers::LayerManager>
1963   PersistentLayerManagerForDocument(nsIDocument *aDoc);
1964 
1965   /**
1966    * Determine whether a content node is focused or not,
1967    *
1968    * @param aContent the content node to check
1969    * @return true if the content node is focused, false otherwise.
1970    */
1971   static bool IsFocusedContent(const nsIContent *aContent);
1972 
1973   /**
1974    * Returns true if the DOM full-screen API is enabled.
1975    */
1976   static bool IsFullScreenApiEnabled();
1977 
1978   /**
1979    * Returns true if the unprefixed fullscreen API is enabled.
1980    */
IsUnprefixedFullscreenApiEnabled()1981   static bool IsUnprefixedFullscreenApiEnabled()
1982     { return sIsUnprefixedFullscreenApiEnabled; }
1983 
1984   /**
1985    * Returns true if requests for full-screen are allowed in the current
1986    * context. Requests are only allowed if the user initiated them (like with
1987    * a mouse-click or key press), unless this check has been disabled by
1988    * setting the pref "full-screen-api.allow-trusted-requests-only" to false.
1989    */
1990   static bool IsRequestFullScreenAllowed();
1991 
1992   /**
1993    * Returns true if calling execCommand with 'cut' or 'copy' arguments
1994    * is restricted to chrome code.
1995    */
IsCutCopyRestricted()1996   static bool IsCutCopyRestricted()
1997   {
1998     return !sIsCutCopyAllowed;
1999   }
2000 
2001   /**
2002    * Returns true if calling execCommand with 'cut' or 'copy' arguments is
2003    * allowed in the current context. These are only allowed if the user initiated
2004    * them (like with a mouse-click or key press).
2005    */
2006   static bool IsCutCopyAllowed();
2007 
2008   /*
2009    * Returns true if the performance timing APIs are enabled.
2010    */
IsPerformanceTimingEnabled()2011   static bool IsPerformanceTimingEnabled()
2012   {
2013     return sIsPerformanceTimingEnabled;
2014   }
2015 
2016   /*
2017    * Returns true if user timing API should print to console.
2018    */
IsUserTimingLoggingEnabled()2019   static bool IsUserTimingLoggingEnabled()
2020   {
2021     return sIsUserTimingLoggingEnabled;
2022   }
2023 
2024   /*
2025    * Returns true if the performance timing APIs are enabled.
2026    */
IsResourceTimingEnabled()2027   static bool IsResourceTimingEnabled()
2028   {
2029     return sIsResourceTimingEnabled;
2030   }
2031 
2032   /*
2033    * Returns true if notification should be sent for peformance timing events.
2034    */
SendPerformanceTimingNotifications()2035   static bool SendPerformanceTimingNotifications()
2036   {
2037     return sSendPerformanceTimingNotifications;
2038   }
2039 
2040   /*
2041    * Returns true if the frame timing APIs are enabled.
2042    */
2043   static bool IsFrameTimingEnabled();
2044 
2045   /*
2046    * Returns true if URL setters should percent encode the Hash/Ref segment
2047    * and getters should return the percent decoded value of the segment
2048    */
EncodeDecodeURLHash()2049   static bool EncodeDecodeURLHash()
2050   {
2051     return sEncodeDecodeURLHash;
2052   }
2053 
2054   /*
2055    * Returns true if URL getters should percent decode the value of the segment
2056    */
GettersDecodeURLHash()2057   static bool GettersDecodeURLHash()
2058   {
2059     return sGettersDecodeURLHash && sEncodeDecodeURLHash;
2060   }
2061 
2062   /*
2063    * Returns true if the browser should attempt to prevent content scripts
2064    * from collecting distinctive information about the browser that could
2065    * be used to "fingerprint" and track the user across websites.
2066    */
ResistFingerprinting()2067   static bool ResistFingerprinting()
2068   {
2069     return sPrivacyResistFingerprinting;
2070   }
2071 
2072   /*
2073    * Returns true if the browser should attempt to prevent the given caller type
2074    * from collecting distinctive information about the browser that could
2075    * be used to "fingerprint" and track the user across websites.
2076    */
ResistFingerprinting(mozilla::dom::CallerType aCallerType)2077   static bool ResistFingerprinting(mozilla::dom::CallerType aCallerType)
2078   {
2079     return aCallerType != mozilla::dom::CallerType::System &&
2080            ResistFingerprinting();
2081   }
2082 
2083   /**
2084    * Returns true if the browser should show busy cursor when loading page.
2085    */
UseActivityCursor()2086   static bool UseActivityCursor()
2087   {
2088     return sUseActivityCursor;
2089   }
2090 
2091   /**
2092    * Return true if this doc is controlled by a ServiceWorker.
2093    */
2094   static bool IsControlledByServiceWorker(nsIDocument* aDocument);
2095 
2096   /**
2097    * Fire mutation events for changes caused by parsing directly into a
2098    * context node.
2099    *
2100    * @param aDoc the document of the node
2101    * @param aDest the destination node that got stuff appended to it
2102    * @param aOldChildCount the number of children the node had before parsing
2103    */
2104   static void FireMutationEventsForDirectParsing(nsIDocument* aDoc,
2105                                                  nsIContent* aDest,
2106                                                  int32_t aOldChildCount);
2107 
2108   /**
2109    * Returns true if the content is in a document and contains a plugin
2110    * which we don't control event dispatch for, i.e. do any plugins in this
2111    * doc tree receive key events outside of our control? This always returns
2112    * false on MacOSX.
2113    */
2114   static bool HasPluginWithUncontrolledEventDispatch(nsIContent* aContent);
2115 
2116   /**
2117    * Returns the root document in a document hierarchy. Normally this
2118    * will be the chrome document.
2119    */
2120   static nsIDocument* GetRootDocument(nsIDocument* aDoc);
2121 
2122   /**
2123    * Returns true if aWin and the current pointer lock document
2124    * have common scriptable top window.
2125    */
2126   static bool IsInPointerLockContext(nsPIDOMWindowOuter* aWin);
2127 
2128   /**
2129    * Returns the time limit on handling user input before
2130    * EventStateManager::IsHandlingUserInput() stops returning true.
2131    * This enables us to detect long running user-generated event handlers.
2132    */
2133   static TimeDuration HandlingUserInputTimeout();
2134 
2135   static void GetShiftText(nsAString& text);
2136   static void GetControlText(nsAString& text);
2137   static void GetMetaText(nsAString& text);
2138   static void GetOSText(nsAString& text);
2139   static void GetAltText(nsAString& text);
2140   static void GetModifierSeparatorText(nsAString& text);
2141 
2142   /**
2143    * Returns if aContent has a tabbable subdocument.
2144    * A sub document isn't tabbable when it's a zombie document.
2145    *
2146    * @param aElement element to test.
2147    *
2148    * @return Whether the subdocument is tabbable.
2149    */
2150   static bool IsSubDocumentTabbable(nsIContent* aContent);
2151 
2152   /**
2153    * Returns if aNode ignores user focus.
2154    *
2155    * @param aNode node to test
2156    *
2157    * @return Whether the node ignores user focus.
2158    */
2159   static bool IsUserFocusIgnored(nsINode* aNode);
2160 
2161   /**
2162    * Returns if aContent has the 'scrollgrab' property.
2163    * aContent may be null (in this case false is returned).
2164    */
2165   static bool HasScrollgrab(nsIContent* aContent);
2166 
2167   /**
2168    * Flushes the layout tree (recursively)
2169    *
2170    * @param aWindow the window the flush should start at
2171    *
2172    */
2173   static void FlushLayoutForTree(nsPIDOMWindowOuter* aWindow);
2174 
2175   /**
2176    * Returns true if content with the given principal is allowed to use XUL
2177    * and XBL and false otherwise.
2178    */
2179   static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
2180 
2181   /**
2182    * Perform cleanup that's appropriate for XPCOM shutdown.
2183    */
2184   static void XPCOMShutdown();
2185 
2186   /**
2187    * Checks if internal PDF viewer is enabled.
2188    */
2189   static bool IsPDFJSEnabled();
2190 
2191   /**
2192    * Checks if internal SWF player is enabled.
2193    */
2194   static bool IsSWFPlayerEnabled();
2195 
2196   enum ContentViewerType
2197   {
2198       TYPE_UNSUPPORTED,
2199       TYPE_CONTENT,
2200       TYPE_PLUGIN,
2201       TYPE_UNKNOWN
2202   };
2203 
2204   static already_AddRefed<nsIDocumentLoaderFactory>
2205   FindInternalContentViewer(const nsACString& aType,
2206                             ContentViewerType* aLoaderType = nullptr);
2207 
2208   /**
2209    * This helper method returns true if the aPattern pattern matches aValue.
2210    * aPattern should not contain leading and trailing slashes (/).
2211    * The pattern has to match the entire value not just a subset.
2212    * aDocument must be a valid pointer (not null).
2213    *
2214    * This is following the HTML5 specification:
2215    * http://dev.w3.org/html5/spec/forms.html#attr-input-pattern
2216    *
2217    * WARNING: This method mutates aPattern and aValue!
2218    *
2219    * @param aValue    the string to check.
2220    * @param aPattern  the string defining the pattern.
2221    * @param aDocument the owner document of the element.
2222    * @result          whether the given string is matches the pattern.
2223    */
2224   static bool IsPatternMatching(nsAString& aValue, nsAString& aPattern,
2225                                   nsIDocument* aDocument);
2226 
2227   /**
2228    * Calling this adds support for
2229    * ontouch* event handler DOM attributes.
2230    */
2231   static void InitializeTouchEventTable();
2232 
2233   /**
2234    * Test whether the given URI always inherits a security context
2235    * from the document it comes from.
2236    */
2237   static nsresult URIInheritsSecurityContext(nsIURI *aURI, bool *aResult);
2238 
2239   /**
2240     * Called before a channel is created to query whether the new
2241     * channel should inherit the principal.
2242     *
2243     * The argument aLoadingPrincipal must not be null. The argument
2244     * aURI must be the URI of the new channel. If aInheritForAboutBlank
2245     * is true, then about:blank will be told to inherit the principal.
2246     * If aForceInherit is true, the new channel will be told to inherit
2247     * the principal no matter what.
2248     *
2249     * The return value is whether the new channel should inherit
2250     * the principal.
2251     */
2252   static bool ChannelShouldInheritPrincipal(nsIPrincipal* aLoadingPrincipal,
2253                                             nsIURI* aURI,
2254                                             bool aInheritForAboutBlank,
2255                                             bool aForceInherit);
2256 
2257   static nsresult Btoa(const nsAString& aBinaryData,
2258                        nsAString& aAsciiBase64String);
2259 
2260   static nsresult Atob(const nsAString& aAsciiString,
2261                        nsAString& aBinaryData);
2262 
2263   /**
2264    * Returns whether the input element passed in parameter has the autocomplete
2265    * functionality enabled. It is taking into account the form owner.
2266    * NOTE: the caller has to make sure autocomplete makes sense for the
2267    * element's type.
2268    *
2269    * @param aInput the input element to check. NOTE: aInput can't be null.
2270    * @return whether the input element has autocomplete enabled.
2271    */
2272   static bool IsAutocompleteEnabled(nsIDOMHTMLInputElement* aInput);
2273 
2274   enum AutocompleteAttrState : uint8_t
2275   {
2276     eAutocompleteAttrState_Unknown = 1,
2277     eAutocompleteAttrState_Invalid,
2278     eAutocompleteAttrState_Valid,
2279   };
2280   /**
2281    * Parses the value of the autocomplete attribute into aResult, ensuring it's
2282    * composed of valid tokens, otherwise the value "" is used.
2283    * Note that this method is used for form fields, not on a <form> itself.
2284    *
2285    * @return whether aAttr was valid and can be cached.
2286    */
2287   static AutocompleteAttrState
2288   SerializeAutocompleteAttribute(const nsAttrValue* aAttr,
2289                                  nsAString& aResult,
2290                                  AutocompleteAttrState aCachedState =
2291                                    eAutocompleteAttrState_Unknown);
2292 
2293   /* Variation that is used to retrieve a dictionary of the parts of the
2294    * autocomplete attribute.
2295    *
2296    * @return whether aAttr was valid and can be cached.
2297    */
2298   static AutocompleteAttrState
2299   SerializeAutocompleteAttribute(const nsAttrValue* aAttr,
2300                                  mozilla::dom::AutocompleteInfo& aInfo,
2301                                  AutocompleteAttrState aCachedState =
2302                                    eAutocompleteAttrState_Unknown);
2303 
2304   /**
2305    * This will parse aSource, to extract the value of the pseudo attribute
2306    * with the name specified in aName. See
2307    * http://www.w3.org/TR/xml-stylesheet/#NT-StyleSheetPI for the specification
2308    * which is used to parse aSource.
2309    *
2310    * @param aSource the string to parse
2311    * @param aName the name of the attribute to get the value for
2312    * @param aValue [out] the value for the attribute with name specified in
2313    *                     aAttribute. Empty if the attribute isn't present.
2314    * @return true     if the attribute exists and was successfully parsed.
2315    *         false if the attribute doesn't exist, or has a malformed
2316    *                  value, such as an unknown or unterminated entity.
2317    */
2318   static bool GetPseudoAttributeValue(const nsString& aSource, nsIAtom *aName,
2319                                       nsAString& aValue);
2320 
2321   /**
2322    * Returns true if the language name is a version of JavaScript and
2323    * false otherwise
2324    */
2325   static bool IsJavaScriptLanguage(const nsString& aName);
2326 
2327   /**
2328    * Returns the JSVersion for a string of the form '1.n', n = 0, ..., 8, and
2329    * JSVERSION_UNKNOWN for other strings.
2330    */
2331   static JSVersion ParseJavascriptVersion(const nsAString& aVersionStr);
2332 
2333   static bool IsJavascriptMIMEType(const nsAString& aMIMEType);
2334 
2335   static void SplitMimeType(const nsAString& aValue, nsString& aType,
2336                             nsString& aParams);
2337 
2338   /**
2339    * Function checks if the user is idle.
2340    *
2341    * @param aRequestedIdleTimeInMS    The idle observer's requested idle time.
2342    * @param aUserIsIdle               boolean indicating if the user
2343    *                                  is currently idle or not.   *
2344    * @return NS_OK                    NS_OK returned if the requested idle service and
2345    *                                  the current idle time were successfully obtained.
2346    *                                  NS_ERROR_FAILURE returned if the the requested
2347    *                                  idle service or the current idle were not obtained.
2348    */
2349   static nsresult IsUserIdle(uint32_t aRequestedIdleTimeInMS, bool* aUserIsIdle);
2350 
2351   /**
2352    * Takes a selection, and a text control element (<input> or <textarea>), and
2353    * returns the offsets in the text content corresponding to the selection.
2354    * The selection's anchor and focus must both be in the root node passed or a
2355    * descendant.
2356    *
2357    * @param aSelection      Selection to check
2358    * @param aRoot           Root <input> or <textarea> element
2359    * @param aOutStartOffset Output start offset
2360    * @param aOutEndOffset   Output end offset
2361    */
2362   static void GetSelectionInTextControl(mozilla::dom::Selection* aSelection,
2363                                         Element* aRoot,
2364                                         int32_t& aOutStartOffset,
2365                                         int32_t& aOutEndOffset);
2366 
2367   /**
2368    * Takes a frame for anonymous content within a text control (<input> or
2369    * <textarea>), and returns an offset in the text content, adjusted for a
2370    * trailing <br> frame.
2371    *
2372    * @param aOffsetFrame      Frame for the text content in which the offset
2373    *                          lies
2374    * @param aOffset           Offset as calculated by GetContentOffsetsFromPoint
2375    * @param aOutOffset        Output adjusted offset
2376    *
2377    * @see GetSelectionInTextControl for the original basis of this function.
2378    */
2379   static int32_t GetAdjustedOffsetInTextControl(nsIFrame* aOffsetFrame,
2380                                                 int32_t aOffset);
2381 
2382   static nsIEditor* GetHTMLEditor(nsPresContext* aPresContext);
2383 
2384   /**
2385    * Returns true if the browser.dom.window.dump.enabled pref is set.
2386    */
2387   static bool DOMWindowDumpEnabled();
2388 
2389   /**
2390    * Returns true if the privacy.donottrackheader.enabled pref is set.
2391    */
2392   static bool DoNotTrackEnabled();
2393 
2394   /**
2395    * Returns a LogModule that dump calls from content script are logged to.
2396    * This can be enabled with the 'Dump' module, and is useful for synchronizing
2397    * content JS to other logging modules.
2398    */
2399   static mozilla::LogModule* DOMDumpLog();
2400 
2401   /**
2402    * Returns whether a content is an insertion point for XBL
2403    * bindings or web components ShadowRoot. In web components,
2404    * this corresponds to a <content> element that participates
2405    * in node distribution. In XBL this corresponds to an
2406    * <xbl:children> element in anonymous content.
2407    *
2408    * @param aContent The content to test for being an insertion point.
2409    */
2410   static bool IsContentInsertionPoint(nsIContent* aContent);
2411 
2412 
2413   /**
2414    * Returns whether the children of the provided content are
2415    * nodes that are distributed to Shadow DOM insertion points.
2416    */
2417   static bool HasDistributedChildren(nsIContent* aContent);
2418 
2419   /**
2420    * Returns whether a given header is forbidden for an XHR or fetch
2421    * request.
2422    */
2423   static bool IsForbiddenRequestHeader(const nsACString& aHeader);
2424 
2425   /**
2426    * Returns whether a given header is forbidden for a system XHR
2427    * request.
2428    */
2429   static bool IsForbiddenSystemRequestHeader(const nsACString& aHeader);
2430 
2431   /**
2432    * Returns whether a given Content-Type header value is allowed
2433    * for a non-CORS XHR or fetch request.
2434    */
2435   static bool IsAllowedNonCorsContentType(const nsACString& aHeaderValue);
2436 
2437   /**
2438    * Returns whether a given header is forbidden for an XHR or fetch
2439    * response.
2440    */
2441   static bool IsForbiddenResponseHeader(const nsACString& aHeader);
2442 
2443   /**
2444    * Returns the inner window ID for the window associated with a request,
2445    */
2446   static uint64_t GetInnerWindowID(nsIRequest* aRequest);
2447 
2448   /**
2449    * If the hostname for aURI is an IPv6 it encloses it in brackets,
2450    * otherwise it just outputs the hostname in aHost.
2451    */
2452   static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsAString& aHost);
2453   static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsCString& aHost);
2454 
2455   /*
2456    * Call the given callback on all remote children of the given top-level
2457    * window. Return true from the callback to stop calling further children.
2458    */
2459   static void CallOnAllRemoteChildren(nsPIDOMWindowOuter* aWindow,
2460                                       CallOnRemoteChildFunction aCallback,
2461                                       void* aArg);
2462 
2463   /*
2464    * Call nsPIDOMWindow::SetKeyboardIndicators all all remote children. This is
2465    * in here rather than nsGlobalWindow because TabParent indirectly includes
2466    * Windows headers which aren't allowed there.
2467    */
2468   static void SetKeyboardIndicatorsOnRemoteChildren(nsPIDOMWindowOuter* aWindow,
2469                                                     UIStateChangeType aShowAccelerators,
2470                                                     UIStateChangeType aShowFocusRings);
2471 
2472   /**
2473    * Given an nsIFile, attempts to read it into aString.
2474    *
2475    * Note: Use sparingly! This causes main-thread I/O, which causes jank and all
2476    * other bad things.
2477    */
2478   static nsresult SlurpFileToString(nsIFile* aFile, nsACString& aString);
2479 
2480   /**
2481    * Returns true if the mime service thinks this file contains an image.
2482    *
2483    * The content type is returned in aType.
2484    */
2485   static bool IsFileImage(nsIFile* aFile, nsACString& aType);
2486 
2487   /**
2488    * Given an IPCDataTransferItem that has a flavor for which IsFlavorImage
2489    * returns true and whose IPCDataTransferData is of type nsCString (raw image
2490    * data), construct an imgIContainer for the image encoded by the transfer
2491    * item.
2492    */
2493   static nsresult DataTransferItemToImage(const mozilla::dom::IPCDataTransferItem& aItem,
2494                                           imgIContainer** aContainer);
2495 
2496   /**
2497    * Given a flavor obtained from an IPCDataTransferItem or nsITransferable,
2498    * returns true if we should treat the data as an image.
2499    */
2500   static bool IsFlavorImage(const nsACString& aFlavor);
2501 
2502   static nsresult IPCTransferableToTransferable(const mozilla::dom::IPCDataTransfer& aDataTransfer,
2503                                                 const bool& aIsPrivateData,
2504                                                 nsIPrincipal* aRequestingPrincipal,
2505                                                 nsITransferable* aTransferable,
2506                                                 mozilla::dom::nsIContentParent* aContentParent,
2507                                                 mozilla::dom::TabChild* aTabChild);
2508 
2509   static void TransferablesToIPCTransferables(nsIArray* aTransferables,
2510                                               nsTArray<mozilla::dom::IPCDataTransfer>& aIPC,
2511                                               bool aInSyncMessage,
2512                                               mozilla::dom::nsIContentChild* aChild,
2513                                               mozilla::dom::nsIContentParent* aParent);
2514 
2515   static void TransferableToIPCTransferable(nsITransferable* aTransferable,
2516                                             mozilla::dom::IPCDataTransfer* aIPCDataTransfer,
2517                                             bool aInSyncMessage,
2518                                             mozilla::dom::nsIContentChild* aChild,
2519                                             mozilla::dom::nsIContentParent* aParent);
2520 
2521   /*
2522    * Get the pixel data from the given source surface and return it as a buffer.
2523    * The length and stride will be assigned from the surface.
2524    */
2525   static mozilla::UniquePtr<char[]> GetSurfaceData(
2526     mozilla::NotNull<mozilla::gfx::DataSourceSurface*> aSurface,
2527     size_t* aLength, int32_t* aStride);
2528 
2529   /*
2530    * Get the pixel data from the given source surface and fill it in Shmem.
2531    * The length and stride will be assigned from the surface.
2532    */
2533   static void GetSurfaceData(mozilla::gfx::DataSourceSurface* aSurface,
2534                              size_t* aLength, int32_t* aStride,
2535                              mozilla::ipc::IShmemAllocator* aAlloc,
2536                              mozilla::ipc::Shmem *aOutShmem);
2537 
2538   // Helpers shared by the implementations of nsContentUtils methods and
2539   // nsIDOMWindowUtils methods.
2540   static mozilla::Modifiers GetWidgetModifiers(int32_t aModifiers);
2541   static nsIWidget* GetWidget(nsIPresShell* aPresShell, nsPoint* aOffset);
2542   static int16_t GetButtonsFlagForButton(int32_t aButton);
2543   static mozilla::LayoutDeviceIntPoint ToWidgetPoint(const mozilla::CSSPoint& aPoint,
2544                                                      const nsPoint& aOffset,
2545                                                      nsPresContext* aPresContext);
2546   static nsView* GetViewToDispatchEvent(nsPresContext* aPresContext,
2547                                         nsIPresShell** aPresShell);
2548 
2549   /**
2550    * Synthesize a key event to the given widget
2551    * (see nsIDOMWindowUtils.sendKeyEvent).
2552    */
2553   static nsresult SendKeyEvent(nsIWidget* aWidget,
2554                                const nsAString& aType,
2555                                int32_t aKeyCode,
2556                                int32_t aCharCode,
2557                                int32_t aModifiers,
2558                                uint32_t aAdditionalFlags,
2559                                bool* aDefaultActionTaken);
2560 
2561   /**
2562    * Synthesize a mouse event to the given widget
2563    * (see nsIDOMWindowUtils.sendMouseEvent).
2564    */
2565   static nsresult SendMouseEvent(nsCOMPtr<nsIPresShell> aPresShell,
2566                                  const nsAString& aType,
2567                                  float aX,
2568                                  float aY,
2569                                  int32_t aButton,
2570                                  int32_t aButtons,
2571                                  int32_t aClickCount,
2572                                  int32_t aModifiers,
2573                                  bool aIgnoreRootScrollFrame,
2574                                  float aPressure,
2575                                  unsigned short aInputSourceArg,
2576                                  bool aToWindow,
2577                                  bool *aPreventDefault,
2578                                  bool aIsDOMEventSynthesized,
2579                                  bool aIsWidgetEventSynthesized);
2580 
2581   static void FirePageShowEvent(nsIDocShellTreeItem* aItem,
2582                                 mozilla::dom::EventTarget* aChromeEventHandler,
2583                                 bool aFireIfShowing);
2584 
2585   static void FirePageHideEvent(nsIDocShellTreeItem* aItem,
2586                                 mozilla::dom::EventTarget* aChromeEventHandler);
2587 
2588   static already_AddRefed<nsPIWindowRoot> GetWindowRoot(nsIDocument* aDoc);
2589 
2590   /*
2591    * Implements step 3.1 and 3.3 of the Determine request's Referrer algorithm
2592    * from the Referrer Policy specification.
2593    *
2594    * The referrer policy of the document is applied by Necko when using
2595    * channels.
2596    *
2597    * For documents representing an iframe srcdoc attribute, the document sets
2598    * its own URI correctly, so this method simply uses the document's original
2599    * or current URI as appropriate.
2600    *
2601    * aDoc may be null.
2602    *
2603    * https://w3c.github.io/webappsec/specs/referrer-policy/#determine-requests-referrer
2604    */
2605   static nsresult SetFetchReferrerURIWithPolicy(nsIPrincipal* aPrincipal,
2606                                                 nsIDocument* aDoc,
2607                                                 nsIHttpChannel* aChannel,
2608                                                 mozilla::net::ReferrerPolicy aReferrerPolicy);
2609 
2610     /*
2611    * Parse a referrer policy from a Referrer-Policy header
2612    * https://www.w3.org/TR/referrer-policy/#parse-referrer-policy-from-header
2613    *
2614    * @param aHeader the response's Referrer-Policy header to parse
2615    * @return referrer policy from the response header.
2616    */
2617   static mozilla::net::ReferrerPolicy GetReferrerPolicyFromHeader(const nsAString& aHeader);
2618 
2619   static bool PushEnabled(JSContext* aCx, JSObject* aObj);
2620 
2621   static bool IsNonSubresourceRequest(nsIChannel* aChannel);
2622 
CookiesBehavior()2623   static uint32_t CookiesBehavior()
2624   {
2625     return sCookiesBehavior;
2626   }
2627 
2628   // The order of these entries matters, as we use std::min for total ordering
2629   // of permissions. Private Browsing is considered to be more limiting
2630   // then session scoping
2631   enum class StorageAccess {
2632     // Don't allow access to the storage
2633     eDeny = 0,
2634     // Allow access to the storage, but only if it is secure to do so in a
2635     // private browsing context.
2636     ePrivateBrowsing = 1,
2637     // Allow access to the storage, but only persist it for the current session
2638     eSessionScoped = 2,
2639     // Allow access to the storage
2640     eAllow = 3,
2641   };
2642 
2643   /*
2644    * Checks if storage for the given window is permitted by a combination of
2645    * the user's preferences, and whether the window is a third-party iframe.
2646    *
2647    * This logic is intended to be shared between the different forms of
2648    * persistent storage which are available to web pages. Cookies don't use
2649    * this logic, and security logic related to them must be updated separately.
2650    */
2651   static StorageAccess StorageAllowedForWindow(nsPIDOMWindowInner* aWindow);
2652 
2653   /*
2654    * Checks if storage for the given principal is permitted by the user's
2655    * preferences. The caller is assumed to not be a third-party iframe.
2656    * (if that is possible, the caller should use StorageAllowedForWindow)
2657    */
2658   static StorageAccess StorageAllowedForPrincipal(nsIPrincipal* aPrincipal);
2659 
2660   /*
2661    * Serializes a HTML nsINode into its markup representation.
2662    */
2663   static bool SerializeNodeToMarkup(nsINode* aRoot,
2664                                     bool aDescendentsOnly,
2665                                     nsAString& aOut);
2666 
2667   /*
2668    * Returns true iff the provided JSObject is a global, and its URI matches
2669    * the provided about: URI.
2670    * @param aGlobal the JSObject whose URI to check, if it is a global.
2671    * @param aUri the URI to match, e.g. "about:feeds"
2672    */
2673   static bool IsSpecificAboutPage(JSObject* aGlobal, const char* aUri);
2674 
2675   static void SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible);
2676 
2677   /*
2678    * Return the associated presentation URL of the presented content.
2679    * Will return empty string if the docshell is not in a presented content.
2680    */
2681   static void GetPresentationURL(nsIDocShell* aDocShell, nsAString& aPresentationUrl);
2682 
2683   /*
2684    * Try to find the docshell corresponding to the given event target.
2685    */
2686   static nsIDocShell* GetDocShellForEventTarget(mozilla::dom::EventTarget* aTarget);
2687 
2688   /**
2689    * Returns true if the "HTTPS state" of the document should be "modern". See:
2690    *
2691    * https://html.spec.whatwg.org/#concept-document-https-state
2692    * https://fetch.spec.whatwg.org/#concept-response-https-state
2693    */
2694   static bool HttpsStateIsModern(nsIDocument* aDocument);
2695 
2696   /**
2697    * Looking up a custom element definition.
2698    * https://html.spec.whatwg.org/#look-up-a-custom-element-definition
2699    */
2700   static mozilla::dom::CustomElementDefinition*
2701     LookupCustomElementDefinition(nsIDocument* aDoc,
2702                                   const nsAString& aLocalName,
2703                                   uint32_t aNameSpaceID,
2704                                   const nsAString* aIs = nullptr);
2705 
2706   static void SetupCustomElement(Element* aElement,
2707                                  const nsAString* aTypeExtension = nullptr);
2708 
2709   static void EnqueueLifecycleCallback(nsIDocument* aDoc,
2710                                        nsIDocument::ElementCallbackType aType,
2711                                        Element* aCustomElement,
2712                                        mozilla::dom::LifecycleCallbackArgs* aArgs = nullptr,
2713                                        mozilla::dom::CustomElementDefinition* aDefinition = nullptr);
2714 
2715   static void GetCustomPrototype(nsIDocument* aDoc,
2716                                  int32_t aNamespaceID,
2717                                  nsIAtom* aAtom,
2718                                  JS::MutableHandle<JSObject*> prototype);
2719 
2720   static bool AttemptLargeAllocationLoad(nsIHttpChannel* aChannel);
2721 
2722 private:
2723   static bool InitializeEventTable();
2724 
2725   static nsresult EnsureStringBundle(PropertiesFile aFile);
2726 
2727   static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
2728                                 nsIPrincipal* aPrincipal);
2729 
2730   static nsresult WrapNative(JSContext *cx, nsISupports *native,
2731                              nsWrapperCache *cache, const nsIID* aIID,
2732                              JS::MutableHandle<JS::Value> vp,
2733                              bool aAllowWrapping);
2734 
2735   static nsresult DispatchEvent(nsIDocument* aDoc,
2736                                 nsISupports* aTarget,
2737                                 const nsAString& aEventName,
2738                                 bool aCanBubble,
2739                                 bool aCancelable,
2740                                 bool aTrusted,
2741                                 bool *aDefaultAction = nullptr,
2742                                 bool aOnlyChromeDispatch = false);
2743 
2744   static void InitializeModifierStrings();
2745 
2746   static void DropFragmentParsers();
2747 
2748   static bool MatchClassNames(nsIContent* aContent, int32_t aNamespaceID,
2749                               nsIAtom* aAtom, void* aData);
2750   static void DestroyClassNameArray(void* aData);
2751   static void* AllocClassMatchingInfo(nsINode* aRootNode,
2752                                       const nsString* aClasses);
2753 
2754   // Fills in aInfo with the tokens from the supplied autocomplete attribute.
2755   static AutocompleteAttrState InternalSerializeAutocompleteAttribute(const nsAttrValue* aAttrVal,
2756                                                                       mozilla::dom::AutocompleteInfo& aInfo);
2757 
2758   static bool CallOnAllRemoteChildren(nsIMessageBroadcaster* aManager,
2759                                       CallOnRemoteChildFunction aCallback,
2760                                       void* aArg);
2761 
2762   /*
2763    * Checks if storage for a given principal is permitted by the user's
2764    * preferences. If aWindow is non-null, its principal must be passed as
2765    * aPrincipal, and the third-party iframe and sandboxing status of the window
2766    * are also checked.
2767    *
2768    * Used in the implementation of StorageAllowedForWindow and
2769    * StorageAllowedForPrincipal.
2770    */
2771   static StorageAccess InternalStorageAllowedForPrincipal(nsIPrincipal* aPrincipal,
2772                                                           nsPIDOMWindowInner* aWindow);
2773 
2774   static nsIXPConnect *sXPConnect;
2775 
2776   static nsIScriptSecurityManager *sSecurityManager;
2777   static nsIPrincipal *sSystemPrincipal;
2778   static nsIPrincipal *sNullSubjectPrincipal;
2779 
2780   static nsIParserService *sParserService;
2781 
2782   static nsNameSpaceManager *sNameSpaceManager;
2783 
2784   static nsIIOService *sIOService;
2785   static nsIUUIDGenerator *sUUIDGenerator;
2786 
2787   static nsIConsoleService* sConsoleService;
2788 
2789   static nsDataHashtable<nsISupportsHashKey, EventNameMapping>* sAtomEventTable;
2790   static nsDataHashtable<nsStringHashKey, EventNameMapping>* sStringEventTable;
2791   static nsCOMArray<nsIAtom>* sUserDefinedEvents;
2792 
2793   static nsIStringBundleService* sStringBundleService;
2794   static nsIStringBundle* sStringBundles[PropertiesFile_COUNT];
2795 
2796   static nsIContentPolicy* sContentPolicyService;
2797   static bool sTriedToGetContentPolicy;
2798 
2799   static nsILineBreaker* sLineBreaker;
2800   static nsIWordBreaker* sWordBreaker;
2801 
2802   static nsIBidiKeyboard* sBidiKeyboard;
2803 
2804   static bool sInitialized;
2805   static uint32_t sScriptBlockerCount;
2806   static uint32_t sDOMNodeRemovedSuppressCount;
2807   static uint32_t sMicroTaskLevel;
2808   // Not an nsCOMArray because removing elements from those is slower
2809   static AutoTArray<nsCOMPtr<nsIRunnable>, 8>* sBlockedScriptRunners;
2810   static uint32_t sRunnersCountAtFirstBlocker;
2811   static uint32_t sScriptBlockerCountWhereRunnersPrevented;
2812 
2813   static nsIInterfaceRequestor* sSameOriginChecker;
2814 
2815   static bool sIsHandlingKeyBoardEvent;
2816   static bool sAllowXULXBL_for_file;
2817   static bool sIsFullScreenApiEnabled;
2818   static bool sIsUnprefixedFullscreenApiEnabled;
2819   static bool sTrustedFullScreenOnly;
2820   static bool sIsCutCopyAllowed;
2821   static uint32_t sHandlingInputTimeout;
2822   static bool sIsPerformanceTimingEnabled;
2823   static bool sIsResourceTimingEnabled;
2824   static bool sIsUserTimingLoggingEnabled;
2825   static bool sIsFrameTimingPrefEnabled;
2826   static bool sIsExperimentalAutocompleteEnabled;
2827   static bool sEncodeDecodeURLHash;
2828   static bool sGettersDecodeURLHash;
2829   static bool sPrivacyResistFingerprinting;
2830   static bool sSendPerformanceTimingNotifications;
2831   static bool sUseActivityCursor;
2832   static uint32_t sCookiesLifetimePolicy;
2833   static uint32_t sCookiesBehavior;
2834 
2835   static nsHtml5StringParser* sHTMLFragmentParser;
2836   static nsIParser* sXMLFragmentParser;
2837   static nsIFragmentContentSink* sXMLFragmentSink;
2838 
2839   /**
2840    * True if there's a fragment parser activation on the stack.
2841    */
2842   static bool sFragmentParsingActive;
2843 
2844   static nsString* sShiftText;
2845   static nsString* sControlText;
2846   static nsString* sMetaText;
2847   static nsString* sOSText;
2848   static nsString* sAltText;
2849   static nsString* sModifierSeparator;
2850 
2851 #if !(defined(DEBUG) || defined(MOZ_ENABLE_JS_DUMP))
2852   static bool sDOMWindowDumpEnabled;
2853 #endif
2854   static bool sDoNotTrackEnabled;
2855   static mozilla::LazyLogModule sDOMDumpLog;
2856 };
2857 
2858 class MOZ_RAII nsAutoScriptBlocker {
2859 public:
nsAutoScriptBlocker(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM)2860   explicit nsAutoScriptBlocker(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) {
2861     MOZ_GUARD_OBJECT_NOTIFIER_INIT;
2862     nsContentUtils::AddScriptBlocker();
2863   }
~nsAutoScriptBlocker()2864   ~nsAutoScriptBlocker() {
2865     nsContentUtils::RemoveScriptBlocker();
2866   }
2867 private:
2868   MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
2869 };
2870 
2871 class MOZ_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved :
2872                           public nsAutoScriptBlocker {
2873 public:
nsAutoScriptBlockerSuppressNodeRemoved()2874   nsAutoScriptBlockerSuppressNodeRemoved() {
2875     ++nsContentUtils::sDOMNodeRemovedSuppressCount;
2876   }
~nsAutoScriptBlockerSuppressNodeRemoved()2877   ~nsAutoScriptBlockerSuppressNodeRemoved() {
2878     --nsContentUtils::sDOMNodeRemovedSuppressCount;
2879   }
2880 };
2881 
2882 class MOZ_STACK_CLASS nsAutoMicroTask
2883 {
2884 public:
nsAutoMicroTask()2885   nsAutoMicroTask()
2886   {
2887     nsContentUtils::EnterMicroTask();
2888   }
~nsAutoMicroTask()2889   ~nsAutoMicroTask()
2890   {
2891     nsContentUtils::LeaveMicroTask();
2892   }
2893 };
2894 
2895 namespace mozilla {
2896 namespace dom {
2897 
2898 class TreeOrderComparator {
2899 public:
Equals(nsINode * aElem1,nsINode * aElem2)2900   bool Equals(nsINode* aElem1, nsINode* aElem2) const {
2901     return aElem1 == aElem2;
2902   }
LessThan(nsINode * aElem1,nsINode * aElem2)2903   bool LessThan(nsINode* aElem1, nsINode* aElem2) const {
2904     return nsContentUtils::PositionIsBefore(aElem1, aElem2);
2905   }
2906 };
2907 
2908 } // namespace dom
2909 } // namespace mozilla
2910 
2911 #define NS_INTERFACE_MAP_ENTRY_TEAROFF(_interface, _allocator)                \
2912   if (aIID.Equals(NS_GET_IID(_interface))) {                                  \
2913     foundInterface = static_cast<_interface *>(_allocator);                   \
2914     if (!foundInterface) {                                                    \
2915       *aInstancePtr = nullptr;                                                \
2916       return NS_ERROR_OUT_OF_MEMORY;                                          \
2917     }                                                                         \
2918   } else
2919 
2920 /*
2921  * In the following helper macros we exploit the fact that the result of a
2922  * series of additions will not be finite if any one of the operands in the
2923  * series is not finite.
2924  */
2925 #define NS_ENSURE_FINITE(f, rv)                                               \
2926   if (!mozilla::IsFinite(f)) {                                                \
2927     return (rv);                                                              \
2928   }
2929 
2930 #define NS_ENSURE_FINITE2(f1, f2, rv)                                         \
2931   if (!mozilla::IsFinite((f1)+(f2))) {                                        \
2932     return (rv);                                                              \
2933   }
2934 
2935 #define NS_ENSURE_FINITE4(f1, f2, f3, f4, rv)                                 \
2936   if (!mozilla::IsFinite((f1)+(f2)+(f3)+(f4))) {                              \
2937     return (rv);                                                              \
2938   }
2939 
2940 #define NS_ENSURE_FINITE5(f1, f2, f3, f4, f5, rv)                             \
2941   if (!mozilla::IsFinite((f1)+(f2)+(f3)+(f4)+(f5))) {                         \
2942     return (rv);                                                              \
2943   }
2944 
2945 #define NS_ENSURE_FINITE6(f1, f2, f3, f4, f5, f6, rv)                         \
2946   if (!mozilla::IsFinite((f1)+(f2)+(f3)+(f4)+(f5)+(f6))) {                    \
2947     return (rv);                                                              \
2948   }
2949 
2950 // Deletes a linked list iteratively to avoid blowing up the stack (bug 460444).
2951 #define NS_CONTENT_DELETE_LIST_MEMBER(type_, ptr_, member_)                   \
2952   {                                                                           \
2953     type_ *cur = (ptr_)->member_;                                             \
2954     (ptr_)->member_ = nullptr;                                                 \
2955     while (cur) {                                                             \
2956       type_ *next = cur->member_;                                             \
2957       cur->member_ = nullptr;                                                  \
2958       delete cur;                                                             \
2959       cur = next;                                                             \
2960     }                                                                         \
2961   }
2962 
2963 #endif /* nsContentUtils_h___ */
2964