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) {
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.SwapElements(aURIs);
94   }
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   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(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 }
138 
TraverseObjectsInGlobal(nsCycleCollectionTraversalCallback & cb)139 void nsIGlobalObject::TraverseObjectsInGlobal(
140     nsCycleCollectionTraversalCallback& cb) {
141   // Currently we only store BlobImpl objects off the the main-thread and they
142   // are not CCed.
143   if (!mHostObjectURIs.IsEmpty() && NS_IsMainThread()) {
144     for (uint32_t index = 0; index < mHostObjectURIs.Length(); ++index) {
145       BlobURLProtocolHandler::Traverse(mHostObjectURIs[index], cb);
146     }
147   }
148 
149   nsIGlobalObject* tmp = this;
150   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportRecords)
151   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReportingObservers)
152 }
153 
AddEventTargetObject(DOMEventTargetHelper * aObject)154 void nsIGlobalObject::AddEventTargetObject(DOMEventTargetHelper* aObject) {
155   MOZ_DIAGNOSTIC_ASSERT(aObject);
156   MOZ_ASSERT(!aObject->isInList());
157   mEventTargetObjects.insertBack(aObject);
158 }
159 
RemoveEventTargetObject(DOMEventTargetHelper * aObject)160 void nsIGlobalObject::RemoveEventTargetObject(DOMEventTargetHelper* aObject) {
161   MOZ_DIAGNOSTIC_ASSERT(aObject);
162   MOZ_ASSERT(aObject->isInList());
163   MOZ_ASSERT(aObject->GetOwnerGlobal() == this);
164   aObject->remove();
165 }
166 
ForEachEventTargetObject(const std::function<void (DOMEventTargetHelper *,bool * aDoneOut)> & aFunc) const167 void nsIGlobalObject::ForEachEventTargetObject(
168     const std::function<void(DOMEventTargetHelper*, bool* aDoneOut)>& aFunc)
169     const {
170   // Protect against the function call triggering a mutation of the list
171   // while we are iterating by copying the DETH references to a temporary
172   // list.
173   AutoTArray<RefPtr<DOMEventTargetHelper>, 64> targetList;
174   for (const DOMEventTargetHelper* deth = mEventTargetObjects.getFirst(); deth;
175        deth = deth->getNext()) {
176     targetList.AppendElement(const_cast<DOMEventTargetHelper*>(deth));
177   }
178 
179   // Iterate the target list and call the function on each one.
180   bool done = false;
181   for (auto target : targetList) {
182     // Check to see if a previous iteration's callback triggered the removal
183     // of this target as a side-effect.  If it did, then just ignore it.
184     if (target->GetOwnerGlobal() != this) {
185       continue;
186     }
187     aFunc(target, &done);
188     if (done) {
189       break;
190     }
191   }
192 }
193 
DisconnectEventTargetObjects()194 void nsIGlobalObject::DisconnectEventTargetObjects() {
195   ForEachEventTargetObject([&](DOMEventTargetHelper* aTarget, bool* aDoneOut) {
196     aTarget->DisconnectFromOwner();
197 
198     // Calling DisconnectFromOwner() should result in
199     // RemoveEventTargetObject() being called.
200     MOZ_DIAGNOSTIC_ASSERT(aTarget->GetOwnerGlobal() != this);
201   });
202 }
203 
GetClientInfo() const204 Maybe<ClientInfo> nsIGlobalObject::GetClientInfo() const {
205   // By default globals do not expose themselves as a client.  Only real
206   // window and worker globals are currently considered clients.
207   return Maybe<ClientInfo>();
208 }
209 
GetAgentClusterId() const210 Maybe<nsID> nsIGlobalObject::GetAgentClusterId() const {
211   Maybe<ClientInfo> ci = GetClientInfo();
212   if (ci.isSome()) {
213     return ci.value().AgentClusterId();
214   }
215   return mozilla::Nothing();
216 }
217 
GetController() const218 Maybe<ServiceWorkerDescriptor> nsIGlobalObject::GetController() const {
219   // By default globals do not have a service worker controller.  Only real
220   // window and worker globals can currently be controlled as a client.
221   return Maybe<ServiceWorkerDescriptor>();
222 }
223 
GetOrCreateServiceWorker(const ServiceWorkerDescriptor & aDescriptor)224 RefPtr<ServiceWorker> nsIGlobalObject::GetOrCreateServiceWorker(
225     const ServiceWorkerDescriptor& aDescriptor) {
226   MOZ_DIAGNOSTIC_ASSERT(false,
227                         "this global should not have any service workers");
228   return nullptr;
229 }
230 
GetServiceWorkerRegistration(const mozilla::dom::ServiceWorkerRegistrationDescriptor & aDescriptor) const231 RefPtr<ServiceWorkerRegistration> nsIGlobalObject::GetServiceWorkerRegistration(
232     const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
233     const {
234   MOZ_DIAGNOSTIC_ASSERT(false,
235                         "this global should not have any service workers");
236   return nullptr;
237 }
238 
239 RefPtr<ServiceWorkerRegistration>
GetOrCreateServiceWorkerRegistration(const ServiceWorkerRegistrationDescriptor & aDescriptor)240 nsIGlobalObject::GetOrCreateServiceWorkerRegistration(
241     const ServiceWorkerRegistrationDescriptor& aDescriptor) {
242   MOZ_DIAGNOSTIC_ASSERT(
243       false, "this global should not have any service worker registrations");
244   return nullptr;
245 }
246 
AsInnerWindow()247 nsPIDOMWindowInner* nsIGlobalObject::AsInnerWindow() {
248   if (MOZ_LIKELY(mIsInnerWindow)) {
249     return static_cast<nsPIDOMWindowInner*>(
250         static_cast<nsGlobalWindowInner*>(this));
251   }
252   return nullptr;
253 }
254 
ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const255 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const {
256   size_t rtn = mHostObjectURIs.ShallowSizeOfExcludingThis(aSizeOf);
257   return rtn;
258 }
259 
260 class QueuedMicrotask : public MicroTaskRunnable {
261  public:
QueuedMicrotask(nsIGlobalObject * aGlobal,VoidFunction & aCallback)262   QueuedMicrotask(nsIGlobalObject* aGlobal, VoidFunction& aCallback)
263       : mGlobal(aGlobal), mCallback(&aCallback) {}
264 
Run(AutoSlowOperation & aAso)265   MOZ_CAN_RUN_SCRIPT_BOUNDARY void Run(AutoSlowOperation& aAso) final {
266     IgnoredErrorResult rv;
267     MOZ_KnownLive(mCallback)->Call(static_cast<ErrorResult&>(rv));
268   }
269 
Suppressed()270   bool Suppressed() final { return mGlobal->IsInSyncOperation(); }
271 
272  private:
273   nsCOMPtr<nsIGlobalObject> mGlobal;
274   RefPtr<VoidFunction> mCallback;
275 };
276 
QueueMicrotask(VoidFunction & aCallback)277 void nsIGlobalObject::QueueMicrotask(VoidFunction& aCallback) {
278   CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
279   if (context) {
280     RefPtr<MicroTaskRunnable> mt = new QueuedMicrotask(this, aCallback);
281     context->DispatchToMicroTask(mt.forget());
282   }
283 }
284 
RegisterReportingObserver(ReportingObserver * aObserver,bool aBuffered)285 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver* aObserver,
286                                                 bool aBuffered) {
287   MOZ_ASSERT(aObserver);
288 
289   if (mReportingObservers.Contains(aObserver)) {
290     return;
291   }
292 
293   if (NS_WARN_IF(
294           !mReportingObservers.AppendElement(aObserver, mozilla::fallible))) {
295     return;
296   }
297 
298   if (!aBuffered) {
299     return;
300   }
301 
302   for (Report* report : mReportRecords) {
303     aObserver->MaybeReport(report);
304   }
305 }
306 
UnregisterReportingObserver(ReportingObserver * aObserver)307 void nsIGlobalObject::UnregisterReportingObserver(
308     ReportingObserver* aObserver) {
309   MOZ_ASSERT(aObserver);
310   mReportingObservers.RemoveElement(aObserver);
311 }
312 
BroadcastReport(Report * aReport)313 void nsIGlobalObject::BroadcastReport(Report* aReport) {
314   MOZ_ASSERT(aReport);
315 
316   for (ReportingObserver* observer : mReportingObservers) {
317     observer->MaybeReport(aReport);
318   }
319 
320   if (NS_WARN_IF(!mReportRecords.AppendElement(aReport, mozilla::fallible))) {
321     return;
322   }
323 
324   while (mReportRecords.Length() > MAX_REPORT_RECORDS) {
325     mReportRecords.RemoveElementAt(0);
326   }
327 }
328 
NotifyReportingObservers()329 void nsIGlobalObject::NotifyReportingObservers() {
330   for (auto& observer : mReportingObservers.Clone()) {
331     // MOZ_KnownLive because the clone of 'mReportingObservers' is guaranteed to
332     // keep it alive.
333     //
334     // This can go away once
335     // https://bugzilla.mozilla.org/show_bug.cgi?id=1620312 is fixed.
336     MOZ_KnownLive(observer)->MaybeNotify();
337   }
338 }
339 
RemoveReportRecords()340 void nsIGlobalObject::RemoveReportRecords() {
341   mReportRecords.Clear();
342 
343   for (auto& observer : mReportingObservers) {
344     observer->ForgetReports();
345   }
346 }
347