LCOV - code coverage report
Current view: top level - dom/base - nsContentUtils.h (source / functions) Hit Total Coverage
Test: output.info Lines: 84 123 68.3 %
Date: 2017-07-14 16:53:18 Functions: 38 59 64.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13