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/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"
18 
19 // Max number of Report objects
20 constexpr auto MAX_REPORT_RECORDS = 100;
21 
22 using mozilla::AutoSlowOperation;
23 using mozilla::CycleCollectedJSContext;
24 using mozilla::DOMEventTargetHelper;
25 using mozilla::ErrorResult;
26 using mozilla::IgnoredErrorResult;
27 using mozilla::MallocSizeOf;
28 using mozilla::Maybe;
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;
39 
nsIGlobalObject()40 nsIGlobalObject::nsIGlobalObject()
41     : mIsDying(false), mIsScriptForbidden(false), mIsInnerWindow(false) {}
42 
IsScriptForbidden(JSObject * aCallback,bool aIsJSImplementedWebIDL) const43 bool nsIGlobalObject::IsScriptForbidden(JSObject* aCallback,
44                                         bool aIsJSImplementedWebIDL) const {
45   if (mIsScriptForbidden || mIsDying) {
46     return true;
47   }
48 
49   if (NS_IsMainThread()) {
50     if (aIsJSImplementedWebIDL) {
51       return false;
52     }
53     if (!xpc::Scriptability::Get(aCallback).Allowed()) {
54       return true;
55     }
56   }
57 
58   return false;
59 }
60 
~nsIGlobalObject()61 nsIGlobalObject::~nsIGlobalObject() {
62   UnlinkObjectsInGlobal();
63   DisconnectEventTargetObjects();
64   MOZ_DIAGNOSTIC_ASSERT(mEventTargetObjects.isEmpty());
65 }
66 
PrincipalOrNull()67 nsIPrincipal* nsIGlobalObject::PrincipalOrNull() {
68   if (!NS_IsMainThread()) {
69     return nullptr;
70   }
71 
72   JSObject* global = GetGlobalJSObjectPreserveColor();
73   if (NS_WARN_IF(!global)) return nullptr;
74 
75   return nsContentUtils::ObjectPrincipal(global);
76 }
77 
RegisterHostObjectURI(const nsACString & aURI)78 void nsIGlobalObject::RegisterHostObjectURI(const nsACString& aURI) {
79   MOZ_ASSERT(!mHostObjectURIs.Contains(aURI));
80   mHostObjectURIs.AppendElement(aURI);
81 }
82 
UnregisterHostObjectURI(const nsACString & aURI)83 void nsIGlobalObject::UnregisterHostObjectURI(const nsACString& aURI) {
84   mHostObjectURIs.RemoveElement(aURI);
85 }
86 
87 namespace {
88 
89 class UnlinkHostObjectURIsRunnable final : public mozilla::Runnable {
90  public:
UnlinkHostObjectURIsRunnable(nsTArray<nsCString> && aURIs)91   explicit UnlinkHostObjectURIsRunnable(nsTArray<nsCString>&& aURIs)
92       : mozilla::Runnable("UnlinkHostObjectURIsRunnable"),
93         mURIs(std::move(aURIs)) {}
94 
Run()95   NS_IMETHOD Run() override {
96     MOZ_ASSERT(NS_IsMainThread());
97 
98     for (uint32_t index = 0; index < mURIs.Length(); ++index) {
99       BlobURLProtocolHandler::RemoveDataEntry(mURIs[index]);
100     }
101 
102     return NS_OK;
103   }
104 
105  private:
106   ~UnlinkHostObjectURIsRunnable() = default;
107 
108   const nsTArray<nsCString> mURIs;
109 };
110 
111 }  // namespace
112 
UnlinkObjectsInGlobal()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]);
119       }
120 
121       mHostObjectURIs.Clear();
122     } else {
123       RefPtr<UnlinkHostObjectURIsRunnable> runnable =
124           new UnlinkHostObjectURIsRunnable(std::move(mHostObjectURIs));
125       MOZ_ASSERT(mHostObjectURIs.IsEmpty());
126 
127       nsresult rv = NS_DispatchToMainThread(runnable);
128       if (NS_FAILED(rv)) {
129         NS_WARNING("Failed to dispatch a runnable to the main-thread.");
130       }
131     }
132   }
133 
134   mReportRecords.Clear();
135   mReportingObservers.Clear();
136 }
137 
TraverseObjectsInGlobal(nsCycleCollectionTraversalCallback & cb)138 void nsIGlobalObject::TraverseObjectsInGlobal(
139     nsCycleCollectionTraversalCallback& cb) {
140   // Currently we only store BlobImpl objects off the the main-thread and they
141   // are not CCed.
142   if (!mHostObjectURIs.IsEmpty() && NS_IsMainThread()) {
143     for (uint32_t index = 0; index < mHostObjectURIs.Length(); ++index) {
144       BlobURLProtocolHandler::Traverse(mHostObjectURIs[index], cb);
145     }
146   }
147 
148   nsIGlobalObject* tmp = this;
149   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportRecords)
150   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportingObservers)
151 }
152 
AddEventTargetObject(DOMEventTargetHelper * aObject)153 void nsIGlobalObject::AddEventTargetObject(DOMEventTargetHelper* aObject) {
154   MOZ_DIAGNOSTIC_ASSERT(aObject);
155   MOZ_ASSERT(!aObject->isInList());
156   mEventTargetObjects.insertBack(aObject);
157 }
158 
RemoveEventTargetObject(DOMEventTargetHelper * aObject)159 void nsIGlobalObject::RemoveEventTargetObject(DOMEventTargetHelper* aObject) {
160   MOZ_DIAGNOSTIC_ASSERT(aObject);
161   MOZ_ASSERT(aObject->isInList());
162   MOZ_ASSERT(aObject->GetOwnerGlobal() == this);
163   aObject->remove();
164 }
165 
ForEachEventTargetObject(const std::function<void (DOMEventTargetHelper *,bool * aDoneOut)> & aFunc) const166 void nsIGlobalObject::ForEachEventTargetObject(
167     const std::function<void(DOMEventTargetHelper*, bool* aDoneOut)>& aFunc)
168     const {
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
171   // list.
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));
176   }
177 
178   // Iterate the target list and call the function on each one.
179   bool done = false;
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) {
184       continue;
185     }
186     aFunc(target, &done);
187     if (done) {
188       break;
189     }
190   }
191 }
192 
DisconnectEventTargetObjects()193 void nsIGlobalObject::DisconnectEventTargetObjects() {
194   ForEachEventTargetObject([&](DOMEventTargetHelper* aTarget, bool* aDoneOut) {
195     aTarget->DisconnectFromOwner();
196 
197     // Calling DisconnectFromOwner() should result in
198     // RemoveEventTargetObject() being called.
199     MOZ_DIAGNOSTIC_ASSERT(aTarget->GetOwnerGlobal() != this);
200   });
201 }
202 
GetClientInfo() const203 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>();
207 }
208 
GetAgentClusterId() const209 Maybe<nsID> nsIGlobalObject::GetAgentClusterId() const {
210   Maybe<ClientInfo> ci = GetClientInfo();
211   if (ci.isSome()) {
212     return ci.value().AgentClusterId();
213   }
214   return mozilla::Nothing();
215 }
216 
GetController() const217 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>();
221 }
222 
GetOrCreateServiceWorker(const ServiceWorkerDescriptor & aDescriptor)223 RefPtr<ServiceWorker> nsIGlobalObject::GetOrCreateServiceWorker(
224     const ServiceWorkerDescriptor& aDescriptor) {
225   MOZ_DIAGNOSTIC_ASSERT(false,
226                         "this global should not have any service workers");
227   return nullptr;
228 }
229 
GetServiceWorkerRegistration(const mozilla::dom::ServiceWorkerRegistrationDescriptor & aDescriptor) const230 RefPtr<ServiceWorkerRegistration> nsIGlobalObject::GetServiceWorkerRegistration(
231     const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
232     const {
233   MOZ_DIAGNOSTIC_ASSERT(false,
234                         "this global should not have any service workers");
235   return nullptr;
236 }
237 
238 RefPtr<ServiceWorkerRegistration>
GetOrCreateServiceWorkerRegistration(const ServiceWorkerRegistrationDescriptor & aDescriptor)239 nsIGlobalObject::GetOrCreateServiceWorkerRegistration(
240     const ServiceWorkerRegistrationDescriptor& aDescriptor) {
241   MOZ_DIAGNOSTIC_ASSERT(
242       false, "this global should not have any service worker registrations");
243   return nullptr;
244 }
245 
AsInnerWindow()246 nsPIDOMWindowInner* nsIGlobalObject::AsInnerWindow() {
247   if (MOZ_LIKELY(mIsInnerWindow)) {
248     return static_cast<nsPIDOMWindowInner*>(
249         static_cast<nsGlobalWindowInner*>(this));
250   }
251   return nullptr;
252 }
253 
ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const254 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const {
255   size_t rtn = mHostObjectURIs.ShallowSizeOfExcludingThis(aSizeOf);
256   return rtn;
257 }
258 
259 class QueuedMicrotask : public MicroTaskRunnable {
260  public:
QueuedMicrotask(nsIGlobalObject * aGlobal,VoidFunction & aCallback)261   QueuedMicrotask(nsIGlobalObject* aGlobal, VoidFunction& aCallback)
262       : mGlobal(aGlobal), mCallback(&aCallback) {}
263 
Run(AutoSlowOperation & aAso)264   MOZ_CAN_RUN_SCRIPT_BOUNDARY void Run(AutoSlowOperation& aAso) final {
265     IgnoredErrorResult rv;
266     MOZ_KnownLive(mCallback)->Call(static_cast<ErrorResult&>(rv));
267   }
268 
Suppressed()269   bool Suppressed() final { return mGlobal->IsInSyncOperation(); }
270 
271  private:
272   nsCOMPtr<nsIGlobalObject> mGlobal;
273   RefPtr<VoidFunction> mCallback;
274 };
275 
QueueMicrotask(VoidFunction & aCallback)276 void nsIGlobalObject::QueueMicrotask(VoidFunction& aCallback) {
277   CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
278   if (context) {
279     RefPtr<MicroTaskRunnable> mt = new QueuedMicrotask(this, aCallback);
280     context->DispatchToMicroTask(mt.forget());
281   }
282 }
283 
RegisterReportingObserver(ReportingObserver * aObserver,bool aBuffered)284 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver* aObserver,
285                                                 bool aBuffered) {
286   MOZ_ASSERT(aObserver);
287 
288   if (mReportingObservers.Contains(aObserver)) {
289     return;
290   }
291 
292   if (NS_WARN_IF(
293           !mReportingObservers.AppendElement(aObserver, mozilla::fallible))) {
294     return;
295   }
296 
297   if (!aBuffered) {
298     return;
299   }
300 
301   for (Report* report : mReportRecords) {
302     aObserver->MaybeReport(report);
303   }
304 }
305 
UnregisterReportingObserver(ReportingObserver * aObserver)306 void nsIGlobalObject::UnregisterReportingObserver(
307     ReportingObserver* aObserver) {
308   MOZ_ASSERT(aObserver);
309   mReportingObservers.RemoveElement(aObserver);
310 }
311 
BroadcastReport(Report * aReport)312 void nsIGlobalObject::BroadcastReport(Report* aReport) {
313   MOZ_ASSERT(aReport);
314 
315   for (ReportingObserver* observer : mReportingObservers) {
316     observer->MaybeReport(aReport);
317   }
318 
319   if (NS_WARN_IF(!mReportRecords.AppendElement(aReport, mozilla::fallible))) {
320     return;
321   }
322 
323   while (mReportRecords.Length() > MAX_REPORT_RECORDS) {
324     mReportRecords.RemoveElementAt(0);
325   }
326 }
327 
NotifyReportingObservers()328 void nsIGlobalObject::NotifyReportingObservers() {
329   for (auto& observer : mReportingObservers.Clone()) {
330     // MOZ_KnownLive because the clone of 'mReportingObservers' is guaranteed to
331     // keep it alive.
332     //
333     // This can go away once
334     // https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
335     MOZ_KnownLive(observer)->MaybeNotify();
336   }
337 }
338 
RemoveReportRecords()339 void nsIGlobalObject::RemoveReportRecords() {
340   mReportRecords.Clear();
341 
342   for (auto& observer : mReportingObservers) {
343     observer->ForgetReports();
344   }
345 }
346