summaryrefslogtreecommitdiffstats
path: root/xpcom/base/AvailableMemoryWatcher.cpp
blob: 44e0f7d2206e858d1fa6366898658824b93dd31d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "AvailableMemoryWatcher.h"

#include "mozilla/ClearOnShutdown.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Services.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/Telemetry.h"
#include "nsExceptionHandler.h"
#include "nsMemoryPressure.h"
#include "nsXULAppAPI.h"

namespace mozilla {

// Use this class as the initial value of
// nsAvailableMemoryWatcherBase::mCallback until RegisterCallback() is called
// so that nsAvailableMemoryWatcherBase does not have to check if its callback
// object is valid or not.
class NullTabUnloader final : public nsITabUnloader {
  ~NullTabUnloader() = default;

 public:
  NullTabUnloader() = default;

  NS_DECL_ISUPPORTS
  NS_DECL_NSITABUNLOADER
};

NS_IMPL_ISUPPORTS(NullTabUnloader, nsITabUnloader)

NS_IMETHODIMP NullTabUnloader::UnloadTabAsync() {
  return NS_ERROR_NOT_IMPLEMENTED;
}

StaticRefPtr<nsAvailableMemoryWatcherBase>
    nsAvailableMemoryWatcherBase::sSingleton;

/*static*/
already_AddRefed<nsAvailableMemoryWatcherBase>
nsAvailableMemoryWatcherBase::GetSingleton() {
  if (!sSingleton) {
    sSingleton = CreateAvailableMemoryWatcher();
    ClearOnShutdown(&sSingleton);
  }

  return do_AddRef(sSingleton);
}

NS_IMPL_ISUPPORTS(nsAvailableMemoryWatcherBase, nsIAvailableMemoryWatcherBase);

nsAvailableMemoryWatcherBase::nsAvailableMemoryWatcherBase()
    : mNumOfTabUnloading(0),
      mNumOfMemoryPressure(0),
      mTabUnloader(new NullTabUnloader),
      mInteracting(false) {
  MOZ_ASSERT(XRE_IsParentProcess(),
             "Watching memory only in the main process.");
}

const char* const nsAvailableMemoryWatcherBase::kObserverTopics[] = {
    // Use this shutdown phase to make sure the instance is destroyed in GTest
    "xpcom-shutdown",
    "user-interaction-active",
    "user-interaction-inactive",
};

nsresult nsAvailableMemoryWatcherBase::Init() {
  MOZ_ASSERT(NS_IsMainThread(),
             "nsAvailableMemoryWatcherBase needs to be initialized "
             "in the main thread.");

  if (mObserverSvc) {
    return NS_ERROR_ALREADY_INITIALIZED;
  }

  mObserverSvc = services::GetObserverService();
  MOZ_ASSERT(mObserverSvc);

  for (auto topic : kObserverTopics) {
    nsresult rv = mObserverSvc->AddObserver(this, topic,
                                            /* ownsWeak */ false);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
}

void nsAvailableMemoryWatcherBase::Shutdown() {
  for (auto topic : kObserverTopics) {
    mObserverSvc->RemoveObserver(this, topic);
  }
}

NS_IMETHODIMP
nsAvailableMemoryWatcherBase::Observe(nsISupports* aSubject, const char* aTopic,
                                      const char16_t* aData) {
  MOZ_ASSERT(NS_IsMainThread());

  if (strcmp(aTopic, "xpcom-shutdown") == 0) {
    Shutdown();
  } else if (strcmp(aTopic, "user-interaction-inactive") == 0) {
    mInteracting = false;
#ifdef MOZ_CRASHREPORTER
    CrashReporter::SetInactiveStateStart();
#endif
  } else if (strcmp(aTopic, "user-interaction-active") == 0) {
    mInteracting = true;
#ifdef MOZ_CRASHREPORTER
    CrashReporter::ClearInactiveStateStart();
#endif
  }
  return NS_OK;
}

nsresult nsAvailableMemoryWatcherBase::RegisterTabUnloader(
    nsITabUnloader* aTabUnloader) {
  mTabUnloader = aTabUnloader;
  return NS_OK;
}

nsresult nsAvailableMemoryWatcherBase::OnUnloadAttemptCompleted(
    nsresult aResult) {
  switch (aResult) {
    // A tab was unloaded successfully.
    case NS_OK:
      ++mNumOfTabUnloading;
      break;

    // There was no unloadable tab.
    case NS_ERROR_NOT_AVAILABLE:
      ++mNumOfMemoryPressure;
      NS_NotifyOfEventualMemoryPressure(MemoryPressureState::LowMemory);
      break;

    // There was a pending task to unload a tab.
    case NS_ERROR_ABORT:
      break;

    default:
      MOZ_ASSERT_UNREACHABLE("Unexpected aResult");
      break;
  }
  return NS_OK;
}

void nsAvailableMemoryWatcherBase::UpdateLowMemoryTimeStamp() {
  if (mLowMemoryStart.IsNull()) {
    mLowMemoryStart = TimeStamp::NowLoRes();
  }
}

void nsAvailableMemoryWatcherBase::RecordTelemetryEventOnHighMemory() {
  Telemetry::SetEventRecordingEnabled("memory_watcher"_ns, true);
  Telemetry::RecordEvent(
      Telemetry::EventID::Memory_watcher_OnHighMemory_Stats,
      Some(nsPrintfCString(
          "%u,%u,%f", mNumOfTabUnloading, mNumOfMemoryPressure,
          (TimeStamp::NowLoRes() - mLowMemoryStart).ToSeconds())),
      Nothing());
  mNumOfTabUnloading = mNumOfMemoryPressure = 0;
  mLowMemoryStart = TimeStamp();
}

// Define the fallback method for a platform for which a platform-specific
// CreateAvailableMemoryWatcher() is not defined.
#if defined(ANDROID) || \
    !defined(XP_WIN) && !defined(XP_DARWIN) && !defined(XP_LINUX)
already_AddRefed<nsAvailableMemoryWatcherBase> CreateAvailableMemoryWatcher() {
  RefPtr instance(new nsAvailableMemoryWatcherBase);
  return do_AddRef(instance);
}
#endif

}  // namespace mozilla