Bug 1852740: add tests for the `fetchpriority` attribute in Link headers. r=necko...
[gecko.git] / dom / base / nsIGlobalObject.cpp
blob4b93c0ec232f9286cb2d11e87cf5f87c2150dabf
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;
33 using mozilla::Maybe;
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) {
52 return true;
55 if (NS_IsMainThread()) {
56 if (aIsJSImplementedWebIDL) {
57 return false;
60 if (!xpc::Scriptability::AllowedIfExists(aCallback)) {
61 return true;
65 return false;
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);
90 namespace {
92 class UnlinkHostObjectURIsRunnable final : public mozilla::Runnable {
93 public:
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]);
105 return NS_OK;
108 private:
109 ~UnlinkHostObjectURIsRunnable() = default;
111 const nsTArray<nsCString> mURIs;
114 } // namespace
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();
125 } else {
126 RefPtr<UnlinkHostObjectURIsRunnable> runnable =
127 new UnlinkHostObjectURIsRunnable(std::move(mHostObjectURIs));
128 MOZ_ASSERT(mHostObjectURIs.IsEmpty());
130 nsresult rv = NS_DispatchToMainThread(runnable);
131 if (NS_FAILED(rv)) {
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
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);
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);
170 aObject->remove();
173 void nsIGlobalObject::ForEachEventTargetObject(
174 const std::function<void(DOMEventTargetHelper*, bool* aDoneOut)>& aFunc)
175 const {
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
178 // list.
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.
186 bool done = false;
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) {
191 continue;
193 aFunc(target, &done);
194 if (done) {
195 break;
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();
218 if (ci.isSome()) {
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");
234 return nullptr;
237 RefPtr<ServiceWorkerRegistration> nsIGlobalObject::GetServiceWorkerRegistration(
238 const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor)
239 const {
240 MOZ_DIAGNOSTIC_ASSERT(false,
241 "this global should not have any service workers");
242 return nullptr;
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");
250 return nullptr;
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));
262 return nullptr;
265 size_t nsIGlobalObject::ShallowSizeOfExcludingThis(MallocSizeOf aSizeOf) const {
266 size_t rtn = mHostObjectURIs.ShallowSizeOfExcludingThis(aSizeOf);
267 return rtn;
270 class QueuedMicrotask : public MicroTaskRunnable {
271 public:
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(); }
282 private:
283 nsCOMPtr<nsIGlobalObject> mGlobal;
284 RefPtr<VoidFunction> mCallback;
287 void nsIGlobalObject::QueueMicrotask(VoidFunction& aCallback) {
288 CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
289 if (context) {
290 RefPtr<MicroTaskRunnable> mt = new QueuedMicrotask(this, aCallback);
291 context->DispatchToMicroTask(mt.forget());
295 void nsIGlobalObject::RegisterReportingObserver(ReportingObserver* aObserver,
296 bool aBuffered) {
297 MOZ_ASSERT(aObserver);
299 if (mReportingObservers.Contains(aObserver)) {
300 return;
303 if (NS_WARN_IF(
304 !mReportingObservers.AppendElement(aObserver, mozilla::fallible))) {
305 return;
308 if (!aBuffered) {
309 return;
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) {
324 MOZ_ASSERT(aReport);
326 for (ReportingObserver* observer : mReportingObservers) {
327 observer->MaybeReport(aReport);
330 if (NS_WARN_IF(!mReportRecords.AppendElement(aReport, mozilla::fallible))) {
331 return;
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
342 // keep it alive.
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);