Bug 1750871 - run mochitest-remote on fission everywhere. r=releng-reviewers,aki
[gecko.git] / dom / base / nsIGlobalObject.cpp
blobab3fc735d1ca0631a75168d290e5b3eb9f8ea996
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsIGlobalObject.h"
8 #include "mozilla/CycleCollectedJSContext.h"
9 #include "mozilla/StorageAccess.h"
10 #include "mozilla/dom/BlobURLProtocolHandler.h"
11 #include "mozilla/dom/FunctionBinding.h"
12 #include "mozilla/dom/Report.h"
13 #include "mozilla/dom/ReportingObserver.h"
14 #include "mozilla/dom/ServiceWorker.h"
15 #include "mozilla/dom/ServiceWorkerRegistration.h"
16 #include "nsContentUtils.h"
17 #include "nsThreadUtils.h"
18 #include "nsGlobalWindowInner.h"
20 // Max number of Report objects
21 constexpr auto MAX_REPORT_RECORDS = 100;
23 using mozilla::AutoSlowOperation;
24 using mozilla::CycleCollectedJSContext;
25 using mozilla::DOMEventTargetHelper;
26 using mozilla::ErrorResult;
27 using mozilla::IgnoredErrorResult;
28 using mozilla::MallocSizeOf;
29 using mozilla::Maybe;
30 using mozilla::MicroTaskRunnable;
31 using mozilla::dom::BlobURLProtocolHandler;
32 using mozilla::dom::ClientInfo;
33 using mozilla::dom::Report;
34 using mozilla::dom::ReportingObserver;
35 using mozilla::dom::ServiceWorker;
36 using mozilla::dom::ServiceWorkerDescriptor;
37 using mozilla::dom::ServiceWorkerRegistration;
38 using mozilla::dom::ServiceWorkerRegistrationDescriptor;
39 using mozilla::dom::VoidFunction;
41 nsIGlobalObject::nsIGlobalObject()
42 : mIsDying(false), mIsScriptForbidden(false), mIsInnerWindow(false) {}
44 bool nsIGlobalObject::IsScriptForbidden(JSObject* aCallback,
45 bool aIsJSImplementedWebIDL) const {
46 if (mIsScriptForbidden || mIsDying) {
47 return true;
50 if (NS_IsMainThread()) {
51 if (aIsJSImplementedWebIDL) {
52 return false;
54 if (!xpc::Scriptability::Get(aCallback).Allowed()) {
55 return true;
59 return false;
62 nsIGlobalObject::~nsIGlobalObject() {
63 UnlinkObjectsInGlobal();
64 DisconnectEventTargetObjects();
65 MOZ_DIAGNOSTIC_ASSERT(mEventTargetObjects.isEmpty());
68 nsIPrincipal* nsIGlobalObject::PrincipalOrNull() {
69 if (!NS_IsMainThread()) {
70 return nullptr;
73 JSObject* global = GetGlobalJSObjectPreserveColor();
74 if (NS_WARN_IF(!global)) return nullptr;
76 return nsContentUtils::ObjectPrincipal(global);
79 void nsIGlobalObject::RegisterHostObjectURI(const nsACString& aURI) {
80 MOZ_ASSERT(!mHostObjectURIs.Contains(aURI));
81 mHostObjectURIs.AppendElement(aURI);
84 void nsIGlobalObject::UnregisterHostObjectURI(const nsACString& aURI) {
85 mHostObjectURIs.RemoveElement(aURI);
88 namespace {
90 class UnlinkHostObjectURIsRunnable final : public mozilla::Runnable {
91 public:
92 explicit UnlinkHostObjectURIsRunnable(nsTArray<nsCString>&& aURIs)
93 : mozilla::Runnable("UnlinkHostObjectURIsRunnable"),
94 mURIs(std::move(aURIs)) {}
96 NS_IMETHOD Run() override {
97 MOZ_ASSERT(NS_IsMainThread());
99 for (uint32_t index = 0; index < mURIs.Length(); ++index) {
100 BlobURLProtocolHandler::RemoveDataEntry(mURIs[index]);
103 return NS_OK;
106 private:
107 ~UnlinkHostObjectURIsRunnable() = default;
109 const nsTArray<nsCString> mURIs;
112 } // namespace
114 void nsIGlobalObject::UnlinkObjectsInGlobal() {
115 if (!mHostObjectURIs.IsEmpty()) {
116 // BlobURLProtocolHandler is main-thread only.
117 if (NS_IsMainThread()) {
118 for (uint32_t index = 0; index < mHostObjectURIs.Length(); ++index) {
119 BlobURLProtocolHandler::RemoveDataEntry(mHostObjectURIs[index]);
122 mHostObjectURIs.Clear();
123 } else {
124 RefPtr<UnlinkHostObjectURIsRunnable> runnable =
125 new UnlinkHostObjectURIsRunnable(std::move(mHostObjectURIs));
126 MOZ_ASSERT(mHostObjectURIs.IsEmpty());
128 nsresult rv = NS_DispatchToMainThread(runnable);
129 if (NS_FAILED(rv)) {
130 NS_WARNING("Failed to dispatch a runnable to the main-thread.");
135 mReportRecords.Clear();
136 mReportingObservers.Clear();
137 #ifdef MOZ_DOM_STREAMS
138 mCountQueuingStrategySizeFunction = nullptr;
139 mByteLengthQueuingStrategySizeFunction = nullptr;
140 #endif
143 void nsIGlobalObject::TraverseObjectsInGlobal(
144 nsCycleCollectionTraversalCallback& cb) {
145 // Currently we only store BlobImpl objects off the the main-thread and they
146 // are not CCed.
147 if (!mHostObjectURIs.IsEmpty() && NS_IsMainThread()) {
148 for (uint32_t index = 0; index < mHostObjectURIs.Length(); ++index) {
149 BlobURLProtocolHandler::Traverse(mHostObjectURIs[index], cb);
153 nsIGlobalObject* tmp = this;
154 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportRecords)
155 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportingObservers)
156 #ifdef MOZ_DOM_STREAMS
157 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCountQueuingStrategySizeFunction)
158 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mByteLengthQueuingStrategySizeFunction)
159 #endif
162 void nsIGlobalObject::AddEventTargetObject(DOMEventTargetHelper* aObject) {
163 MOZ_DIAGNOSTIC_ASSERT(aObject);
164 MOZ_ASSERT(!aObject->isInList());
165 mEventTargetObjects.insertBack(aObject);
168 void nsIGlobalObject::RemoveEventTargetObject(DOMEventTargetHelper* aObject) {
169 MOZ_DIAGNOSTIC_ASSERT(aObject);
170 MOZ_ASSERT(aObject->isInList());
171 MOZ_ASSERT(aObject->GetOwnerGlobal() == this);
172 aObject->remove();
175 void nsIGlobalObject::ForEachEventTargetObject(
176 const std::function<void(DOMEventTargetHelper*, bool* aDoneOut)>& aFunc)
177 const {
178 // Protect against the function call triggering a mutation of the list
179 // while we are iterating by copying the DETH references to a temporary
180 // list.
181 AutoTArray<RefPtr<DOMEventTargetHelper>, 64> targetList;
182 for (const DOMEventTargetHelper* deth = mEventTargetObjects.getFirst(); deth;
183 deth = deth->getNext()) {
184 targetList.AppendElement(const_cast<DOMEventTargetHelper*>(deth));
187 // Iterate the target list and call the function on each one.
188 bool done = false;
189 for (auto target : targetList) {
190 // Check to see if a previous iteration's callback triggered the removal
191 // of this target as a side-effect. If it did, then just ignore it.
192 if (target->GetOwnerGlobal() != this) {
193 continue;
195 aFunc(target, &done);
196 if (done) {
197 break;
202 void nsIGlobalObject::DisconnectEventTargetObjects() {
203 ForEachEventTargetObject([&](DOMEventTargetHelper* aTarget, bool* aDoneOut) {
204 aTarget->DisconnectFromOwner();
206 // Calling DisconnectFromOwner() should result in
207 // RemoveEventTargetObject() being called.
208 MOZ_DIAGNOSTIC_ASSERT(aTarget->GetOwnerGlobal() != this);
212 Maybe<ClientInfo> nsIGlobalObject::GetClientInfo() const {
213 // By default globals do not expose themselves as a client. Only real
214 // window and worker globals are currently considered clients.
215 return Maybe<ClientInfo>();
218 Maybe<nsID> nsIGlobalObject::GetAgentClusterId() const {
219 Maybe<ClientInfo> ci = GetClientInfo();
220 if (ci.isSome()) {
221 return ci.value().AgentClusterId();
223 return mozilla::Nothing();
226 Maybe<ServiceWorkerDescriptor> nsIGlobalObject::GetController() const {
227 // By default globals do not have a service worker controller. Only real
228 // window and worker globals can currently be controlled as a client.
229 return Maybe<ServiceWorkerDescriptor>();
232 RefPtr<ServiceWorker> nsIGlobalObject::GetOrCreateServiceWorker(
233 const ServiceWorkerDescriptor& aDescriptor) {
234 MOZ_DIAGNOSTIC_ASSERT(false,
235 "this global should not have any service workers");
236 return nullptr;
239 RefPtr<ServiceWorkerRegistration> nsIGlobalObject::GetServiceWorkerRegistration(
240 const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
241 const {
242 MOZ_DIAGNOSTIC_ASSERT(false,
243 "this global should not have any service workers");
244 return nullptr;
247 RefPtr<ServiceWorkerRegistration>
248 nsIGlobalObject::GetOrCreateServiceWorkerRegistration(
249 const ServiceWorkerRegistrationDescriptor& aDescriptor) {
250 MOZ_DIAGNOSTIC_ASSERT(
251 false, "this global should not have any service worker registrations");
252 return nullptr;
255 mozilla::StorageAccess nsIGlobalObject::GetStorageAccess() {
256 return mozilla::StorageAccess::eDeny;
259 nsPIDOMWindowInner* nsIGlobalObject::AsInnerWindow() {
260 if (MOZ_LIKELY(mIsInnerWindow)) {
261 return static_cast<nsPIDOMWindowInner*>(
262 static_cast<nsGlobalWindowInner*>(this));
264 return nullptr;
267 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const {
268 size_t rtn = mHostObjectURIs.ShallowSizeOfExcludingThis(aSizeOf);
269 return rtn;
272 class QueuedMicrotask : public MicroTaskRunnable {
273 public:
274 QueuedMicrotask(nsIGlobalObject* aGlobal, VoidFunction& aCallback)
275 : mGlobal(aGlobal), mCallback(&aCallback) {}
277 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Run(AutoSlowOperation& aAso) final {
278 IgnoredErrorResult rv;
279 MOZ_KnownLive(mCallback)->Call(static_cast<ErrorResult&>(rv));
282 bool Suppressed() final { return mGlobal->IsInSyncOperation(); }
284 private:
285 nsCOMPtr<nsIGlobalObject> mGlobal;
286 RefPtr<VoidFunction> mCallback;
289 void nsIGlobalObject::QueueMicrotask(VoidFunction& aCallback) {
290 CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
291 if (context) {
292 RefPtr<MicroTaskRunnable> mt = new QueuedMicrotask(this, aCallback);
293 context->DispatchToMicroTask(mt.forget());
297 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver* aObserver,
298 bool aBuffered) {
299 MOZ_ASSERT(aObserver);
301 if (mReportingObservers.Contains(aObserver)) {
302 return;
305 if (NS_WARN_IF(
306 !mReportingObservers.AppendElement(aObserver, mozilla::fallible))) {
307 return;
310 if (!aBuffered) {
311 return;
314 for (Report* report : mReportRecords) {
315 aObserver->MaybeReport(report);
319 void nsIGlobalObject::UnregisterReportingObserver(
320 ReportingObserver* aObserver) {
321 MOZ_ASSERT(aObserver);
322 mReportingObservers.RemoveElement(aObserver);
325 void nsIGlobalObject::BroadcastReport(Report* aReport) {
326 MOZ_ASSERT(aReport);
328 for (ReportingObserver* observer : mReportingObservers) {
329 observer->MaybeReport(aReport);
332 if (NS_WARN_IF(!mReportRecords.AppendElement(aReport, mozilla::fallible))) {
333 return;
336 while (mReportRecords.Length() > MAX_REPORT_RECORDS) {
337 mReportRecords.RemoveElementAt(0);
341 void nsIGlobalObject::NotifyReportingObservers() {
342 for (auto& observer : mReportingObservers.Clone()) {
343 // MOZ_KnownLive because the clone of 'mReportingObservers' is guaranteed to
344 // keep it alive.
346 // This can go away once
347 // https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
348 MOZ_KnownLive(observer)->MaybeNotify();
352 void nsIGlobalObject::RemoveReportRecords() {
353 mReportRecords.Clear();
355 for (auto& observer : mReportingObservers) {
356 observer->ForgetReports();
360 #ifdef MOZ_DOM_STREAMS
361 already_AddRefed<mozilla::dom::Function>
362 nsIGlobalObject::GetCountQueuingStrategySizeFunction() {
363 return do_AddRef(mCountQueuingStrategySizeFunction);
366 void nsIGlobalObject::SetCountQueuingStrategySizeFunction(
367 mozilla::dom::Function* aFunction) {
368 mCountQueuingStrategySizeFunction = aFunction;
371 already_AddRefed<mozilla::dom::Function>
372 nsIGlobalObject::GetByteLengthQueuingStrategySizeFunction() {
373 return do_AddRef(mByteLengthQueuingStrategySizeFunction);
376 void nsIGlobalObject::SetByteLengthQueuingStrategySizeFunction(
377 mozilla::dom::Function* aFunction) {
378 mByteLengthQueuingStrategySizeFunction = aFunction;
380 #endif
382 bool nsIGlobalObject::ShouldResistFingerprinting() const {
383 return nsContentUtils::ShouldResistFingerprinting();