File: PreallocatedProcessManager.cpp

package info (click to toggle)
firefox-esr 78.15.0esr-1~deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 3,301,296 kB
  • sloc: cpp: 5,665,905; javascript: 4,798,386; ansic: 2,878,233; python: 977,004; asm: 270,347; xml: 181,456; java: 111,756; sh: 72,926; makefile: 21,819; perl: 13,380; cs: 4,725; yacc: 4,565; objc: 3,026; pascal: 1,787; lex: 1,720; ada: 1,681; exp: 505; php: 436; lisp: 260; awk: 152; ruby: 103; csh: 80; sed: 53; sql: 45
file content (329 lines) | stat: -rw-r--r-- 10,145 bytes parent folder | download | duplicates (4)
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/* -*- 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 "mozilla/PreallocatedProcessManager.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Preferences.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/StaticPrefs_dom.h"
#include "nsIPropertyBag2.h"
#include "ProcessPriorityManager.h"
#include "nsServiceManagerUtils.h"
#include "nsIXULRuntime.h"

using namespace mozilla::hal;
using namespace mozilla::dom;

namespace mozilla {
/**
 * This singleton class implements the static methods on
 * PreallocatedProcessManager.
 */
class PreallocatedProcessManagerImpl final : public nsIObserver {
 public:
  static PreallocatedProcessManagerImpl* Singleton();

  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  // See comments on PreallocatedProcessManager for these methods.
  void AddBlocker(ContentParent* aParent);
  void RemoveBlocker(ContentParent* aParent);
  already_AddRefed<ContentParent> Take();
  bool Provide(ContentParent* aParent);
  void Erase(ContentParent* aParent);

 private:
  static const char* const kObserverTopics[];

  static mozilla::StaticRefPtr<PreallocatedProcessManagerImpl> sSingleton;

  PreallocatedProcessManagerImpl();
  ~PreallocatedProcessManagerImpl();
  DISALLOW_EVIL_CONSTRUCTORS(PreallocatedProcessManagerImpl);

  void Init();

  bool CanAllocate();
  void AllocateAfterDelay();
  void AllocateOnIdle();
  void AllocateNow();

  void RereadPrefs();
  void Enable();
  void Disable();
  void CloseProcess();

  bool mEnabled;
  bool mShutdown;
  bool mLaunchInProgress;
  RefPtr<ContentParent> mPreallocatedProcess;
  nsTHashtable<nsUint64HashKey> mBlockers;

  bool IsEmpty() const { return !mPreallocatedProcess && !mLaunchInProgress; }
};

const char* const PreallocatedProcessManagerImpl::kObserverTopics[] = {
    "memory-pressure",
    "profile-change-teardown",
    NS_XPCOM_SHUTDOWN_OBSERVER_ID,
};

/* static */
StaticRefPtr<PreallocatedProcessManagerImpl>
    PreallocatedProcessManagerImpl::sSingleton;

/* static */
PreallocatedProcessManagerImpl* PreallocatedProcessManagerImpl::Singleton() {
  MOZ_ASSERT(NS_IsMainThread());
  if (!sSingleton) {
    sSingleton = new PreallocatedProcessManagerImpl();
    sSingleton->Init();
    ClearOnShutdown(&sSingleton);
  }

  return sSingleton;
}

NS_IMPL_ISUPPORTS(PreallocatedProcessManagerImpl, nsIObserver)

PreallocatedProcessManagerImpl::PreallocatedProcessManagerImpl()
    : mEnabled(false), mShutdown(false), mLaunchInProgress(false) {}

PreallocatedProcessManagerImpl::~PreallocatedProcessManagerImpl() {
  // This shouldn't happen, because the promise callbacks should
  // hold strong references, but let't make absolutely sure:
  MOZ_RELEASE_ASSERT(!mLaunchInProgress);
}

