File: nsIGlobalObject.h

package info (click to toggle)
firefox 149.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,767,760 kB
  • sloc: cpp: 7,416,064; javascript: 6,752,859; ansic: 3,774,850; python: 1,250,473; xml: 641,578; asm: 439,191; java: 186,617; sh: 56,634; makefile: 18,856; objc: 13,092; perl: 12,763; pascal: 5,960; yacc: 4,583; cs: 3,846; lex: 1,720; ruby: 1,002; php: 436; lisp: 258; awk: 105; sql: 66; sed: 53; csh: 10; exp: 6
file content (425 lines) | stat: -rw-r--r-- 16,193 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsIGlobalObject_h_
#define nsIGlobalObject_h_

#include "js/TypeDecls.h"
#include "mozilla/LinkedList.h"
#include "mozilla/Maybe.h"
#include "mozilla/OriginTrials.h"
#include "mozilla/dom/ClientInfo.h"
#include "mozilla/dom/ClientState.h"
#include "mozilla/dom/ServiceWorkerDescriptor.h"
#include "nsContentUtils.h"
#include "nsHashKeys.h"
#include "nsISupports.h"
#include "nsRFPService.h"
#include "nsStringFwd.h"
#include "nsTArray.h"
#include "nsTHashtable.h"

// Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
#define NS_IGLOBALOBJECT_IID \
  {0x11afa8be, 0xd997, 0x4e07, {0xa6, 0xa3, 0x6f, 0x87, 0x2e, 0xc3, 0xee, 0x7f}}

class nsCycleCollectionTraversalCallback;
class nsICookieJarSettings;
class nsIPrincipal;
class nsIURI;
class nsPIDOMWindowInner;

namespace mozilla {
class DOMEventTargetHelper;
class GlobalFreezeObserver;
class GlobalTeardownObserver;
template <typename V, typename E>
class Result;
enum class StorageAccess;
namespace dom {
class WorkerGlobalScopeBase;
class VoidFunction;
class DebuggerNotificationManager;
class FontFaceSet;
class Function;
class Report;
class ReportBody;
class ReportingObserver;
class ServiceWorker;
class ServiceWorkerContainer;
class ServiceWorkerRegistration;
class ServiceWorkerRegistrationDescriptor;
class StorageManager;
class WebTaskSchedulingState;
enum class CallerType : uint32_t;
}  // namespace dom
namespace ipc {
class PrincipalInfo;
}  // namespace ipc
}  // namespace mozilla

namespace JS::loader {
class ModuleLoaderBase;
}  // namespace JS::loader

/**
 * See <https://developer.mozilla.org/en-US/docs/Glossary/Global_object>.
 */
class nsIGlobalObject : public nsISupports {
 private:
  nsTArray<nsCString> mHostObjectURIs;

  // Raw pointers to bound DETH objects.  These are added by
  // AddGlobalTeardownObserver().
  mozilla::LinkedList<mozilla::GlobalTeardownObserver> mGlobalTeardownObservers;
  // And by AddGlobalFreezeObserver()
  mozilla::LinkedList<mozilla::GlobalFreezeObserver> mGlobalFreezeObservers;

  bool mIsDying;

 protected:
  bool mIsInnerWindow;

  nsIGlobalObject();

 public:
  using RTPCallerType = mozilla::RTPCallerType;
  using RFPTarget = mozilla::RFPTarget;
  NS_INLINE_DECL_STATIC_IID(NS_IGLOBALOBJECT_IID)

  /**
   * This check is added to deal with Promise microtask queues. On the main
   * thread, we do not impose restrictions about when script stops running or
   * when runnables can no longer be dispatched to the main thread. This means
   * it is possible for a Promise chain to keep resolving an infinite chain of
   * promises, preventing the browser from shutting down. See Bug 1058695. To
   * prevent this, the nsGlobalWindow subclass sets this flag when it is
   * closed. The Promise implementation checks this and prohibits new runnables
   * from being dispatched.
   *
   * We pair this with checks during processing the promise microtask queue
   * that pops up the slow script dialog when the Promise queue is preventing
   * a window from going away.
   */
  bool IsDying() const { return mIsDying; }

  /**
   * Is it currently forbidden to call into script?  JS-implemented WebIDL is
   * a special case that's always allowed because it has the system principal,
   * and callers should indicate this.
   */
  bool IsScriptForbidden(JSObject* aCallback,
                         bool aIsJSImplementedWebIDL = false) const;

