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 #ifndef nsIGlobalObject_h__
8 #define nsIGlobalObject_h__
9 
10 #include "mozilla/LinkedList.h"
11 #include "mozilla/Maybe.h"
12 #include "mozilla/dom/ClientInfo.h"
13 #include "mozilla/dom/DispatcherTrait.h"
14 #include "mozilla/dom/ServiceWorkerDescriptor.h"
15 #include "nsHashKeys.h"
16 #include "nsISupports.h"
17 #include "nsStringFwd.h"
18 #include "nsTArray.h"
19 #include "nsTHashtable.h"
20 #include "js/TypeDecls.h"
21 
22 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
23 #define NS_IGLOBALOBJECT_IID                         \
24   {                                                  \
25     0x11afa8be, 0xd997, 0x4e07, {                    \
26       0xa6, 0xa3, 0x6f, 0x87, 0x2e, 0xc3, 0xee, 0x7f \
27     }                                                \
28   }
29 
30 class nsCycleCollectionTraversalCallback;
31 class nsIPrincipal;
32 class nsPIDOMWindowInner;
33 
34 namespace mozilla {
35 class DOMEventTargetHelper;
36 enum class StorageAccess;
37 namespace dom {
38 class VoidFunction;
39 class DebuggerNotificationManager;
40 class Function;
41 class Report;
42 class ReportBody;
43 class ReportingObserver;
44 class ServiceWorker;
45 class ServiceWorkerRegistration;
46 class ServiceWorkerRegistrationDescriptor;
47 }  // namespace dom
48 }  // namespace mozilla
49 
50 /**
51  * See <https://developer.mozilla.org/en-US/docs/Glossary/Global_object>.
52  */
53 class nsIGlobalObject : public nsISupports,
54                         public mozilla::dom::DispatcherTrait {
55   nsTArray<nsCString> mHostObjectURIs;
56 
57   // Raw pointers to bound DETH objects.  These are added by
58   // AddEventTargetObject().
59   mozilla::LinkedList<mozilla::DOMEventTargetHelper> mEventTargetObjects;
60 
61   bool mIsDying;
62   bool mIsScriptForbidden;
63 
64  protected:
65   bool mIsInnerWindow;
66 
67   nsIGlobalObject();
68 
69  public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IGLOBALOBJECT_IID)70   NS_DECLARE_STATIC_IID_ACCESSOR(NS_IGLOBALOBJECT_IID)
71 
72   /**
73    * This check is added to deal with Promise microtask queues. On the main
74    * thread, we do not impose restrictions about when script stops running or
75    * when runnables can no longer be dispatched to the main thread. This means
76    * it is possible for a Promise chain to keep resolving an infinite chain of
77    * promises, preventing the browser from shutting down. See Bug 1058695. To
78    * prevent this, the nsGlobalWindow subclass sets this flag when it is
79    * closed. The Promise implementation checks this and prohibits new runnables
80    * from being dispatched.
81    *
82    * We pair this with checks during processing the promise microtask queue
83    * that pops up the slow script dialog when the Promise queue is preventing
84    * a window from going away.
85    */
86   bool IsDying() const { return mIsDying; }
87 
88   /**
89    * Is it currently forbidden to call into script?  JS-implemented WebIDL is
90    * a special case that's always allowed because it has the system principal,
91    * and callers should indicate this.
92    */
93   bool IsScriptForbidden(JSObject* aCallback,
94                          bool aIsJSImplementedWebIDL = false) const;
95 
96   /**
97    * Return the JSObject for this global, if it still has one.  Otherwise return
98    * null.
99    *
100    * If non-null is returned, then the returned object will have been already
101    * exposed to active JS, so callers do not need to do it.
102    */
103   virtual JSObject* GetGlobalJSObject() = 0;
104 
105   /**
106    * Return the JSObject for this global _without_ exposing it to active JS.
107    * This may return a gray object.
108    *
109    * This method is appropriate to use in assertions (so there is less of a
110    * difference in GC/CC marking between debug and optimized builds) and in
111    * situations where we are sure no CC activity can happen while the return
112    * value is used and the return value does not end up escaping to the heap in
113    * any way.  In all other cases, and in particular in cases where the return
114    * value is held in a JS::Rooted or passed to the JSAutoRealm constructor, use
115    * GetGlobalJSObject.
116    */
117   virtual JSObject* GetGlobalJSObjectPreserveColor() const = 0;
118 
119   /**
120    * Check whether this nsIGlobalObject still has a JSObject associated with it,
121    * or whether it's torn-down enough that the JSObject is gone.
122    */
HasJSGlobal()123   bool HasJSGlobal() const { return GetGlobalJSObjectPreserveColor(); }
124 
125   // This method is not meant to be overridden.
126   nsIPrincipal* PrincipalOrNull();
127 
128   void RegisterHostObjectURI(const nsACString& aURI);
129 
130   void UnregisterHostObjectURI(const nsACString& aURI);
131 
132   // Any CC class inheriting nsIGlobalObject should call these 2 methods to
133   // cleanup objects stored in nsIGlobalObject such as blobURLs and Reports.
134   void UnlinkObjectsInGlobal();
135   void TraverseObjectsInGlobal(nsCycleCollectionTraversalCallback& aCb);
136 
137   // DETH objects must register themselves on the global when they
138   // bind to it in order to get the DisconnectFromOwner() method
139   // called correctly.  RemoveEventTargetObject() must be called
140   // before the DETH object is destroyed.
141   void AddEventTargetObject(mozilla::DOMEventTargetHelper* aObject);
142   void RemoveEventTargetObject(mozilla::DOMEventTargetHelper* aObject);
143 
144   // Iterate the registered DETH objects and call the given function
145   // for each one.
146   void ForEachEventTargetObject(
147       const std::function<void(mozilla::DOMEventTargetHelper*, bool* aDoneOut)>&
148           aFunc) const;
149 
IsInSyncOperation()150   virtual bool IsInSyncOperation() { return false; }
151 
152   virtual mozilla::dom::DebuggerNotificationManager*
GetOrCreateDebuggerNotificationManager()153   GetOrCreateDebuggerNotificationManager() {
154     return nullptr;
155   }
156 
157   virtual mozilla::dom::DebuggerNotificationManager*
GetExistingDebuggerNotificationManager()158   GetExistingDebuggerNotificationManager() {
159     return nullptr;
160   }
161 
162   virtual mozilla::Maybe<mozilla::dom::ClientInfo> GetClientInfo() const;
163 
164   virtual mozilla::Maybe<nsID> GetAgentClusterId() const;
165 
CrossOriginIsolated()166   virtual bool CrossOriginIsolated() const { return false; }
167 
IsSharedMemoryAllowed()168   virtual bool IsSharedMemoryAllowed() const { return false; }
169 
170   virtual mozilla::Maybe<mozilla::dom::ServiceWorkerDescriptor> GetController()
171       const;
172 
173   // Get the DOM object for the given descriptor or attempt to create one.
174   // Creation can still fail and return nullptr during shutdown, etc.
175   virtual RefPtr<mozilla::dom::ServiceWorker> GetOrCreateServiceWorker(
176       const mozilla::dom::ServiceWorkerDescriptor& aDescriptor);
177 
178   // Get the DOM object for the given descriptor or return nullptr if it does
179   // not exist.
180   virtual RefPtr<mozilla::dom::ServiceWorkerRegistration>
181   GetServiceWorkerRegistration(
182       const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
183       const;
184 
185   // Get the DOM object for the given descriptor or attempt to create one.
186   // Creation can still fail and return nullptr during shutdown, etc.
187   virtual RefPtr<mozilla::dom::ServiceWorkerRegistration>
188   GetOrCreateServiceWorkerRegistration(
189       const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor);
190 
191   /**
192    * Returns the storage access of this global.
193    *
194    * If you have a global that needs storage access, you should be overriding
195    * this method in your subclass of this class!
196    */
197   virtual mozilla::StorageAccess GetStorageAccess();
198 
199   // Returns a pointer to this object as an inner window if this is one or
200   // nullptr otherwise.
201   nsPIDOMWindowInner* AsInnerWindow();
202 
203   void QueueMicrotask(mozilla::dom::VoidFunction& aCallback);
204 
205   void RegisterReportingObserver(mozilla::dom::ReportingObserver* aObserver,
206                                  bool aBuffered);
207 
208   void UnregisterReportingObserver(mozilla::dom::ReportingObserver* aObserver);
209 
210   void BroadcastReport(mozilla::dom::Report* aReport);
211 
212   MOZ_CAN_RUN_SCRIPT void NotifyReportingObservers();
213 
214   void RemoveReportRecords();
215 
216 #ifdef MOZ_DOM_STREAMS
217   // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
218   // This function is set once by CountQueuingStrategy::GetSize.
219   already_AddRefed<mozilla::dom::Function>
220   GetCountQueuingStrategySizeFunction();
221   void SetCountQueuingStrategySizeFunction(mozilla::dom::Function* aFunction);
222 
223   already_AddRefed<mozilla::dom::Function>
224   GetByteLengthQueuingStrategySizeFunction();
225   void SetByteLengthQueuingStrategySizeFunction(
226       mozilla::dom::Function* aFunction);
227 #endif
228 
229   /**
230    * Check whether we should avoid leaking distinguishing information to JS/CSS.
231    * https://w3c.github.io/fingerprinting-guidance/
232    */
233   virtual bool ShouldResistFingerprinting() const;
234 
235   /**
236    * Threadsafe way to get nsIPrincipal::GetHashValue for the associated
237    * principal.
238    */
GetPrincipalHashValue()239   virtual uint32_t GetPrincipalHashValue() const { return 0; }
240 
241  protected:
242   virtual ~nsIGlobalObject();
243 
StartDying()244   void StartDying() { mIsDying = true; }
245 
StartForbiddingScript()246   void StartForbiddingScript() { mIsScriptForbidden = true; }
StopForbiddingScript()247   void StopForbiddingScript() { mIsScriptForbidden = false; }
248 
249   void DisconnectEventTargetObjects();
250 
251   size_t ShallowSizeOfExcludingThis(mozilla::MallocSizeOf aSizeOf) const;
252 
253  private:
254   // List of Report objects for ReportingObservers.
255   nsTArray<RefPtr<mozilla::dom::ReportingObserver>> mReportingObservers;
256   nsTArray<RefPtr<mozilla::dom::Report>> mReportRecords;
257 
258 #ifdef MOZ_DOM_STREAMS
259   // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
260   RefPtr<mozilla::dom::Function> mCountQueuingStrategySizeFunction;
261 
262   // https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
263   RefPtr<mozilla::dom::Function> mByteLengthQueuingStrategySizeFunction;
264 #endif
265 };
266 
267 NS_DEFINE_STATIC_IID_ACCESSOR(nsIGlobalObject, NS_IGLOBALOBJECT_IID)
268 
269 #endif  // nsIGlobalObject_h__
270