void PreallocatedProcessManagerImpl::Init() {
  Preferences::AddStrongObserver(this, "dom.ipc.processPrelaunch.enabled");
  // We have to respect processCount at all time. This is especially important
  // for testing.
  Preferences::AddStrongObserver(this, "dom.ipc.processCount");
  nsCOMPtr<nsIObserverService> os = services::GetObserverService();
  MOZ_ASSERT(os);
  for (auto topic : kObserverTopics) {
    os->AddObserver(this, topic, /* ownsWeak */ false);
  }
  RereadPrefs();
}

NS_IMETHODIMP
PreallocatedProcessManagerImpl::Observe(nsISupports* aSubject,
                                        const char* aTopic,
                                        const char16_t* aData) {
  if (!strcmp("nsPref:changed", aTopic)) {
    // The only other observer we registered was for our prefs.
    RereadPrefs();
  } else if (!strcmp(NS_XPCOM_SHUTDOWN_OBSERVER_ID, aTopic) ||
             !strcmp("profile-change-teardown", aTopic)) {
    Preferences::RemoveObserver(this, "dom.ipc.processPrelaunch.enabled");
    Preferences::RemoveObserver(this, "dom.ipc.processCount");
    nsCOMPtr<nsIObserverService> os = services::GetObserverService();
    MOZ_ASSERT(os);
    for (auto topic : kObserverTopics) {
      os->RemoveObserver(this, topic);
    }
    // Let's prevent any new preallocated processes from starting. ContentParent
    // will handle the shutdown of the existing process and the
    // mPreallocatedProcess reference will be cleared by the ClearOnShutdown of
    // the manager singleton.
    mShutdown = true;
  } else if (!strcmp("memory-pressure", aTopic)) {
    CloseProcess();
  } else {
    MOZ_ASSERT_UNREACHABLE("Unknown topic");
  }

  return NS_OK;
}

void PreallocatedProcessManagerImpl::RereadPrefs() {
  if (mozilla::BrowserTabsRemoteAutostart() &&
      Preferences::GetBool("dom.ipc.processPrelaunch.enabled")) {
    Enable();
  } else {
    Disable();
  }

  if (ContentParent::IsMaxProcessCountReached(
          NS_LITERAL_STRING(DEFAULT_REMOTE_TYPE))) {
    CloseProcess();
  }
}

already_AddRefed<ContentParent> PreallocatedProcessManagerImpl::Take() {
  if (!mEnabled || mShutdown) {
    return nullptr;
  }

  if (mPreallocatedProcess) {
    // The preallocated process is taken. Let's try to start up a new one soon.
    ProcessPriorityManager::SetProcessPriority(mPreallocatedProcess,
                                               PROCESS_PRIORITY_FOREGROUND);
    AllocateOnIdle();
  }

  return mPreallocatedProcess.forget();
}

bool PreallocatedProcessManagerImpl::Provide(ContentParent* aParent) {
  // This will take the already-running process even if there's a
  // launch in progress; if that process hasn't been taken by the
  // time the launch completes, the new process will be shut down.
  if (mEnabled && !mShutdown && !mPreallocatedProcess) {
    mPreallocatedProcess = aParent;
  }

  // We might get a call from both NotifyTabDestroying and NotifyTabDestroyed
  // with the same ContentParent. Returning true here for both calls is
  // important to avoid the cached process to be destroyed.
  return aParent == mPreallocatedProcess;
}

void PreallocatedProcessManagerImpl::Erase(ContentParent* aParent) {
  if (mPreallocatedProcess == aParent) {
    mBlockers.RemoveEntry(aParent->ChildID());
    mPreallocatedProcess = nullptr;
  }
}

void PreallocatedProcessManagerImpl::Enable() {
  if (mEnabled) {
    return;
  }

  mEnabled = true;
  AllocateAfterDelay();
}

void PreallocatedProcessManagerImpl::AddBlocker(ContentParent* aParent) {
  uint64_t childID = aParent->ChildID();
  MOZ_ASSERT(!mBlockers.Contains(childID));
  mBlockers.PutEntry(childID);
}