  /**
   * Return the JSObject for this global, if it still has one.  Otherwise return
   * null.
   *
   * If non-null is returned, then the returned object will have been already
   * exposed to active JS, so callers do not need to do it.
   */
  virtual JSObject* GetGlobalJSObject() = 0;

  /**
   * Return the JSObject for this global _without_ exposing it to active JS.
   * This may return a gray object.
   *
   * This method is appropriate to use in assertions (so there is less of a
   * difference in GC/CC marking between debug and optimized builds) and in
   * situations where we are sure no CC activity can happen while the return
   * value is used and the return value does not end up escaping to the heap in
   * any way.  In all other cases, and in particular in cases where the return
   * value is held in a JS::Rooted or passed to the JSAutoRealm constructor, use
   * GetGlobalJSObject.
   */
  virtual JSObject* GetGlobalJSObjectPreserveColor() const = 0;

  /**
   * Check whether this nsIGlobalObject still has a JSObject associated with it,
   * or whether it's torn-down enough that the JSObject is gone.
   */
  bool HasJSGlobal() const { return GetGlobalJSObjectPreserveColor(); }

  virtual nsISerialEventTarget* SerialEventTarget() const = 0;
  virtual nsresult Dispatch(already_AddRefed<nsIRunnable>&&) const = 0;

  // This method is not meant to be overridden.
  nsIPrincipal* PrincipalOrNull() const;

  void RegisterHostObjectURI(const nsACString& aURI);

  void UnregisterHostObjectURI(const nsACString& aURI);

  // Any CC class inheriting nsIGlobalObject should call these 2 methods to
  // cleanup objects stored in nsIGlobalObject such as blobURLs and Reports.
  void UnlinkObjectsInGlobal();
  void TraverseObjectsInGlobal(nsCycleCollectionTraversalCallback& aCb);

  // GlobalTeardownObservers must register themselves on the global when they
  // bind to it in order to get the DisconnectFromOwner() method
  // called correctly.  RemoveGlobalTeardownObserver() must be called
  // before the GlobalTeardownObserver is destroyed.
  void AddGlobalTeardownObserver(mozilla::GlobalTeardownObserver* aObject);
  void RemoveGlobalTeardownObserver(mozilla::GlobalTeardownObserver* aObject);

  // Iterate the registered GlobalTeardownObservers and call the given function
  // for each one.
  void ForEachGlobalTeardownObserver(
      const std::function<void(mozilla::GlobalTeardownObserver*,
                               bool* aDoneOut)>& aFunc) const;

  // GlobalFreezeObservers must register themselves on the global too for
  // FreezeCallback and optionally ThawCallback.
  void AddGlobalFreezeObserver(mozilla::GlobalFreezeObserver* aObserver);
  void RemoveGlobalFreezeObserver(mozilla::GlobalFreezeObserver* aObserver);

  // Iterate the registered GlobalFreezeObservers and call the given function
  // for each one.
  void ForEachGlobalFreezeObserver(
      const std::function<void(mozilla::GlobalFreezeObserver*, bool* aDoneOut)>&
          aFunc) const;

  virtual bool IsInSyncOperation() { return false; }

  virtual mozilla::dom::DebuggerNotificationManager*
  GetOrCreateDebuggerNotificationManager() {
    return nullptr;
  }

  virtual mozilla::dom::DebuggerNotificationManager*
  GetExistingDebuggerNotificationManager() {
    return nullptr;
  }

  virtual void SetWebTaskSchedulingState(
      mozilla::dom::WebTaskSchedulingState* aState) {}
  virtual mozilla::dom::WebTaskSchedulingState* GetWebTaskSchedulingState()
      const {
    return nullptr;
  }

  // For globals with a concept of a Base URI (windows, workers), the base URI,
  // nullptr otherwise.
  virtual nsIURI* GetBaseURI() const;

  virtual mozilla::Maybe<mozilla::dom::ClientInfo> GetClientInfo() const;
  virtual mozilla::Maybe<mozilla::dom::ClientState> GetClientState() const;

  virtual mozilla::Maybe<nsID> GetAgentClusterId() const;

  virtual bool CrossOriginIsolated() const { return false; }

