Bug 1860492 - Change file name in test @ toolkit/components/antitracking/test/browser...
[gecko.git] / xpcom / ds / nsObserverService.cpp
blob882d86747437bb81510ce30c4b7ae56559e85117
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 "mozilla/Logging.h"
8 #include "nsComponentManagerUtils.h"
9 #include "nsContentUtils.h"
10 #include "nsIConsoleService.h"
11 #include "nsIObserverService.h"
12 #include "nsIObserver.h"
13 #include "nsIScriptError.h"
14 #include "nsObserverService.h"
15 #include "nsObserverList.h"
16 #include "nsServiceManagerUtils.h"
17 #include "nsThreadUtils.h"
18 #include "nsEnumeratorUtils.h"
19 #include "xpcpublic.h"
20 #include "mozilla/AppShutdown.h"
21 #include "mozilla/net/NeckoCommon.h"
22 #include "mozilla/ProfilerLabels.h"
23 #include "mozilla/ProfilerMarkers.h"
24 #include "mozilla/ResultExtensions.h"
25 #include "mozilla/Telemetry.h"
26 #include "mozilla/TimeStamp.h"
27 #include "mozilla/Try.h"
28 #include "nsString.h"
30 // Log module for nsObserverService logging...
32 // To enable logging (see prlog.h for full details):
34 // set MOZ_LOG=ObserverService:5
35 // set MOZ_LOG_FILE=service.log
37 // This enables LogLevel::Debug level information and places all output in
38 // the file service.log.
39 static mozilla::LazyLogModule sObserverServiceLog("ObserverService");
40 #define LOG(x) MOZ_LOG(sObserverServiceLog, mozilla::LogLevel::Debug, x)
42 using namespace mozilla;
44 NS_IMETHODIMP
45 nsObserverService::CollectReports(nsIHandleReportCallback* aHandleReport,
46 nsISupports* aData, bool aAnonymize) {
47 struct SuspectObserver {
48 SuspectObserver(const char* aTopic, size_t aReferentCount)
49 : mTopic(aTopic), mReferentCount(aReferentCount) {}
50 const char* mTopic;
51 size_t mReferentCount;
54 size_t totalNumStrong = 0;
55 size_t totalNumWeakAlive = 0;
56 size_t totalNumWeakDead = 0;
57 nsTArray<SuspectObserver> suspectObservers;
59 for (auto iter = mObserverTopicTable.Iter(); !iter.Done(); iter.Next()) {
60 nsObserverList* observerList = iter.Get();
61 if (!observerList) {
62 continue;
65 size_t topicNumStrong = 0;
66 size_t topicNumWeakAlive = 0;
67 size_t topicNumWeakDead = 0;
69 nsMaybeWeakPtrArray<nsIObserver>& observers = observerList->mObservers;
70 for (uint32_t i = 0; i < observers.Length(); i++) {
71 if (observers[i].IsWeak()) {
72 nsCOMPtr<nsIObserver> ref = observers[i].GetValue();
73 if (ref) {
74 topicNumWeakAlive++;
75 } else {
76 topicNumWeakDead++;
78 } else {
79 topicNumStrong++;
83 totalNumStrong += topicNumStrong;
84 totalNumWeakAlive += topicNumWeakAlive;
85 totalNumWeakDead += topicNumWeakDead;
87 // Keep track of topics that have a suspiciously large number
88 // of referents (symptom of leaks).
89 size_t topicTotal = topicNumStrong + topicNumWeakAlive + topicNumWeakDead;
90 if (topicTotal > kSuspectReferentCount) {
91 SuspectObserver suspect(observerList->GetKey(), topicTotal);
92 suspectObservers.AppendElement(suspect);
96 // These aren't privacy-sensitive and so don't need anonymizing.
97 for (uint32_t i = 0; i < suspectObservers.Length(); i++) {
98 SuspectObserver& suspect = suspectObservers[i];
99 nsPrintfCString suspectPath("observer-service-suspect/referent(topic=%s)",
100 suspect.mTopic);
101 aHandleReport->Callback(
102 /* process */ ""_ns, suspectPath, KIND_OTHER, UNITS_COUNT,
103 suspect.mReferentCount,
104 nsLiteralCString("A topic with a suspiciously large number of "
105 "referents. This may be symptomatic of a leak "
106 "if the number of referents is high with "
107 "respect to the number of windows."),
108 aData);
111 MOZ_COLLECT_REPORT(
112 "observer-service/referent/strong", KIND_OTHER, UNITS_COUNT,
113 totalNumStrong,
114 "The number of strong references held by the observer service.");
116 MOZ_COLLECT_REPORT(
117 "observer-service/referent/weak/alive", KIND_OTHER, UNITS_COUNT,
118 totalNumWeakAlive,
119 "The number of weak references held by the observer service that are "
120 "still alive.");
122 MOZ_COLLECT_REPORT(
123 "observer-service/referent/weak/dead", KIND_OTHER, UNITS_COUNT,
124 totalNumWeakDead,
125 "The number of weak references held by the observer service that are "
126 "dead.");
128 return NS_OK;
131 ////////////////////////////////////////////////////////////////////////////////
132 // nsObserverService Implementation
134 NS_IMPL_ISUPPORTS(nsObserverService, nsIObserverService, nsObserverService,
135 nsIMemoryReporter)
137 nsObserverService::nsObserverService() : mShuttingDown(false) {}
139 nsObserverService::~nsObserverService(void) { Shutdown(); }
141 void nsObserverService::RegisterReporter() { RegisterWeakMemoryReporter(this); }
143 void nsObserverService::Shutdown() {
144 if (mShuttingDown) {
145 return;
148 mShuttingDown = true;
149 UnregisterWeakMemoryReporter(this);
150 mObserverTopicTable.Clear();
153 nsresult nsObserverService::Create(const nsIID& aIID, void** aInstancePtr) {
154 LOG(("nsObserverService::Create()"));
156 RefPtr<nsObserverService> os = new nsObserverService();
158 // The memory reporter can not be immediately registered here because
159 // the nsMemoryReporterManager may attempt to get the nsObserverService
160 // during initialization, causing a recursive GetService.
161 NS_DispatchToCurrentThread(
162 NewRunnableMethod("nsObserverService::RegisterReporter", os,
163 &nsObserverService::RegisterReporter));
165 return os->QueryInterface(aIID, aInstancePtr);
168 nsresult nsObserverService::EnsureValidCall() const {
169 if (!NS_IsMainThread()) {
170 MOZ_CRASH("Using observer service off the main thread!");
171 return NS_ERROR_UNEXPECTED;
174 if (mShuttingDown) {
175 NS_ERROR("Using observer service after XPCOM shutdown!");
176 return NS_ERROR_ILLEGAL_DURING_SHUTDOWN;
179 return NS_OK;
182 nsresult nsObserverService::FilterHttpOnTopics(const char* aTopic) {
183 // Specifically allow some http-on-* observer notifications in the child
184 // process.
185 if (mozilla::net::IsNeckoChild() && !strncmp(aTopic, "http-on-", 8) &&
186 strcmp(aTopic, "http-on-before-stop-request") &&
187 strcmp(aTopic, "http-on-failed-opening-request") &&
188 strcmp(aTopic, "http-on-image-cache-response") &&
189 strcmp(aTopic, "http-on-opening-request") &&
190 strcmp(aTopic, "http-on-stop-request")) {
191 nsCOMPtr<nsIConsoleService> console(
192 do_GetService(NS_CONSOLESERVICE_CONTRACTID));
193 nsCOMPtr<nsIScriptError> error(
194 do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
195 error->Init(u"http-on-* observers only work in the parent process"_ns,
196 u""_ns, u""_ns, 0, 0, nsIScriptError::warningFlag,
197 "chrome javascript"_ns, false /* from private window */,
198 true /* from chrome context */);
199 console->LogMessage(error);
201 return NS_ERROR_NOT_IMPLEMENTED;
204 return NS_OK;
207 NS_IMETHODIMP
208 nsObserverService::AddObserver(nsIObserver* aObserver, const char* aTopic,
209 bool aOwnsWeak) {
210 LOG(("nsObserverService::AddObserver(%p: %s, %s)", (void*)aObserver, aTopic,
211 aOwnsWeak ? "weak" : "strong"));
213 MOZ_TRY(EnsureValidCall());
214 if (NS_WARN_IF(!aObserver) || NS_WARN_IF(!aTopic)) {
215 return NS_ERROR_INVALID_ARG;
218 MOZ_TRY(FilterHttpOnTopics(aTopic));
220 nsObserverList* observerList = mObserverTopicTable.PutEntry(aTopic);
221 if (!observerList) {
222 return NS_ERROR_OUT_OF_MEMORY;
225 return observerList->AddObserver(aObserver, aOwnsWeak);
228 NS_IMETHODIMP
229 nsObserverService::RemoveObserver(nsIObserver* aObserver, const char* aTopic) {
230 LOG(("nsObserverService::RemoveObserver(%p: %s)", (void*)aObserver, aTopic));
232 if (mShuttingDown) {
233 // The service is shutting down. Let's ignore this call.
234 return NS_OK;
237 MOZ_TRY(EnsureValidCall());
238 if (NS_WARN_IF(!aObserver) || NS_WARN_IF(!aTopic)) {
239 return NS_ERROR_INVALID_ARG;
242 nsObserverList* observerList = mObserverTopicTable.GetEntry(aTopic);
243 if (!observerList) {
244 return NS_ERROR_FAILURE;
247 return observerList->RemoveObserver(aObserver);
250 NS_IMETHODIMP
251 nsObserverService::EnumerateObservers(const char* aTopic,
252 nsISimpleEnumerator** anEnumerator) {
253 LOG(("nsObserverService::EnumerateObservers(%s)", aTopic));
255 MOZ_TRY(EnsureValidCall());
256 if (NS_WARN_IF(!anEnumerator) || NS_WARN_IF(!aTopic)) {
257 return NS_ERROR_INVALID_ARG;
260 nsObserverList* observerList = mObserverTopicTable.GetEntry(aTopic);
261 if (!observerList) {
262 return NS_NewEmptyEnumerator(anEnumerator);
265 observerList->GetObserverList(anEnumerator);
266 return NS_OK;
269 // Enumerate observers of aTopic and call Observe on each.
270 NS_IMETHODIMP nsObserverService::NotifyObservers(nsISupports* aSubject,
271 const char* aTopic,
272 const char16_t* aSomeData) {
273 LOG(("nsObserverService::NotifyObservers(%s)", aTopic));
275 MOZ_TRY(EnsureValidCall());
276 if (NS_WARN_IF(!aTopic)) {
277 return NS_ERROR_INVALID_ARG;
280 MOZ_ASSERT(AppShutdown::IsNoOrLegalShutdownTopic(aTopic));
282 AUTO_PROFILER_MARKER_TEXT("NotifyObservers", OTHER, MarkerStack::Capture(),
283 nsDependentCString(aTopic));
284 AUTO_PROFILER_LABEL_DYNAMIC_CSTR_NONSENSITIVE(
285 "nsObserverService::NotifyObservers", OTHER, aTopic);
287 nsObserverList* observerList = mObserverTopicTable.GetEntry(aTopic);
288 if (observerList) {
289 observerList->NotifyObservers(aSubject, aTopic, aSomeData);
292 return NS_OK;
295 NS_IMETHODIMP
296 nsObserverService::UnmarkGrayStrongObservers() {
297 MOZ_TRY(EnsureValidCall());
299 nsCOMArray<nsIObserver> strongObservers;
300 for (auto iter = mObserverTopicTable.Iter(); !iter.Done(); iter.Next()) {
301 nsObserverList* aObserverList = iter.Get();
302 if (aObserverList) {
303 aObserverList->AppendStrongObservers(strongObservers);
307 for (uint32_t i = 0; i < strongObservers.Length(); ++i) {
308 xpc_TryUnmarkWrappedGrayObject(strongObservers[i]);
311 return NS_OK;
314 bool nsObserverService::HasObservers(const char* aTopic) {
315 return mObserverTopicTable.Contains(aTopic);
318 namespace {
320 class NotifyWhenScriptSafeRunnable : public mozilla::Runnable {
321 public:
322 NotifyWhenScriptSafeRunnable(nsIObserverService* aObs, nsISupports* aSubject,
323 const char* aTopic, const char16_t* aData)
324 : mozilla::Runnable("NotifyWhenScriptSafeRunnable"),
325 mObs(aObs),
326 mSubject(aSubject),
327 mTopic(aTopic) {
328 if (aData) {
329 mData.Assign(aData);
330 } else {
331 mData.SetIsVoid(true);
335 NS_IMETHOD Run() override {
336 const char16_t* data = mData.IsVoid() ? nullptr : mData.get();
337 return mObs->NotifyObservers(mSubject, mTopic.get(), data);
340 private:
341 nsCOMPtr<nsIObserverService> mObs;
342 nsCOMPtr<nsISupports> mSubject;
343 nsCString mTopic;
344 nsString mData;
347 } // namespace
349 nsresult nsIObserverService::NotifyWhenScriptSafe(nsISupports* aSubject,
350 const char* aTopic,
351 const char16_t* aData) {
352 if (nsContentUtils::IsSafeToRunScript()) {
353 return NotifyObservers(aSubject, aTopic, aData);
356 nsContentUtils::AddScriptRunner(MakeAndAddRef<NotifyWhenScriptSafeRunnable>(
357 this, aSubject, aTopic, aData));
358 return NS_OK;