void PreallocatedProcessManagerImpl::RemoveBlocker(ContentParent* aParent) {
  uint64_t childID = aParent->ChildID();
  // This used to assert that the blocker existed, but preallocated
  // processes aren't blockers anymore because it's not useful and
  // interferes with async launch, and it's simpler if content
  // processes don't need to remember whether they were preallocated.
  // (And preallocated processes can't AddBlocker when taken, because
  // it's possible for a short-lived process to be recycled through
  // Provide() and Take() before reaching RecvFirstIdle.)
  mBlockers.RemoveEntry(childID);
  if (IsEmpty() && mBlockers.IsEmpty()) {
    AllocateAfterDelay();
  }
}

bool PreallocatedProcessManagerImpl::CanAllocate() {
  return mEnabled && mBlockers.IsEmpty() && IsEmpty() && !mShutdown &&
         !ContentParent::IsMaxProcessCountReached(
             NS_LITERAL_STRING(DEFAULT_REMOTE_TYPE));
}

void PreallocatedProcessManagerImpl::AllocateAfterDelay() {
  if (!mEnabled) {
    return;
  }

  NS_DelayedDispatchToCurrentThread(
      NewRunnableMethod("PreallocatedProcessManagerImpl::AllocateOnIdle", this,
                        &PreallocatedProcessManagerImpl::AllocateOnIdle),
      StaticPrefs::dom_ipc_processPrelaunch_delayMs());
}

void PreallocatedProcessManagerImpl::AllocateOnIdle() {
  if (!mEnabled) {
    return;
  }

  NS_DispatchToCurrentThreadQueue(
      NewRunnableMethod("PreallocatedProcessManagerImpl::AllocateNow", this,
                        &PreallocatedProcessManagerImpl::AllocateNow),
      EventQueuePriority::Idle);
}

void PreallocatedProcessManagerImpl::AllocateNow() {
  if (!CanAllocate()) {
    if (mEnabled && !mShutdown && IsEmpty() && !mBlockers.IsEmpty()) {
      // If it's too early to allocate a process let's retry later.
      AllocateAfterDelay();
    }
    return;
  }

  RefPtr<PreallocatedProcessManagerImpl> self(this);
  mLaunchInProgress = true;

  ContentParent::PreallocateProcess()->Then(
      GetCurrentThreadSerialEventTarget(), __func__,

      [self, this](const RefPtr<ContentParent>& process) {
        mLaunchInProgress = false;
        if (CanAllocate()) {
          mPreallocatedProcess = process;
        } else {
          process->ShutDownProcess(ContentParent::SEND_SHUTDOWN_MESSAGE);
        }
      },

      [self, this](ContentParent::LaunchError err) {
        mLaunchInProgress = false;
      });
}

void PreallocatedProcessManagerImpl::Disable() {
  if (!mEnabled) {
    return;
  }

  mEnabled = false;
  CloseProcess();
}

void PreallocatedProcessManagerImpl::CloseProcess() {
  if (mPreallocatedProcess) {
    mPreallocatedProcess->ShutDownProcess(ContentParent::SEND_SHUTDOWN_MESSAGE);
    mPreallocatedProcess = nullptr;
  }
}

inline PreallocatedProcessManagerImpl* GetPPMImpl() {
  return PreallocatedProcessManagerImpl::Singleton();
}

/* static */
void PreallocatedProcessManager::AddBlocker(ContentParent* aParent) {
  GetPPMImpl()->AddBlocker(aParent);
}

/* static */
void PreallocatedProcessManager::RemoveBlocker(ContentParent* aParent) {
  GetPPMImpl()->RemoveBlocker(aParent);
}

/* static */
already_AddRefed<ContentParent> PreallocatedProcessManager::Take() {
  return GetPPMImpl()->Take();
}

/* static */
bool PreallocatedProcessManager::Provide(ContentParent* aParent) {
  return GetPPMImpl()->Provide(aParent);
}

/* static */
void PreallocatedProcessManager::Erase(ContentParent* aParent) {
  return GetPPMImpl()->Erase(aParent);
}

}  // namespace mozilla