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/dom/BlobURLProtocolHandler.h"
10 #include "mozilla/dom/FunctionBinding.h"
11 #include "mozilla/dom/Report.h"
12 #include "mozilla/dom/ReportingObserver.h"
13 #include "mozilla/dom/ServiceWorker.h"
14 #include "mozilla/dom/ServiceWorkerRegistration.h"
15 #include "nsContentUtils.h"
16 #include "nsThreadUtils.h"
17 #include "nsGlobalWindowInner.h"
19 // Max number of Report objects
20 constexpr auto MAX_REPORT_RECORDS
= 100;
22 using mozilla::AutoSlowOperation
;
23 using mozilla::CycleCollectedJSContext
;
24 using mozilla::DOMEventTargetHelper
;
25 using mozilla::ErrorResult
;
26 using mozilla::IgnoredErrorResult
;
27 using mozilla::MallocSizeOf
;
29 using mozilla::MicroTaskRunnable
;
30 using mozilla::dom::BlobURLProtocolHandler
;
31 using mozilla::dom::ClientInfo
;
32 using mozilla::dom::Report
;
33 using mozilla::dom::ReportingObserver
;
34 using mozilla::dom::ServiceWorker
;
35 using mozilla::dom::ServiceWorkerDescriptor
;
36 using mozilla::dom::ServiceWorkerRegistration
;
37 using mozilla::dom::ServiceWorkerRegistrationDescriptor
;
38 using mozilla::dom::VoidFunction
;
40 nsIGlobalObject::nsIGlobalObject()
41 : mIsDying(false), mIsScriptForbidden(false), mIsInnerWindow(false) {}
43 bool nsIGlobalObject::IsScriptForbidden(JSObject
* aCallback
,
44 bool aIsJSImplementedWebIDL
) const {
45 if (mIsScriptForbidden
) {
49 if (NS_IsMainThread()) {
50 if (aIsJSImplementedWebIDL
) {
53 if (!xpc::Scriptability::Get(aCallback
).Allowed()) {
61 nsIGlobalObject::~nsIGlobalObject() {
62 UnlinkObjectsInGlobal();
63 DisconnectEventTargetObjects();
64 MOZ_DIAGNOSTIC_ASSERT(mEventTargetObjects
.isEmpty());
67 nsIPrincipal
* nsIGlobalObject::PrincipalOrNull() {
68 if (!NS_IsMainThread()) {
72 JSObject
* global
= GetGlobalJSObjectPreserveColor();
73 if (NS_WARN_IF(!global
)) return nullptr;
75 return nsContentUtils::ObjectPrincipal(global
);
78 void nsIGlobalObject::RegisterHostObjectURI(const nsACString
& aURI
) {
79 MOZ_ASSERT(!mHostObjectURIs
.Contains(aURI
));
80 mHostObjectURIs
.AppendElement(aURI
);
83 void nsIGlobalObject::UnregisterHostObjectURI(const nsACString
& aURI
) {
84 mHostObjectURIs
.RemoveElement(aURI
);
89 class UnlinkHostObjectURIsRunnable final
: public mozilla::Runnable
{
91 explicit UnlinkHostObjectURIsRunnable(nsTArray
<nsCString
>&& aURIs
)
92 : mozilla::Runnable("UnlinkHostObjectURIsRunnable"),
93 mURIs(std::move(aURIs
)) {}
95 NS_IMETHOD
Run() override
{
96 MOZ_ASSERT(NS_IsMainThread());
98 for (uint32_t index
= 0; index
< mURIs
.Length(); ++index
) {
99 BlobURLProtocolHandler::RemoveDataEntry(mURIs
[index
]);
106 ~UnlinkHostObjectURIsRunnable() = default;
108 const nsTArray
<nsCString
> mURIs
;
113 void nsIGlobalObject::UnlinkObjectsInGlobal() {
114 if (!mHostObjectURIs
.IsEmpty()) {
115 // BlobURLProtocolHandler is main-thread only.
116 if (NS_IsMainThread()) {
117 for (uint32_t index
= 0; index
< mHostObjectURIs
.Length(); ++index
) {
118 BlobURLProtocolHandler::RemoveDataEntry(mHostObjectURIs
[index
]);
121 mHostObjectURIs
.Clear();
123 RefPtr
<UnlinkHostObjectURIsRunnable
> runnable
=
124 new UnlinkHostObjectURIsRunnable(std::move(mHostObjectURIs
));
125 MOZ_ASSERT(mHostObjectURIs
.IsEmpty());
127 nsresult rv
= NS_DispatchToMainThread(runnable
);
129 NS_WARNING("Failed to dispatch a runnable to the main-thread.");
134 mReportRecords
.Clear();
135 mReportingObservers
.Clear();
138 void nsIGlobalObject::TraverseObjectsInGlobal(
139 nsCycleCollectionTraversalCallback
& cb
) {
140 // Currently we only store BlobImpl objects off the the main-thread and they
142 if (!mHostObjectURIs
.IsEmpty() && NS_IsMainThread()) {
143 for (uint32_t index
= 0; index
< mHostObjectURIs
.Length(); ++index
) {
144 BlobURLProtocolHandler::Traverse(mHostObjectURIs
[index
], cb
);
148 nsIGlobalObject
* tmp
= this;
149 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportRecords
)
150 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportingObservers
)
153 void nsIGlobalObject::AddEventTargetObject(DOMEventTargetHelper
* aObject
) {
154 MOZ_DIAGNOSTIC_ASSERT(aObject
);
155 MOZ_ASSERT(!aObject
->isInList());
156 mEventTargetObjects
.insertBack(aObject
);
159 void nsIGlobalObject::RemoveEventTargetObject(DOMEventTargetHelper
* aObject
) {
160 MOZ_DIAGNOSTIC_ASSERT(aObject
);
161 MOZ_ASSERT(aObject
->isInList());
162 MOZ_ASSERT(aObject
->GetOwnerGlobal() == this);
166 void nsIGlobalObject::ForEachEventTargetObject(
167 const std::function
<void(DOMEventTargetHelper
*, bool* aDoneOut
)>& aFunc
)
169 // Protect against the function call triggering a mutation of the list
170 // while we are iterating by copying the DETH references to a temporary
172 AutoTArray
<RefPtr
<DOMEventTargetHelper
>, 64> targetList
;
173 for (const DOMEventTargetHelper
* deth
= mEventTargetObjects
.getFirst(); deth
;
174 deth
= deth
->getNext()) {
175 targetList
.AppendElement(const_cast<DOMEventTargetHelper
*>(deth
));
178 // Iterate the target list and call the function on each one.
180 for (auto target
: targetList
) {
181 // Check to see if a previous iteration's callback triggered the removal
182 // of this target as a side-effect. If it did, then just ignore it.
183 if (target
->GetOwnerGlobal() != this) {
186 aFunc(target
, &done
);
193 void nsIGlobalObject::DisconnectEventTargetObjects() {
194 ForEachEventTargetObject([&](DOMEventTargetHelper
* aTarget
, bool* aDoneOut
) {
195 aTarget
->DisconnectFromOwner();
197 // Calling DisconnectFromOwner() should result in
198 // RemoveEventTargetObject() being called.
199 MOZ_DIAGNOSTIC_ASSERT(aTarget
->GetOwnerGlobal() != this);
203 Maybe
<ClientInfo
> nsIGlobalObject::GetClientInfo() const {
204 // By default globals do not expose themselves as a client. Only real
205 // window and worker globals are currently considered clients.
206 return Maybe
<ClientInfo
>();
209 Maybe
<nsID
> nsIGlobalObject::GetAgentClusterId() const {
210 Maybe
<ClientInfo
> ci
= GetClientInfo();
212 return ci
.value().AgentClusterId();
214 return mozilla::Nothing();
217 Maybe
<ServiceWorkerDescriptor
> nsIGlobalObject::GetController() const {
218 // By default globals do not have a service worker controller. Only real
219 // window and worker globals can currently be controlled as a client.
220 return Maybe
<ServiceWorkerDescriptor
>();
223 RefPtr
<ServiceWorker
> nsIGlobalObject::GetOrCreateServiceWorker(
224 const ServiceWorkerDescriptor
& aDescriptor
) {
225 MOZ_DIAGNOSTIC_ASSERT(false,
226 "this global should not have any service workers");
230 RefPtr
<ServiceWorkerRegistration
> nsIGlobalObject::GetServiceWorkerRegistration(
231 const mozilla::dom::ServiceWorkerRegistrationDescriptor
& aDescriptor
)
233 MOZ_DIAGNOSTIC_ASSERT(false,
234 "this global should not have any service workers");
238 RefPtr
<ServiceWorkerRegistration
>
239 nsIGlobalObject::GetOrCreateServiceWorkerRegistration(
240 const ServiceWorkerRegistrationDescriptor
& aDescriptor
) {
241 MOZ_DIAGNOSTIC_ASSERT(
242 false, "this global should not have any service worker registrations");
246 nsPIDOMWindowInner
* nsIGlobalObject::AsInnerWindow() {
247 if (MOZ_LIKELY(mIsInnerWindow
)) {
248 return static_cast<nsPIDOMWindowInner
*>(
249 static_cast<nsGlobalWindowInner
*>(this));
254 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf
) const {
255 size_t rtn
= mHostObjectURIs
.ShallowSizeOfExcludingThis(aSizeOf
);
259 class QueuedMicrotask
: public MicroTaskRunnable
{
261 QueuedMicrotask(nsIGlobalObject
* aGlobal
, VoidFunction
& aCallback
)
262 : mGlobal(aGlobal
), mCallback(&aCallback
) {}
264 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void Run(AutoSlowOperation
& aAso
) final
{
265 IgnoredErrorResult rv
;
266 MOZ_KnownLive(mCallback
)->Call(static_cast<ErrorResult
&>(rv
));
269 bool Suppressed() final
{ return mGlobal
->IsInSyncOperation(); }
272 nsCOMPtr
<nsIGlobalObject
> mGlobal
;
273 RefPtr
<VoidFunction
> mCallback
;
276 void nsIGlobalObject::QueueMicrotask(VoidFunction
& aCallback
) {
277 CycleCollectedJSContext
* context
= CycleCollectedJSContext::Get();
279 RefPtr
<MicroTaskRunnable
> mt
= new QueuedMicrotask(this, aCallback
);
280 context
->DispatchToMicroTask(mt
.forget());
284 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver
* aObserver
,
286 MOZ_ASSERT(aObserver
);
288 if (mReportingObservers
.Contains(aObserver
)) {
293 !mReportingObservers
.AppendElement(aObserver
, mozilla::fallible
))) {
301 for (Report
* report
: mReportRecords
) {
302 aObserver
->MaybeReport(report
);
306 void nsIGlobalObject::UnregisterReportingObserver(
307 ReportingObserver
* aObserver
) {
308 MOZ_ASSERT(aObserver
);
309 mReportingObservers
.RemoveElement(aObserver
);
312 void nsIGlobalObject::BroadcastReport(Report
* aReport
) {
315 for (ReportingObserver
* observer
: mReportingObservers
) {
316 observer
->MaybeReport(aReport
);
319 if (NS_WARN_IF(!mReportRecords
.AppendElement(aReport
, mozilla::fallible
))) {
323 while (mReportRecords
.Length() > MAX_REPORT_RECORDS
) {
324 mReportRecords
.RemoveElementAt(0);
328 void nsIGlobalObject::NotifyReportingObservers() {
329 for (auto& observer
: mReportingObservers
.Clone()) {
330 // MOZ_KnownLive because the clone of 'mReportingObservers' is guaranteed to
333 // This can go away once
334 // https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
335 MOZ_KnownLive(observer
)->MaybeNotify();
339 void nsIGlobalObject::RemoveReportRecords() {
340 mReportRecords
.Clear();
342 for (auto& observer
: mReportingObservers
) {
343 observer
->ForgetReports();