Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / dom / base / nsIGlobalObject.cpp
blob2c7ebb25620ae0d2de6a8f906cd60ddc83924c00
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/BasePrincipal.h"
9 #include "mozilla/CycleCollectedJSContext.h"
10 #include "mozilla/GlobalTeardownObserver.h"
11 #include "mozilla/Result.h"
12 #include "mozilla/StorageAccess.h"
13 #include "mozilla/dom/BindingDeclarations.h"
14 #include "mozilla/dom/BlobURLProtocolHandler.h"
15 #include "mozilla/dom/FunctionBinding.h"
16 #include "mozilla/dom/Report.h"
17 #include "mozilla/dom/ReportingObserver.h"
18 #include "mozilla/dom/ServiceWorker.h"
19 #include "mozilla/dom/ServiceWorkerRegistration.h"
20 #include "mozilla/ipc/PBackgroundSharedTypes.h"
21 #include "nsContentUtils.h"
22 #include "nsThreadUtils.h"
23 #include "nsGlobalWindowInner.h"
25 // Max number of Report objects
26 constexpr auto MAX_REPORT_RECORDS = 100;
28 using mozilla::AutoSlowOperation;
29 using mozilla::CycleCollectedJSContext;
30 using mozilla::DOMEventTargetHelper;
31 using mozilla::ErrorResult;
32 using mozilla::GlobalTeardownObserver;
33 using mozilla::IgnoredErrorResult;
34 using mozilla::MallocSizeOf;
35 using mozilla::Maybe;
36 using mozilla::MicroTaskRunnable;
37 using mozilla::dom::BlobURLProtocolHandler;
38 using mozilla::dom::CallerType;
39 using mozilla::dom::ClientInfo;
40 using mozilla::dom::Report;
41 using mozilla::dom::ReportingObserver;
42 using mozilla::dom::ServiceWorker;
43 using mozilla::dom::ServiceWorkerDescriptor;
44 using mozilla::dom::ServiceWorkerRegistration;
45 using mozilla::dom::ServiceWorkerRegistrationDescriptor;
46 using mozilla::dom::VoidFunction;
48 nsIGlobalObject::nsIGlobalObject()
49 : mIsDying(false), mIsScriptForbidden(false), mIsInnerWindow(false) {}
51 bool nsIGlobalObject::IsScriptForbidden(JSObject* aCallback,
52 bool aIsJSImplementedWebIDL) const {
53 if (mIsScriptForbidden || mIsDying) {
54 return true;
57 if (NS_IsMainThread()) {
58 if (aIsJSImplementedWebIDL) {
59 return false;
62 if (!xpc::Scriptability::AllowedIfExists(aCallback)) {
63 return true;
67 return false;
70 nsIGlobalObject::~nsIGlobalObject() {
71 UnlinkObjectsInGlobal();
72 DisconnectGlobalTeardownObservers();
73 MOZ_DIAGNOSTIC_ASSERT(mGlobalTeardownObservers.isEmpty());
76 nsIPrincipal* nsIGlobalObject::PrincipalOrNull() const {
77 JSObject* global = GetGlobalJSObjectPreserveColor();
78 if (NS_WARN_IF(!global)) return nullptr;
80 return nsContentUtils::ObjectPrincipal(global);
83 void nsIGlobalObject::RegisterHostObjectURI(const nsACString& aURI) {
84 MOZ_ASSERT(!mHostObjectURIs.Contains(aURI));
85 mHostObjectURIs.AppendElement(aURI);
88 void nsIGlobalObject::UnregisterHostObjectURI(const nsACString& aURI) {
89 mHostObjectURIs.RemoveElement(aURI);
92 namespace {
94 class UnlinkHostObjectURIsRunnable final : public mozilla::Runnable {
95 public:
96 explicit UnlinkHostObjectURIsRunnable(nsTArray<nsCString>&& aURIs)
97 : mozilla::Runnable("UnlinkHostObjectURIsRunnable"),
98 mURIs(std::move(aURIs)) {}
100 NS_IMETHOD Run() override {
101 MOZ_ASSERT(NS_IsMainThread());
103 for (uint32_t index = 0; index < mURIs.Length(); ++index) {
104 BlobURLProtocolHandler::RemoveDataEntry(mURIs[index]);
107 return NS_OK;
110 private:
111 ~UnlinkHostObjectURIsRunnable() = default;
113 const nsTArray<nsCString> mURIs;
116 } // namespace
118 void nsIGlobalObject::UnlinkObjectsInGlobal() {
119 if (!mHostObjectURIs.IsEmpty()) {
120 // BlobURLProtocolHandler is main-thread only.
121 if (NS_IsMainThread()) {
122 for (uint32_t index = 0; index < mHostObjectURIs.Length(); ++index) {
123 BlobURLProtocolHandler::RemoveDataEntry(mHostObjectURIs[index]);
126 mHostObjectURIs.Clear();
127 } else {
128 RefPtr<UnlinkHostObjectURIsRunnable> runnable =
129 new UnlinkHostObjectURIsRunnable(std::move(mHostObjectURIs));
130 MOZ_ASSERT(mHostObjectURIs.IsEmpty());
132 nsresult rv = NS_DispatchToMainThread(runnable);
133 if (NS_FAILED(rv)) {
134 NS_WARNING("Failed to dispatch a runnable to the main-thread.");
139 mReportRecords.Clear();
140 mReportingObservers.Clear();
141 mCountQueuingStrategySizeFunction = nullptr;
142 mByteLengthQueuingStrategySizeFunction = nullptr;
145 void nsIGlobalObject::TraverseObjectsInGlobal(
146 nsCycleCollectionTraversalCallback& cb) {
147 // Currently we only store BlobImpl objects off the the main-thread and they
148 // are not CCed.
149 if (!mHostObjectURIs.IsEmpty() && NS_IsMainThread()) {
150 for (uint32_t index = 0; index < mHostObjectURIs.Length(); ++index) {
151 BlobURLProtocolHandler::Traverse(mHostObjectURIs[index], cb);
155 nsIGlobalObject* tmp = this;
156 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportRecords)
157 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportingObservers)
158 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCountQueuingStrategySizeFunction)
159 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mByteLengthQueuingStrategySizeFunction)
162 void nsIGlobalObject::AddGlobalTeardownObserver(
163 GlobalTeardownObserver* aObject) {
164 MOZ_DIAGNOSTIC_ASSERT(aObject);
165 MOZ_ASSERT(!aObject->isInList());
166 mGlobalTeardownObservers.insertBack(aObject);
169 void nsIGlobalObject::RemoveGlobalTeardownObserver(
170 GlobalTeardownObserver* aObject) {
171 MOZ_DIAGNOSTIC_ASSERT(aObject);
172 MOZ_ASSERT(aObject->isInList());
173 MOZ_ASSERT(aObject->GetOwnerGlobal() == this);
174 aObject->remove();
177 void nsIGlobalObject::ForEachGlobalTeardownObserver(
178 const std::function<void(GlobalTeardownObserver*, bool* aDoneOut)>& aFunc)
179 const {
180 // Protect against the function call triggering a mutation of the list
181 // while we are iterating by copying the DETH references to a temporary
182 // list.
183 AutoTArray<RefPtr<GlobalTeardownObserver>, 64> targetList;
184 for (const GlobalTeardownObserver* gto = mGlobalTeardownObservers.getFirst();
185 gto; gto = gto->getNext()) {
186 targetList.AppendElement(const_cast<GlobalTeardownObserver*>(gto));
189 // Iterate the target list and call the function on each one.
190 bool done = false;
191 for (auto& target : targetList) {
192 // Check to see if a previous iteration's callback triggered the removal
193 // of this target as a side-effect. If it did, then just ignore it.
194 if (target->GetOwnerGlobal() != this) {
195 continue;
197 aFunc(target, &done);
198 if (done) {
199 break;
204 void nsIGlobalObject::DisconnectGlobalTeardownObservers() {
205 ForEachGlobalTeardownObserver(
206 [&](GlobalTeardownObserver* aTarget, bool* aDoneOut) {
207 aTarget->DisconnectFromOwner();
209 // Calling DisconnectFromOwner() should result in
210 // RemoveGlobalTeardownObserver() being called.
211 MOZ_DIAGNOSTIC_ASSERT(aTarget->GetOwnerGlobal() != this);
215 Maybe<ClientInfo> nsIGlobalObject::GetClientInfo() const {
216 // By default globals do not expose themselves as a client. Only real
217 // window and worker globals are currently considered clients.
218 return Maybe<ClientInfo>();
221 Maybe<nsID> nsIGlobalObject::GetAgentClusterId() const {
222 Maybe<ClientInfo> ci = GetClientInfo();
223 if (ci.isSome()) {
224 return ci.value().AgentClusterId();
226 return mozilla::Nothing();
229 Maybe<ServiceWorkerDescriptor> nsIGlobalObject::GetController() const {
230 // By default globals do not have a service worker controller. Only real
231 // window and worker globals can currently be controlled as a client.
232 return Maybe<ServiceWorkerDescriptor>();
235 RefPtr<ServiceWorker> nsIGlobalObject::GetOrCreateServiceWorker(
236 const ServiceWorkerDescriptor& aDescriptor) {
237 MOZ_DIAGNOSTIC_ASSERT(false,
238 "this global should not have any service workers");
239 return nullptr;
242 RefPtr<ServiceWorkerRegistration> nsIGlobalObject::GetServiceWorkerRegistration(
243 const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
244 const {
245 MOZ_DIAGNOSTIC_ASSERT(false,
246 "this global should not have any service workers");
247 return nullptr;
250 RefPtr<ServiceWorkerRegistration>
251 nsIGlobalObject::GetOrCreateServiceWorkerRegistration(
252 const ServiceWorkerRegistrationDescriptor& aDescriptor) {
253 MOZ_DIAGNOSTIC_ASSERT(
254 false, "this global should not have any service worker registrations");
255 return nullptr;
258 mozilla::StorageAccess nsIGlobalObject::GetStorageAccess() {
259 return mozilla::StorageAccess::eDeny;
262 nsPIDOMWindowInner* nsIGlobalObject::GetAsInnerWindow() {
263 if (MOZ_LIKELY(mIsInnerWindow)) {
264 return static_cast<nsPIDOMWindowInner*>(
265 static_cast<nsGlobalWindowInner*>(this));
267 return nullptr;
270 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const {
271 size_t rtn = mHostObjectURIs.ShallowSizeOfExcludingThis(aSizeOf);
272 return rtn;
275 class QueuedMicrotask : public MicroTaskRunnable {
276 public:
277 QueuedMicrotask(nsIGlobalObject* aGlobal, VoidFunction& aCallback)
278 : mGlobal(aGlobal), mCallback(&aCallback) {}
280 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Run(AutoSlowOperation& aAso) final {
281 IgnoredErrorResult rv;
282 MOZ_KnownLive(mCallback)->Call(static_cast<ErrorResult&>(rv));
285 bool Suppressed() final { return mGlobal->IsInSyncOperation(); }
287 private:
288 nsCOMPtr<nsIGlobalObject> mGlobal;
289 RefPtr<VoidFunction> mCallback;
292 void nsIGlobalObject::QueueMicrotask(VoidFunction& aCallback) {
293 CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
294 if (context) {
295 RefPtr<MicroTaskRunnable> mt = new QueuedMicrotask(this, aCallback);
296 context->DispatchToMicroTask(mt.forget());
300 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver* aObserver,
301 bool aBuffered) {
302 MOZ_ASSERT(aObserver);
304 if (mReportingObservers.Contains(aObserver)) {
305 return;
308 if (NS_WARN_IF(
309 !mReportingObservers.AppendElement(aObserver, mozilla::fallible))) {
310 return;
313 if (!aBuffered) {
314 return;
317 for (Report* report : mReportRecords) {
318 aObserver->MaybeReport(report);
322 void nsIGlobalObject::UnregisterReportingObserver(
323 ReportingObserver* aObserver) {
324 MOZ_ASSERT(aObserver);
325 mReportingObservers.RemoveElement(aObserver);
328 void nsIGlobalObject::BroadcastReport(Report* aReport) {
329 MOZ_ASSERT(aReport);
331 for (ReportingObserver* observer : mReportingObservers) {
332 observer->MaybeReport(aReport);
335 if (NS_WARN_IF(!mReportRecords.AppendElement(aReport, mozilla::fallible))) {
336 return;
339 while (mReportRecords.Length() > MAX_REPORT_RECORDS) {
340 mReportRecords.RemoveElementAt(0);
344 void nsIGlobalObject::NotifyReportingObservers() {
345 for (auto& observer : mReportingObservers.Clone()) {
346 // MOZ_KnownLive because the clone of 'mReportingObservers' is guaranteed to
347 // keep it alive.
349 // This can go away once
350 // https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
351 MOZ_KnownLive(observer)->MaybeNotify();
355 void nsIGlobalObject::RemoveReportRecords() {
356 mReportRecords.Clear();
358 for (auto& observer : mReportingObservers) {
359 observer->ForgetReports();
363 already_AddRefed<mozilla::dom::Function>
364 nsIGlobalObject::GetCountQueuingStrategySizeFunction() {
365 return do_AddRef(mCountQueuingStrategySizeFunction);
368 void nsIGlobalObject::SetCountQueuingStrategySizeFunction(
369 mozilla::dom::Function* aFunction) {
370 mCountQueuingStrategySizeFunction = aFunction;
373 already_AddRefed<mozilla::dom::Function>
374 nsIGlobalObject::GetByteLengthQueuingStrategySizeFunction() {
375 return do_AddRef(mByteLengthQueuingStrategySizeFunction);
378 void nsIGlobalObject::SetByteLengthQueuingStrategySizeFunction(
379 mozilla::dom::Function* aFunction) {
380 mByteLengthQueuingStrategySizeFunction = aFunction;
383 mozilla::Result<mozilla::ipc::PrincipalInfo, nsresult>
384 nsIGlobalObject::GetStorageKey() {
385 return mozilla::Err(NS_ERROR_NOT_AVAILABLE);
388 mozilla::Result<bool, nsresult> nsIGlobalObject::HasEqualStorageKey(
389 const mozilla::ipc::PrincipalInfo& aStorageKey) {
390 auto result = GetStorageKey();
391 if (result.isErr()) {
392 return result.propagateErr();
395 const auto& storageKey = result.inspect();
397 return mozilla::ipc::StorageKeysEqual(storageKey, aStorageKey);
400 mozilla::RTPCallerType nsIGlobalObject::GetRTPCallerType() const {
401 if (PrincipalOrNull() && PrincipalOrNull()->IsSystemPrincipal()) {
402 return RTPCallerType::SystemPrincipal;
405 if (ShouldResistFingerprinting(RFPTarget::ReduceTimerPrecision)) {
406 return RTPCallerType::ResistFingerprinting;
409 if (CrossOriginIsolated()) {
410 return RTPCallerType::CrossOriginIsolated;
413 return RTPCallerType::Normal;
416 bool nsIGlobalObject::ShouldResistFingerprinting(CallerType aCallerType,
417 RFPTarget aTarget) const {
418 return aCallerType != CallerType::System &&
419 ShouldResistFingerprinting(aTarget);