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/Result.h"
11 #include "mozilla/StorageAccess.h"
12 #include "mozilla/dom/BindingDeclarations.h"
13 #include "mozilla/dom/BlobURLProtocolHandler.h"
14 #include "mozilla/dom/FunctionBinding.h"
15 #include "mozilla/dom/Report.h"
16 #include "mozilla/dom/ReportingObserver.h"
17 #include "mozilla/dom/ServiceWorker.h"
18 #include "mozilla/dom/ServiceWorkerRegistration.h"
19 #include "mozilla/ipc/PBackgroundSharedTypes.h"
20 #include "nsContentUtils.h"
21 #include "nsThreadUtils.h"
22 #include "nsGlobalWindowInner.h"
24 // Max number of Report objects
25 constexpr auto MAX_REPORT_RECORDS
= 100;
27 using mozilla::AutoSlowOperation
;
28 using mozilla::CycleCollectedJSContext
;
29 using mozilla::DOMEventTargetHelper
;
30 using mozilla::ErrorResult
;
31 using mozilla::IgnoredErrorResult
;
32 using mozilla::MallocSizeOf
;
34 using mozilla::MicroTaskRunnable
;
35 using mozilla::dom::BlobURLProtocolHandler
;
36 using mozilla::dom::CallerType
;
37 using mozilla::dom::ClientInfo
;
38 using mozilla::dom::Report
;
39 using mozilla::dom::ReportingObserver
;
40 using mozilla::dom::ServiceWorker
;
41 using mozilla::dom::ServiceWorkerDescriptor
;
42 using mozilla::dom::ServiceWorkerRegistration
;
43 using mozilla::dom::ServiceWorkerRegistrationDescriptor
;
44 using mozilla::dom::VoidFunction
;
46 nsIGlobalObject::nsIGlobalObject()
47 : mIsDying(false), mIsScriptForbidden(false), mIsInnerWindow(false) {}
49 bool nsIGlobalObject::IsScriptForbidden(JSObject
* aCallback
,
50 bool aIsJSImplementedWebIDL
) const {
51 if (mIsScriptForbidden
|| mIsDying
) {
55 if (NS_IsMainThread()) {
56 if (aIsJSImplementedWebIDL
) {
60 if (!xpc::Scriptability::AllowedIfExists(aCallback
)) {
68 nsIGlobalObject::~nsIGlobalObject() {
69 UnlinkObjectsInGlobal();
70 DisconnectEventTargetObjects();
71 MOZ_DIAGNOSTIC_ASSERT(mEventTargetObjects
.isEmpty());
74 nsIPrincipal
* nsIGlobalObject::PrincipalOrNull() const {
75 JSObject
* global
= GetGlobalJSObjectPreserveColor();
76 if (NS_WARN_IF(!global
)) return nullptr;
78 return nsContentUtils::ObjectPrincipal(global
);
81 void nsIGlobalObject::RegisterHostObjectURI(const nsACString
& aURI
) {
82 MOZ_ASSERT(!mHostObjectURIs
.Contains(aURI
));
83 mHostObjectURIs
.AppendElement(aURI
);
86 void nsIGlobalObject::UnregisterHostObjectURI(const nsACString
& aURI
) {
87 mHostObjectURIs
.RemoveElement(aURI
);
92 class UnlinkHostObjectURIsRunnable final
: public mozilla::Runnable
{
94 explicit UnlinkHostObjectURIsRunnable(nsTArray
<nsCString
>&& aURIs
)
95 : mozilla::Runnable("UnlinkHostObjectURIsRunnable"),
96 mURIs(std::move(aURIs
)) {}
98 NS_IMETHOD
Run() override
{
99 MOZ_ASSERT(NS_IsMainThread());
101 for (uint32_t index
= 0; index
< mURIs
.Length(); ++index
) {
102 BlobURLProtocolHandler::RemoveDataEntry(mURIs
[index
]);
109 ~UnlinkHostObjectURIsRunnable() = default;
111 const nsTArray
<nsCString
> mURIs
;
116 void nsIGlobalObject::UnlinkObjectsInGlobal() {
117 if (!mHostObjectURIs
.IsEmpty()) {
118 // BlobURLProtocolHandler is main-thread only.
119 if (NS_IsMainThread()) {
120 for (uint32_t index
= 0; index
< mHostObjectURIs
.Length(); ++index
) {
121 BlobURLProtocolHandler::RemoveDataEntry(mHostObjectURIs
[index
]);
124 mHostObjectURIs
.Clear();
126 RefPtr
<UnlinkHostObjectURIsRunnable
> runnable
=
127 new UnlinkHostObjectURIsRunnable(std::move(mHostObjectURIs
));
128 MOZ_ASSERT(mHostObjectURIs
.IsEmpty());
130 nsresult rv
= NS_DispatchToMainThread(runnable
);
132 NS_WARNING("Failed to dispatch a runnable to the main-thread.");
137 mReportRecords
.Clear();
138 mReportingObservers
.Clear();
139 mCountQueuingStrategySizeFunction
= nullptr;
140 mByteLengthQueuingStrategySizeFunction
= nullptr;
143 void nsIGlobalObject::TraverseObjectsInGlobal(
144 nsCycleCollectionTraversalCallback
& cb
) {
145 // Currently we only store BlobImpl objects off the the main-thread and they
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 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCountQueuingStrategySizeFunction
)
157 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mByteLengthQueuingStrategySizeFunction
)
160 void nsIGlobalObject::AddEventTargetObject(DOMEventTargetHelper
* aObject
) {
161 MOZ_DIAGNOSTIC_ASSERT(aObject
);
162 MOZ_ASSERT(!aObject
->isInList());
163 mEventTargetObjects
.insertBack(aObject
);
166 void nsIGlobalObject::RemoveEventTargetObject(DOMEventTargetHelper
* aObject
) {
167 MOZ_DIAGNOSTIC_ASSERT(aObject
);
168 MOZ_ASSERT(aObject
->isInList());
169 MOZ_ASSERT(aObject
->GetOwnerGlobal() == this);
173 void nsIGlobalObject::ForEachEventTargetObject(
174 const std::function
<void(DOMEventTargetHelper
*, bool* aDoneOut
)>& aFunc
)
176 // Protect against the function call triggering a mutation of the list
177 // while we are iterating by copying the DETH references to a temporary
179 AutoTArray
<RefPtr
<DOMEventTargetHelper
>, 64> targetList
;
180 for (const DOMEventTargetHelper
* deth
= mEventTargetObjects
.getFirst(); deth
;
181 deth
= deth
->getNext()) {
182 targetList
.AppendElement(const_cast<DOMEventTargetHelper
*>(deth
));
185 // Iterate the target list and call the function on each one.
187 for (auto target
: targetList
) {
188 // Check to see if a previous iteration's callback triggered the removal
189 // of this target as a side-effect. If it did, then just ignore it.
190 if (target
->GetOwnerGlobal() != this) {
193 aFunc(target
, &done
);
200 void nsIGlobalObject::DisconnectEventTargetObjects() {
201 ForEachEventTargetObject([&](DOMEventTargetHelper
* aTarget
, bool* aDoneOut
) {
202 aTarget
->DisconnectFromOwner();
204 // Calling DisconnectFromOwner() should result in
205 // RemoveEventTargetObject() being called.
206 MOZ_DIAGNOSTIC_ASSERT(aTarget
->GetOwnerGlobal() != this);
210 Maybe
<ClientInfo
> nsIGlobalObject::GetClientInfo() const {
211 // By default globals do not expose themselves as a client. Only real
212 // window and worker globals are currently considered clients.
213 return Maybe
<ClientInfo
>();
216 Maybe
<nsID
> nsIGlobalObject::GetAgentClusterId() const {
217 Maybe
<ClientInfo
> ci
= GetClientInfo();
219 return ci
.value().AgentClusterId();
221 return mozilla::Nothing();
224 Maybe
<ServiceWorkerDescriptor
> nsIGlobalObject::GetController() const {
225 // By default globals do not have a service worker controller. Only real
226 // window and worker globals can currently be controlled as a client.
227 return Maybe
<ServiceWorkerDescriptor
>();
230 RefPtr
<ServiceWorker
> nsIGlobalObject::GetOrCreateServiceWorker(
231 const ServiceWorkerDescriptor
& aDescriptor
) {
232 MOZ_DIAGNOSTIC_ASSERT(false,
233 "this global should not have any service workers");
237 RefPtr
<ServiceWorkerRegistration
> nsIGlobalObject::GetServiceWorkerRegistration(
238 const mozilla::dom::ServiceWorkerRegistrationDescriptor
& aDescriptor
)
240 MOZ_DIAGNOSTIC_ASSERT(false,
241 "this global should not have any service workers");
245 RefPtr
<ServiceWorkerRegistration
>
246 nsIGlobalObject::GetOrCreateServiceWorkerRegistration(
247 const ServiceWorkerRegistrationDescriptor
& aDescriptor
) {
248 MOZ_DIAGNOSTIC_ASSERT(
249 false, "this global should not have any service worker registrations");
253 mozilla::StorageAccess
nsIGlobalObject::GetStorageAccess() {
254 return mozilla::StorageAccess::eDeny
;
257 nsPIDOMWindowInner
* nsIGlobalObject::GetAsInnerWindow() {
258 if (MOZ_LIKELY(mIsInnerWindow
)) {
259 return static_cast<nsPIDOMWindowInner
*>(
260 static_cast<nsGlobalWindowInner
*>(this));
265 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf
) const {
266 size_t rtn
= mHostObjectURIs
.ShallowSizeOfExcludingThis(aSizeOf
);
270 class QueuedMicrotask
: public MicroTaskRunnable
{
272 QueuedMicrotask(nsIGlobalObject
* aGlobal
, VoidFunction
& aCallback
)
273 : mGlobal(aGlobal
), mCallback(&aCallback
) {}
275 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void Run(AutoSlowOperation
& aAso
) final
{
276 IgnoredErrorResult rv
;
277 MOZ_KnownLive(mCallback
)->Call(static_cast<ErrorResult
&>(rv
));
280 bool Suppressed() final
{ return mGlobal
->IsInSyncOperation(); }
283 nsCOMPtr
<nsIGlobalObject
> mGlobal
;
284 RefPtr
<VoidFunction
> mCallback
;
287 void nsIGlobalObject::QueueMicrotask(VoidFunction
& aCallback
) {
288 CycleCollectedJSContext
* context
= CycleCollectedJSContext::Get();
290 RefPtr
<MicroTaskRunnable
> mt
= new QueuedMicrotask(this, aCallback
);
291 context
->DispatchToMicroTask(mt
.forget());
295 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver
* aObserver
,
297 MOZ_ASSERT(aObserver
);
299 if (mReportingObservers
.Contains(aObserver
)) {
304 !mReportingObservers
.AppendElement(aObserver
, mozilla::fallible
))) {
312 for (Report
* report
: mReportRecords
) {
313 aObserver
->MaybeReport(report
);
317 void nsIGlobalObject::UnregisterReportingObserver(
318 ReportingObserver
* aObserver
) {
319 MOZ_ASSERT(aObserver
);
320 mReportingObservers
.RemoveElement(aObserver
);
323 void nsIGlobalObject::BroadcastReport(Report
* aReport
) {
326 for (ReportingObserver
* observer
: mReportingObservers
) {
327 observer
->MaybeReport(aReport
);
330 if (NS_WARN_IF(!mReportRecords
.AppendElement(aReport
, mozilla::fallible
))) {
334 while (mReportRecords
.Length() > MAX_REPORT_RECORDS
) {
335 mReportRecords
.RemoveElementAt(0);
339 void nsIGlobalObject::NotifyReportingObservers() {
340 for (auto& observer
: mReportingObservers
.Clone()) {
341 // MOZ_KnownLive because the clone of 'mReportingObservers' is guaranteed to
344 // This can go away once
345 // https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
346 MOZ_KnownLive(observer
)->MaybeNotify();
350 void nsIGlobalObject::RemoveReportRecords() {
351 mReportRecords
.Clear();
353 for (auto& observer
: mReportingObservers
) {
354 observer
->ForgetReports();
358 already_AddRefed
<mozilla::dom::Function
>
359 nsIGlobalObject::GetCountQueuingStrategySizeFunction() {
360 return do_AddRef(mCountQueuingStrategySizeFunction
);
363 void nsIGlobalObject::SetCountQueuingStrategySizeFunction(
364 mozilla::dom::Function
* aFunction
) {
365 mCountQueuingStrategySizeFunction
= aFunction
;
368 already_AddRefed
<mozilla::dom::Function
>
369 nsIGlobalObject::GetByteLengthQueuingStrategySizeFunction() {
370 return do_AddRef(mByteLengthQueuingStrategySizeFunction
);
373 void nsIGlobalObject::SetByteLengthQueuingStrategySizeFunction(
374 mozilla::dom::Function
* aFunction
) {
375 mByteLengthQueuingStrategySizeFunction
= aFunction
;
378 mozilla::Result
<mozilla::ipc::PrincipalInfo
, nsresult
>
379 nsIGlobalObject::GetStorageKey() {
380 return mozilla::Err(NS_ERROR_NOT_AVAILABLE
);
383 mozilla::Result
<bool, nsresult
> nsIGlobalObject::HasEqualStorageKey(
384 const mozilla::ipc::PrincipalInfo
& aStorageKey
) {
385 auto result
= GetStorageKey();
386 if (result
.isErr()) {
387 return result
.propagateErr();
390 const auto& storageKey
= result
.inspect();
392 return mozilla::ipc::StorageKeysEqual(storageKey
, aStorageKey
);
395 mozilla::RTPCallerType
nsIGlobalObject::GetRTPCallerType() const {
396 if (PrincipalOrNull() && PrincipalOrNull()->IsSystemPrincipal()) {
397 return RTPCallerType::SystemPrincipal
;
400 if (ShouldResistFingerprinting(RFPTarget::ReduceTimerPrecision
)) {
401 return RTPCallerType::ResistFingerprinting
;
404 if (CrossOriginIsolated()) {
405 return RTPCallerType::CrossOriginIsolated
;
408 return RTPCallerType::Normal
;
411 bool nsIGlobalObject::ShouldResistFingerprinting(CallerType aCallerType
,
412 RFPTarget aTarget
) const {
413 return aCallerType
!= CallerType::System
&&
414 ShouldResistFingerprinting(aTarget
);