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/. */
6
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"
19
20 // Max number of Report objects
21 constexpr auto MAX_REPORT_RECORDS = 100;
22
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;
40
nsIGlobalObject()41 nsIGlobalObject::nsIGlobalObject()
42 : mIsDying(false), mIsScriptForbidden(false), mIsInnerWindow(false) {}
43
IsScriptForbidden(JSObject * aCallback,bool aIsJSImplementedWebIDL) const44 bool nsIGlobalObject::IsScriptForbidden(JSObject* aCallback,
45 bool aIsJSImplementedWebIDL) const {
46 if (mIsScriptForbidden || mIsDying) {
47 return true;
48 }
49
50 if (NS_IsMainThread()) {
51 if (aIsJSImplementedWebIDL) {
52 return false;
53 }
54 if (!xpc::Scriptability::Get(aCallback).Allowed()) {
55 return true;
56 }
57 }
58
59 return false;
60 }
61
~nsIGlobalObject()62 nsIGlobalObject::~nsIGlobalObject() {
63 UnlinkObjectsInGlobal();
64 DisconnectEventTargetObjects();
65 MOZ_DIAGNOSTIC_ASSERT(mEventTargetObjects.isEmpty());
66 }
67
PrincipalOrNull()68 nsIPrincipal* nsIGlobalObject::PrincipalOrNull() {
69 if (!NS_IsMainThread()) {
70 return nullptr;
71 }
72
73 JSObject* global = GetGlobalJSObjectPreserveColor();
74 if (NS_WARN_IF(!global)) return nullptr;
75
76 return nsContentUtils::ObjectPrincipal(global);
77 }
78
RegisterHostObjectURI(const nsACString & aURI)79 void nsIGlobalObject::RegisterHostObjectURI(const nsACString& aURI) {
80 MOZ_ASSERT(!mHostObjectURIs.Contains(aURI));
81 mHostObjectURIs.AppendElement(aURI);
82 }
83
UnregisterHostObjectURI(const nsACString & aURI)84 void nsIGlobalObject::UnregisterHostObjectURI(const nsACString& aURI) {
85 mHostObjectURIs.RemoveElement(aURI);
86 }
87
88 namespace {
89
90 class UnlinkHostObjectURIsRunnable final : public mozilla::Runnable {
91 public:
UnlinkHostObjectURIsRunnable(nsTArray<nsCString> && aURIs)92 explicit UnlinkHostObjectURIsRunnable(nsTArray<nsCString>&& aURIs)
93 : mozilla::Runnable("UnlinkHostObjectURIsRunnable"),
94 mURIs(std::move(aURIs)) {}
95
Run()96 NS_IMETHOD Run() override {
97 MOZ_ASSERT(NS_IsMainThread());
98
99 for (uint32_t index = 0; index < mURIs.Length(); ++index) {
100 BlobURLProtocolHandler::RemoveDataEntry(mURIs[index]);
101 }
102
103 return NS_OK;
104 }
105
106 private:
107 ~UnlinkHostObjectURIsRunnable() = default;
108
109 const nsTArray<nsCString> mURIs;
110 };
111
112 } // namespace
113
UnlinkObjectsInGlobal()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]);
120 }
121
122 mHostObjectURIs.Clear();
123 } else {
124 RefPtr<UnlinkHostObjectURIsRunnable> runnable =
125 new UnlinkHostObjectURIsRunnable(std::move(mHostObjectURIs));
126 MOZ_ASSERT(mHostObjectURIs.IsEmpty());
127
128 nsresult rv = NS_DispatchToMainThread(runnable);
129 if (NS_FAILED(rv)) {
130 NS_WARNING("Failed to dispatch a runnable to the main-thread.");
131 }
132 }
133 }
134
135 mReportRecords.Clear();
136 mReportingObservers.Clear();
137 #ifdef MOZ_DOM_STREAMS
138 mCountQueuingStrategySizeFunction = nullptr;
139 mByteLengthQueuingStrategySizeFunction = nullptr;
140 #endif
141 }
142
TraverseObjectsInGlobal(nsCycleCollectionTraversalCallback & cb)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);
150 }
151 }
152
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
160 }
161
AddEventTargetObject(DOMEventTargetHelper * aObject)162 void nsIGlobalObject::AddEventTargetObject(DOMEventTargetHelper* aObject) {
163 MOZ_DIAGNOSTIC_ASSERT(aObject);
164 MOZ_ASSERT(!aObject->isInList());
165 mEventTargetObjects.insertBack(aObject);
166 }
167
RemoveEventTargetObject(DOMEventTargetHelper * 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();
173 }
174
ForEachEventTargetObject(const std::function<void (DOMEventTargetHelper *,bool * aDoneOut)> & aFunc) const175 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));
185 }
186
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;
194 }
195 aFunc(target, &done);
196 if (done) {
197 break;
198 }
199 }
200 }
201
DisconnectEventTargetObjects()202 void nsIGlobalObject::DisconnectEventTargetObjects() {
203 ForEachEventTargetObject([&](DOMEventTargetHelper* aTarget, bool* aDoneOut) {
204 aTarget->DisconnectFromOwner();
205
206 // Calling DisconnectFromOwner() should result in
207 // RemoveEventTargetObject() being called.
208 MOZ_DIAGNOSTIC_ASSERT(aTarget->GetOwnerGlobal() != this);
209 });
210 }
211
GetClientInfo() const212 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>();
216 }
217
GetAgentClusterId() const218 Maybe<nsID> nsIGlobalObject::GetAgentClusterId() const {
219 Maybe<ClientInfo> ci = GetClientInfo();
220 if (ci.isSome()) {
221 return ci.value().AgentClusterId();
222 }
223 return mozilla::Nothing();
224 }
225
GetController() const226 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>();
230 }
231
GetOrCreateServiceWorker(const ServiceWorkerDescriptor & aDescriptor)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;
237 }
238
GetServiceWorkerRegistration(const mozilla::dom::ServiceWorkerRegistrationDescriptor & aDescriptor) const239 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;
245 }
246
247 RefPtr<ServiceWorkerRegistration>
GetOrCreateServiceWorkerRegistration(const ServiceWorkerRegistrationDescriptor & aDescriptor)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;
253 }
254
GetStorageAccess()255 mozilla::StorageAccess nsIGlobalObject::GetStorageAccess() {
256 return mozilla::StorageAccess::eDeny;
257 }
258
AsInnerWindow()259 nsPIDOMWindowInner* nsIGlobalObject::AsInnerWindow() {
260 if (MOZ_LIKELY(mIsInnerWindow)) {
261 return static_cast<nsPIDOMWindowInner*>(
262 static_cast<nsGlobalWindowInner*>(this));
263 }
264 return nullptr;
265 }
266
ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const267 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const {
268 size_t rtn = mHostObjectURIs.ShallowSizeOfExcludingThis(aSizeOf);
269 return rtn;
270 }
271
272 class QueuedMicrotask : public MicroTaskRunnable {
273 public:
QueuedMicrotask(nsIGlobalObject * aGlobal,VoidFunction & aCallback)274 QueuedMicrotask(nsIGlobalObject* aGlobal, VoidFunction& aCallback)
275 : mGlobal(aGlobal), mCallback(&aCallback) {}
276
Run(AutoSlowOperation & aAso)277 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Run(AutoSlowOperation& aAso) final {
278 IgnoredErrorResult rv;
279 MOZ_KnownLive(mCallback)->Call(static_cast<ErrorResult&>(rv));
280 }
281
Suppressed()282 bool Suppressed() final { return mGlobal->IsInSyncOperation(); }
283
284 private:
285 nsCOMPtr<nsIGlobalObject> mGlobal;
286 RefPtr<VoidFunction> mCallback;
287 };
288
QueueMicrotask(VoidFunction & aCallback)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());
294 }
295 }
296
RegisterReportingObserver(ReportingObserver * aObserver,bool aBuffered)297 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver* aObserver,
298 bool aBuffered) {
299 MOZ_ASSERT(aObserver);
300
301 if (mReportingObservers.Contains(aObserver)) {
302 return;
303 }
304
305 if (NS_WARN_IF(
306 !mReportingObservers.AppendElement(aObserver, mozilla::fallible))) {
307 return;
308 }
309
310 if (!aBuffered) {
311 return;
312 }
313
314 for (Report* report : mReportRecords) {
315 aObserver->MaybeReport(report);
316 }
317 }
318
UnregisterReportingObserver(ReportingObserver * aObserver)319 void nsIGlobalObject::UnregisterReportingObserver(
320 ReportingObserver* aObserver) {
321 MOZ_ASSERT(aObserver);
322 mReportingObservers.RemoveElement(aObserver);
323 }
324
BroadcastReport(Report * aReport)325 void nsIGlobalObject::BroadcastReport(Report* aReport) {
326 MOZ_ASSERT(aReport);
327
328 for (ReportingObserver* observer : mReportingObservers) {
329 observer->MaybeReport(aReport);
330 }
331
332 if (NS_WARN_IF(!mReportRecords.AppendElement(aReport, mozilla::fallible))) {
333 return;
334 }
335
336 while (mReportRecords.Length() > MAX_REPORT_RECORDS) {
337 mReportRecords.RemoveElementAt(0);
338 }
339 }
340
NotifyReportingObservers()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.
345 //
346 // This can go away once
347 // https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
348 MOZ_KnownLive(observer)->MaybeNotify();
349 }
350 }
351
RemoveReportRecords()352 void nsIGlobalObject::RemoveReportRecords() {
353 mReportRecords.Clear();
354
355 for (auto& observer : mReportingObservers) {
356 observer->ForgetReports();
357 }
358 }
359
360 #ifdef MOZ_DOM_STREAMS
361 already_AddRefed<mozilla::dom::Function>
GetCountQueuingStrategySizeFunction()362 nsIGlobalObject::GetCountQueuingStrategySizeFunction() {
363 return do_AddRef(mCountQueuingStrategySizeFunction);
364 }
365
SetCountQueuingStrategySizeFunction(mozilla::dom::Function * aFunction)366 void nsIGlobalObject::SetCountQueuingStrategySizeFunction(
367 mozilla::dom::Function* aFunction) {
368 mCountQueuingStrategySizeFunction = aFunction;
369 }
370
371 already_AddRefed<mozilla::dom::Function>
GetByteLengthQueuingStrategySizeFunction()372 nsIGlobalObject::GetByteLengthQueuingStrategySizeFunction() {
373 return do_AddRef(mByteLengthQueuingStrategySizeFunction);
374 }
375
SetByteLengthQueuingStrategySizeFunction(mozilla::dom::Function * aFunction)376 void nsIGlobalObject::SetByteLengthQueuingStrategySizeFunction(
377 mozilla::dom::Function* aFunction) {
378 mByteLengthQueuingStrategySizeFunction = aFunction;
379 }
380 #endif
381
ShouldResistFingerprinting() const382 bool nsIGlobalObject::ShouldResistFingerprinting() const {
383 return nsContentUtils::ShouldResistFingerprinting();
384 }
385