  virtual bool IsSharedMemoryAllowed() const { return false; }

  virtual mozilla::Maybe<mozilla::dom::ServiceWorkerDescriptor> GetController()
      const;

  virtual already_AddRefed<mozilla::dom::ServiceWorkerContainer>
  GetServiceWorkerContainer();

  // Get the DOM object for the given descriptor or attempt to create one.
  // Creation can still fail and return nullptr during shutdown, etc.
  virtual RefPtr<mozilla::dom::ServiceWorker> GetOrCreateServiceWorker(
      const mozilla::dom::ServiceWorkerDescriptor& aDescriptor);

  // Get the DOM object for the given descriptor or return nullptr if it does
  // not exist.
  virtual RefPtr<mozilla::dom::ServiceWorkerRegistration>
  GetServiceWorkerRegistration(
      const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
      const;

  // Get the DOM object for the given descriptor or attempt to create one.
  // Creation can still fail and return nullptr during shutdown, etc.
  virtual RefPtr<mozilla::dom::ServiceWorkerRegistration>
  GetOrCreateServiceWorkerRegistration(
      const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor);

  /**
   * Returns the storage access of this global.
   *
   * If you have a global that needs storage access, you should be overriding
   * this method in your subclass of this class!
   */
  virtual mozilla::StorageAccess GetStorageAccess();

  // For globals with cookie jars (windows, workers), the cookie jar settings;
  // will likely be null on other global types.
  virtual nsICookieJarSettings* GetCookieJarSettings();

  // Returns the set of active origin trials for this global.
  virtual mozilla::OriginTrials Trials() const = 0;

  // Returns a pointer to this object as an inner window if this is one or
  // nullptr otherwise.
  nsPIDOMWindowInner* GetAsInnerWindow();

  virtual void TriggerUpdateCCFlag() {}

  void QueueMicrotask(mozilla::dom::VoidFunction& aCallback);

  void RegisterReportingObserver(mozilla::dom::ReportingObserver* aObserver,
                                 bool aBuffered);

  void UnregisterReportingObserver(mozilla::dom::ReportingObserver* aObserver);

  void BroadcastReport(mozilla::dom::Report* aReport);

  MOZ_CAN_RUN_SCRIPT void NotifyReportingObservers();

  void RemoveReportRecords();

  // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
  // This function is set once by CountQueuingStrategy::GetSize.
  already_AddRefed<mozilla::dom::Function>
  GetCountQueuingStrategySizeFunction();
  void SetCountQueuingStrategySizeFunction(mozilla::dom::Function* aFunction);

  already_AddRefed<mozilla::dom::Function>
  GetByteLengthQueuingStrategySizeFunction();
  void SetByteLengthQueuingStrategySizeFunction(
      mozilla::dom::Function* aFunction);

  /**
   * Check whether we should avoid leaking distinguishing information to JS/CSS.
   * https://w3c.github.io/fingerprinting-guidance/
   */
  virtual bool ShouldResistFingerprinting(RFPTarget aTarget) const = 0;

  // CallerType::System callers never have to resist fingerprinting.
  bool ShouldResistFingerprinting(mozilla::dom::CallerType aCallerType,
                                  RFPTarget aTarget) const;

  RTPCallerType GetRTPCallerType() const;

  bool IsRFPTargetActive(const nsAString& aTargetName,
                         mozilla::ErrorResult& aRv);

  /**
   * Get the module loader to use for this global, if any. By default this
   * returns null.
   */
  virtual JS::loader::ModuleLoaderBase* GetModuleLoader(JSContext* aCx) {
    return nullptr;
  }

  virtual mozilla::dom::FontFaceSet* GetFonts() { return nullptr; }

  virtual mozilla::Result<mozilla::ipc::PrincipalInfo, nsresult>
  GetStorageKey();
  mozilla::Result<bool, nsresult> HasEqualStorageKey(
      const mozilla::ipc::PrincipalInfo& aStorageKey);

  virtual mozilla::dom::StorageManager* GetStorageManager() { return nullptr; }

  /**
   * https://html.spec.whatwg.org/multipage/web-messaging.html#eligible-for-messaging
   * * a Window object whose associated Document is fully active, or
   * * a WorkerGlobalScope object whose closing flag is false and whose worker
   *   is not a suspendable worker.
   */
  virtual bool IsEligibleForMessaging() { return false; };
  virtual bool IsBackgroundInternal() const { return false; }
  virtual mozilla::dom::TimeoutManager* GetTimeoutManager() { return nullptr; }
  virtual bool IsRunningTimeout() { return false; }
  virtual bool IsPlayingAudio() { return false; }
  // Determine if the window is suspended or frozen.  Outer windows
  // will forward this call to the inner window for convenience.  If
  // there is no inner window then the outer window is considered
  // suspended and frozen by default.
  virtual bool IsSuspended() const { return false; }
  virtual bool IsFrozen() const { return false; }
  MOZ_CAN_RUN_SCRIPT
  virtual bool RunTimeoutHandler(mozilla::dom::Timeout* aTimeout) {
    return false;
  }
  // Return true if there is any active IndexedDB databases which could block
  // timeout-throttling.
  virtual bool HasActiveIndexedDBDatabases() const { return false; }
  /**
   * Check whether the active peer connection count is non-zero.
   */
  virtual bool HasActivePeerConnections() { return false; }
  // Return true if there are any open WebSockets that could block
  // timeout-throttling.
  virtual bool HasOpenWebSockets() const { return false; }

  virtual bool IsXPCSandbox() { return false; }

  virtual bool HasScheduledNormalOrHighPriorityWebTasks() const {
    return false;
  }

  virtual void UpdateWebSocketCount(int32_t aDelta) {};
  // Increase/Decrease the number of active IndexedDB databases for the
  // decision making of timeout-throttling.
  virtual void UpdateActiveIndexedDBDatabaseCount(int32_t aDelta) {}

  /**
   * Report a localized error message to the error console.  Currently this
   * amounts to a wrapper around nsContentUtils::ReportToConsole for window
   * globals and a runnable bounced to the main thread to call
   * nsContentUtils::ReportToConsole for workers but the intent is to migrate
   * towards logging the messages to the `dom::Console` for the global.  See
   * bug 1900706 for more context.
   *
   * This method returns void because there is no reasonable action for a caller
   * for dynamic failure and we can assert on things like erroneous message
   * names.
   *
   *   @param aErrorFlags See nsIScriptError.
   *   @param aCategory Name of module reporting error.
   *   @param aFile Properties file containing localized message.
   *   @param aMessageName Name of localized message.
   *   @param [aParams=empty-array] (Optional) Parameters to be substituted into
   *          localized message.
   *   @param [aURI=nullptr] (Optional) URI of resource containing error; if
   *          omitted, an attempt will be made to use the URI associated with
   *          the global (ex: the document URI).
   *   @param [aSourceLine=u""_ns] (Optional) The text of the line that
   *          contains the error (may be empty).
   *   @param [aLineNumber=0] (Optional) Line number within resource
   *          containing error.
   *   @param [aColumnNumber=0] (Optional) Column number within resource
   *          containing error.
   */
  virtual void ReportToConsole(
      uint32_t aErrorFlags, const nsCString& aCategory,
      nsContentUtils::PropertiesFile aFile, const nsCString& aMessageName,
      const nsTArray<nsString>& aParams = nsTArray<nsString>(),
      const mozilla::SourceLocation& aLocation =
          mozilla::JSCallingLocation::Get());

 protected:
  virtual ~nsIGlobalObject();

  void StartDying() { mIsDying = true; }

  void DisconnectGlobalTeardownObservers();
  void DisconnectGlobalFreezeObservers();
  void NotifyGlobalFrozen();
  void NotifyGlobalThawed();

  size_t ShallowSizeOfExcludingThis(mozilla::MallocSizeOf aSizeOf) const;

 private:
  void ClearReports();

 private:
  // List of Report objects for ReportingObservers.
  nsTArray<RefPtr<mozilla::dom::ReportingObserver>> mReportingObservers;
  // https://w3c.github.io/reporting/#windoworworkerglobalscope-report-buffer
  nsTArray<RefPtr<mozilla::dom::Report>> mReportBuffer;
  nsTHashMap<nsString, uint32_t> mReportPerTypeCount;

  // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
  RefPtr<mozilla::dom::Function> mCountQueuingStrategySizeFunction;

  // https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
  RefPtr<mozilla::dom::Function> mByteLengthQueuingStrategySizeFunction;
};

#endif  // nsIGlobalObject_h_