summaryrefslogtreecommitdiffstats
path: root/docshell/base/BrowsingContextGroup.cpp
blob: 66ef2352710e0b7ec27f906b035f23c9e2a95491 (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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/* -*- 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/dom/BrowsingContextGroup.h"

#include "mozilla/ClearOnShutdown.h"
#include "mozilla/InputTaskManager.h"
#include "mozilla/Preferences.h"
#include "mozilla/dom/BrowsingContextBinding.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/ContentChild.h"
#include "mozilla/dom/ContentParent.h"
#include "mozilla/dom/DocGroup.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/ThrottledEventQueue.h"
#include "nsFocusManager.h"
#include "nsTHashMap.h"

namespace mozilla {
namespace dom {

// Maximum number of successive dialogs before we prompt users to disable
// dialogs for this window.
#define MAX_SUCCESSIVE_DIALOG_COUNT 5

static StaticRefPtr<BrowsingContextGroup> sChromeGroup;

static StaticAutoPtr<nsTHashMap<uint64_t, RefPtr<BrowsingContextGroup>>>
    sBrowsingContextGroups;

already_AddRefed<BrowsingContextGroup> BrowsingContextGroup::GetOrCreate(
    uint64_t aId) {
  if (!sBrowsingContextGroups) {
    sBrowsingContextGroups =
        new nsTHashMap<nsUint64HashKey, RefPtr<BrowsingContextGroup>>();
    ClearOnShutdown(&sBrowsingContextGroups);
  }

  return do_AddRef(sBrowsingContextGroups->LookupOrInsertWith(
      aId, [&aId] { return do_AddRef(new BrowsingContextGroup(aId)); }));
}

already_AddRefed<BrowsingContextGroup> BrowsingContextGroup::GetExisting(
    uint64_t aId) {
  if (sBrowsingContextGroups) {
    return do_AddRef(sBrowsingContextGroups->Get(aId));
  }
  return nullptr;
}

// Only use 53 bits for the BrowsingContextGroup ID.
static constexpr uint64_t kBrowsingContextGroupIdTotalBits = 53;
static constexpr uint64_t kBrowsingContextGroupIdProcessBits = 22;
static constexpr uint64_t kBrowsingContextGroupIdFlagBits = 1;
static constexpr uint64_t kBrowsingContextGroupIdBits =
    kBrowsingContextGroupIdTotalBits - kBrowsingContextGroupIdProcessBits -
    kBrowsingContextGroupIdFlagBits;

// IDs for the relevant flags
static constexpr uint64_t kPotentiallyCrossOriginIsolatedFlag = 0x1;

// The next ID value which will be used.
static uint64_t sNextBrowsingContextGroupId = 1;

// Generate the next ID with the given flags.
static uint64_t GenerateBrowsingContextGroupId(uint64_t aFlags) {
  MOZ_RELEASE_ASSERT(aFlags < (uint64_t(1) << kBrowsingContextGroupIdFlagBits));
  uint64_t childId = XRE_IsContentProcess()
                         ? ContentChild::GetSingleton()->GetID()
                         : uint64_t(0);
  MOZ_RELEASE_ASSERT(childId <
                     (uint64_t(1) << kBrowsingContextGroupIdProcessBits));
  uint64_t id = sNextBrowsingContextGroupId++;
  MOZ_RELEASE_ASSERT(id < (uint64_t(1) << kBrowsingContextGroupIdBits));

  return (childId << (kBrowsingContextGroupIdBits +
                      kBrowsingContextGroupIdFlagBits)) |
         (id << kBrowsingContextGroupIdFlagBits) | aFlags;
}

// Extract flags from the given ID.
static uint64_t GetBrowsingContextGroupIdFlags(uint64_t aId) {
  return aId & ((uint64_t(1) << kBrowsingContextGroupIdFlagBits) - 1);
}

uint64_t BrowsingContextGroup::CreateId(bool aPotentiallyCrossOriginIsolated) {
  // We encode the potentially cross-origin isolated bit within the ID so that
  // the information can be recovered whenever the group needs to be re-created
  // due to e.g. being garbage-collected.
  //
  // In the future if we end up needing more complex information stored within
  // the ID, we can consider converting it to a more complex type, like a
  // string.
  uint64_t flags =
      aPotentiallyCrossOriginIsolated ? kPotentiallyCrossOriginIsolatedFlag : 0;
  uint64_t id = GenerateBrowsingContextGroupId(flags);
  MOZ_ASSERT(GetBrowsingContextGroupIdFlags(id) == flags);
  return id;
}

already_AddRefed<BrowsingContextGroup> BrowsingContextGroup::Create(
    bool aPotentiallyCrossOriginIsolated) {
  return GetOrCreate(CreateId(aPotentiallyCrossOriginIsolated));
}

BrowsingContextGroup::BrowsingContextGroup(uint64_t aId) : mId(aId) {
  mTimerEventQueue = ThrottledEventQueue::Create(
      GetMainThreadSerialEventTarget(), "BrowsingContextGroup timer queue");

  mWorkerEventQueue = ThrottledEventQueue::Create(
      GetMainThreadSerialEventTarget(), "BrowsingContextGroup worker queue");
}

void BrowsingContextGroup::Register(nsISupports* aContext) {
  MOZ_DIAGNOSTIC_ASSERT(!mDestroyed);
  MOZ_DIAGNOSTIC_ASSERT(aContext);
  mContexts.Insert(aContext);
}

void BrowsingContextGroup::Unregister(nsISupports* aContext) {
  MOZ_DIAGNOSTIC_ASSERT(!mDestroyed);
  MOZ_DIAGNOSTIC_ASSERT(aContext);
  mContexts.Remove(aContext);

  MaybeDestroy();
}

void BrowsingContextGroup::EnsureHostProcess(ContentParent* aProcess) {
  MOZ_DIAGNOSTIC_ASSERT(!mDestroyed);
  MOZ_DIAGNOSTIC_ASSERT(this != sChromeGroup,
                        "cannot have content host for chrome group");
  MOZ_DIAGNOSTIC_ASSERT(aProcess->GetRemoteType() != PREALLOC_REMOTE_TYPE,
                        "cannot use preallocated process as host");
  MOZ_DIAGNOSTIC_ASSERT(!aProcess->GetRemoteType().IsEmpty(),
                        "host process must have remote type");

  // XXX: The diagnostic crashes in bug 1816025 seemed to come through caller
  // ContentParent::GetNewOrUsedLaunchingBrowserProcess where we already
  // did AssertAlive, so IsDead should be irrelevant here. Still it reads
  // wrong that we ever might do AddBrowsingContextGroup if aProcess->IsDead().
  if (aProcess->IsDead() ||
      mHosts.WithEntryHandle(aProcess->GetRemoteType(), [&](auto&& entry) {
        if (entry) {
          // We know from bug 1816025 that this happens quite often and we have
          // bug 1815480 on file that should harden the entire flow. But in the
          // meantime we can just live with NOT replacing the found host
          // process with a new one here if it is still alive.
          MOZ_ASSERT(
              entry.Data() == aProcess,
              "There's already another host process for this remote type");
          if (!entry.Data()->IsShuttingDown()) {
            return false;
          }
        }

        // This process wasn't already marked as our host, so insert it (or
        // update if the old process is shutting down), and begin subscribing,
        // unless the process is still launching.
        entry.InsertOrUpdate(do_AddRef(aProcess));

        return true;
      })) {
    aProcess->AddBrowsingContextGroup(this);
  }
}

void BrowsingContextGroup::RemoveHostProcess(ContentParent* aProcess) {
  MOZ_DIAGNOSTIC_ASSERT(aProcess);
  MOZ_DIAGNOSTIC_ASSERT(aProcess->GetRemoteType() != PREALLOC_REMOTE_TYPE);
  auto entry = mHosts.Lookup(aProcess->GetRemoteType());
  if (entry && entry.Data() == aProcess) {
    entry.Remove();
  }
}

static void CollectContextInitializers(
    Span<RefPtr<BrowsingContext>> aContexts,
    nsTArray<SyncedContextInitializer>& aInits) {
  // The order that we record these initializers is important, as it will keep
  // the order that children are attached to their parent in the newly connected
  // content process consistent.
  for (auto& context : aContexts) {
    aInits.AppendElement(context->GetIPCInitializer());
    for (const auto& window : context->GetWindowContexts()) {
      aInits.AppendElement(window->GetIPCInitializer());
      CollectContextInitializers(window->Children(), aInits);
    }
  }
}

void BrowsingContextGroup::Subscribe(ContentParent* aProcess) {
  MOZ_DIAGNOSTIC_ASSERT(!mDestroyed);
  MOZ_DIAGNOSTIC_ASSERT(aProcess && !aProcess->IsLaunching());
  MOZ_DIAGNOSTIC_ASSERT(aProcess->GetRemoteType() != PREALLOC_REMOTE_TYPE);

  // Check if we're already subscribed to this process.
  if (!mSubscribers.EnsureInserted(aProcess)) {
    return;
  }

#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
  // If the process is already marked as dead, we won't be the host, but may
  // still need to subscribe to the process due to creating a popup while
  // shutting down.
  if (!aProcess->IsDead()) {
    auto hostEntry = mHosts.Lookup(aProcess->GetRemoteType());
    MOZ_DIAGNOSTIC_ASSERT(hostEntry && hostEntry.Data() == aProcess,
                          "Cannot subscribe a non-host process");
  }
#endif

  // FIXME: This won't send non-discarded children of discarded BCs, but those
  // BCs will be in the process of being destroyed anyway.
  // FIXME: Prevent that situation from occuring.
  nsTArray<SyncedContextInitializer> inits(mContexts.Count());
  CollectContextInitializers(mToplevels, inits);

  // Send all of our contexts to the target content process.
  Unused << aProcess->SendRegisterBrowsingContextGroup(Id(), inits);

  // If the focused or active BrowsingContexts belong in this group, tell the
  // newly subscribed process.
  if (nsFocusManager* fm = nsFocusManager::GetFocusManager()) {
    BrowsingContext* focused = fm->GetFocusedBrowsingContextInChrome();
    if (focused && focused->Group() != this) {
      focused = nullptr;
    }
    BrowsingContext* active = fm->GetActiveBrowsingContextInChrome();
    if (active && active->Group() != this) {
      active = nullptr;
    }

    if (focused || active) {
      Unused << aProcess->SendSetupFocusedAndActive(
          focused, fm->GetActionIdForFocusedBrowsingContextInChrome(), active,
          fm->GetActionIdForActiveBrowsingContextInChrome());
    }
  }
}

void BrowsingContextGroup::Unsubscribe(ContentParent* aProcess) {
  MOZ_DIAGNOSTIC_ASSERT(aProcess);
  MOZ_DIAGNOSTIC_ASSERT(aProcess->GetRemoteType() != PREALLOC_REMOTE_TYPE);
  mSubscribers.Remove(aProcess);
  aProcess->RemoveBrowsingContextGroup(this);

#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
  auto hostEntry = mHosts.Lookup(aProcess->GetRemoteType());
  MOZ_DIAGNOSTIC_ASSERT(!hostEntry || hostEntry.Data() != aProcess,
                        "Unsubscribing existing host entry");
#endif
}

ContentParent* BrowsingContextGroup::GetHostProcess(
    const nsACString& aRemoteType) {
  return mHosts.GetWeak(aRemoteType);
}

void BrowsingContextGroup::UpdateToplevelsSuspendedIfNeeded() {
  if (!StaticPrefs::dom_suspend_inactive_enabled()) {
    return;
  }

  mToplevelsSuspended = ShouldSuspendAllTopLevelContexts();
  for (const auto& context : mToplevels) {
    nsPIDOMWindowOuter* outer = context->GetDOMWindow();
    if (!outer) {
      continue;
    }
    nsCOMPtr<nsPIDOMWindowInner> inner = outer->GetCurrentInnerWindow();
    if (!inner) {
      continue;
    }
    if (mToplevelsSuspended && !inner->GetWasSuspendedByGroup()) {
      inner->Suspend();
      inner->SetWasSuspendedByGroup(true);
    } else if (!mToplevelsSuspended && inner->GetWasSuspendedByGroup()) {
      inner->Resume();
      inner->SetWasSuspendedByGroup(false);
    }
  }
}

bool BrowsingContextGroup::ShouldSuspendAllTopLevelContexts() const {
  for (const auto& context : mToplevels) {
    if (!context->InactiveForSuspend()) {
      return false;
    }
  }
  return true;
}

BrowsingContextGroup::~BrowsingContextGroup() { Destroy(); }

void BrowsingContextGroup::Destroy() {
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
  if (mDestroyed) {
    MOZ_DIAGNOSTIC_ASSERT(mHosts.Count() == 0);
    MOZ_DIAGNOSTIC_ASSERT(mSubscribers.Count() == 0);
    MOZ_DIAGNOSTIC_ASSERT_IF(sBrowsingContextGroups,
                             !sBrowsingContextGroups->Contains(Id()) ||
                                 *sBrowsingContextGroups->Lookup(Id()) != this);
  }
  mDestroyed = true;
#endif

  // Make sure to call `RemoveBrowsingContextGroup` for every entry in both
  // `mHosts` and `mSubscribers`. This will visit most entries twice, but
  // `RemoveBrowsingContextGroup` is safe to call multiple times.
  for (const auto& entry : mHosts.Values()) {
    entry->RemoveBrowsingContextGroup(this);
  }
  for (const auto& key : mSubscribers) {
    key->RemoveBrowsingContextGroup(this);
  }
  mHosts.Clear();
  mSubscribers.Clear();

  if (sBrowsingContextGroups) {
    sBrowsingContextGroups->Remove(Id());
  }
}

void BrowsingContextGroup::AddKeepAlive() {
  MOZ_DIAGNOSTIC_ASSERT(!mDestroyed);
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
  mKeepAliveCount++;
}

void BrowsingContextGroup::RemoveKeepAlive() {
  MOZ_DIAGNOSTIC_ASSERT(!mDestroyed);
  MOZ_DIAGNOSTIC_ASSERT(mKeepAliveCount > 0);
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
  mKeepAliveCount--;

  MaybeDestroy();
}

auto BrowsingContextGroup::MakeKeepAlivePtr() -> KeepAlivePtr {
  AddKeepAlive();
  return KeepAlivePtr{do_AddRef(this).take()};
}

void BrowsingContextGroup::MaybeDestroy() {
  // Once there are no synced contexts referencing a `BrowsingContextGroup`, we
  // can clear subscribers and destroy this group. We only do this in the parent
  // process, as it will orchestrate destruction of BCGs in content processes.
  if (XRE_IsParentProcess() && mContexts.IsEmpty() && mKeepAliveCount == 0 &&
      this != sChromeGroup) {
    Destroy();

    // We may have been deleted here, as `Destroy()` will clear references. Do
    // not access any members at this point.
  }
}

void BrowsingContextGroup::ChildDestroy() {
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsContentProcess());
  MOZ_DIAGNOSTIC_ASSERT(!mDestroyed);
  MOZ_DIAGNOSTIC_ASSERT(mContexts.IsEmpty());
  Destroy();
}

nsISupports* BrowsingContextGroup::GetParentObject() const {
  return xpc::NativeGlobal(xpc::PrivilegedJunkScope());
}

JSObject* BrowsingContextGroup::WrapObject(JSContext* aCx,
                                           JS::Handle<JSObject*> aGivenProto) {
  return BrowsingContextGroup_Binding::Wrap(aCx, this, aGivenProto);
}

nsresult BrowsingContextGroup::QueuePostMessageEvent(
    already_AddRefed<nsIRunnable>&& aRunnable) {
  if (StaticPrefs::dom_separate_event_queue_for_post_message_enabled()) {
    if (!mPostMessageEventQueue) {
      nsCOMPtr<nsISerialEventTarget> target = GetMainThreadSerialEventTarget();
      mPostMessageEventQueue = ThrottledEventQueue::Create(
          target, "PostMessage Queue",
          nsIRunnablePriority::PRIORITY_DEFERRED_TIMERS);
      nsresult rv = mPostMessageEventQueue->SetIsPaused(false);
      MOZ_ALWAYS_SUCCEEDS(rv);
    }

    // Ensure the queue is enabled
    if (mPostMessageEventQueue->IsPaused()) {
      nsresult rv = mPostMessageEventQueue->SetIsPaused(false);
      MOZ_ALWAYS_SUCCEEDS(rv);
    }

    if (mPostMessageEventQueue) {
      mPostMessageEventQueue->Dispatch(std::move(aRunnable),
                                       NS_DISPATCH_NORMAL);
      return NS_OK;
    }
  }
  return NS_ERROR_FAILURE;
}

void BrowsingContextGroup::FlushPostMessageEvents() {
  if (StaticPrefs::dom_separate_event_queue_for_post_message_enabled()) {
    if (mPostMessageEventQueue) {
      nsresult rv = mPostMessageEventQueue->SetIsPaused(true);
      MOZ_ALWAYS_SUCCEEDS(rv);
      nsCOMPtr<nsIRunnable> event;
      while ((event = mPostMessageEventQueue->GetEvent())) {
        NS_DispatchToMainThread(event.forget());
      }
    }
  }
}

bool BrowsingContextGroup::HasActiveBC() {
  for (auto& topLevelBC : Toplevels()) {
    if (topLevelBC->IsActive()) {
      return true;
    }
  }
  return false;
}

void BrowsingContextGroup::IncInputEventSuspensionLevel() {
  MOZ_ASSERT(StaticPrefs::dom_input_events_canSuspendInBCG_enabled());
  if (!mHasIncreasedInputTaskManagerSuspensionLevel && HasActiveBC()) {
    IncInputTaskManagerSuspensionLevel();
  }
  ++mInputEventSuspensionLevel;
}

void BrowsingContextGroup::DecInputEventSuspensionLevel() {
  MOZ_ASSERT(StaticPrefs::dom_input_events_canSuspendInBCG_enabled());
  --mInputEventSuspensionLevel;
  if (!mInputEventSuspensionLevel &&
      mHasIncreasedInputTaskManagerSuspensionLevel) {
    DecInputTaskManagerSuspensionLevel();
  }
}

void BrowsingContextGroup::DecInputTaskManagerSuspensionLevel() {
  MOZ_ASSERT(StaticPrefs::dom_input_events_canSuspendInBCG_enabled());
  MOZ_ASSERT(mHasIncreasedInputTaskManagerSuspensionLevel);

  InputTaskManager::Get()->DecSuspensionLevel();
  mHasIncreasedInputTaskManagerSuspensionLevel = false;
}

void BrowsingContextGroup::IncInputTaskManagerSuspensionLevel() {
  MOZ_ASSERT(StaticPrefs::dom_input_events_canSuspendInBCG_enabled());
  MOZ_ASSERT(!mHasIncreasedInputTaskManagerSuspensionLevel);
  MOZ_ASSERT(HasActiveBC());

  InputTaskManager::Get()->IncSuspensionLevel();
  mHasIncreasedInputTaskManagerSuspensionLevel = true;
}

void BrowsingContextGroup::UpdateInputTaskManagerIfNeeded(bool aIsActive) {
  MOZ_ASSERT(StaticPrefs::dom_input_events_canSuspendInBCG_enabled());
  if (!aIsActive) {
    if (mHasIncreasedInputTaskManagerSuspensionLevel) {
      MOZ_ASSERT(mInputEventSuspensionLevel > 0);
      if (!HasActiveBC()) {
        DecInputTaskManagerSuspensionLevel();
      }
    }
  } else {
    if (mInputEventSuspensionLevel &&
        !mHasIncreasedInputTaskManagerSuspensionLevel) {
      IncInputTaskManagerSuspensionLevel();
    }
  }
}

/* static */
BrowsingContextGroup* BrowsingContextGroup::GetChromeGroup() {
  MOZ_DIAGNOSTIC_ASSERT(XRE_IsParentProcess());
  if (!sChromeGroup && XRE_IsParentProcess()) {
    sChromeGroup = BrowsingContextGroup::Create();
    ClearOnShutdown(&sChromeGroup);
  }

  return sChromeGroup;
}

void BrowsingContextGroup::GetDocGroups(nsTArray<DocGroup*>& aDocGroups) {
  MOZ_ASSERT(NS_IsMainThread());
  AppendToArray(aDocGroups, mDocGroups.Values());
}

already_AddRefed<DocGroup> BrowsingContextGroup::AddDocument(
    const nsACString& aKey, Document* aDocument) {
  MOZ_ASSERT(NS_IsMainThread());

  RefPtr<DocGroup>& docGroup = mDocGroups.LookupOrInsertWith(
      aKey, [&] { return DocGroup::Create(this, aKey); });

  docGroup->AddDocument(aDocument);
  return do_AddRef(docGroup);
}

void BrowsingContextGroup::RemoveDocument(Document* aDocument,
                                          DocGroup* aDocGroup) {
  MOZ_ASSERT(NS_IsMainThread());
  RefPtr<DocGroup> docGroup = aDocGroup;
  // Removing the last document in DocGroup might decrement the
  // DocGroup BrowsingContextGroup's refcount to 0.
  RefPtr<BrowsingContextGroup> kungFuDeathGrip(this);
  docGroup->RemoveDocument(aDocument);

  if (docGroup->IsEmpty()) {
    mDocGroups.Remove(docGroup->GetKey());
  }
}

already_AddRefed<BrowsingContextGroup> BrowsingContextGroup::Select(
    WindowContext* aParent, BrowsingContext* aOpener) {
  if (aParent) {
    return do_AddRef(aParent->Group());
  }
  if (aOpener) {
    return do_AddRef(aOpener->Group());
  }
  return Create();
}

void BrowsingContextGroup::GetAllGroups(
    nsTArray<RefPtr<BrowsingContextGroup>>& aGroups) {
  aGroups.Clear();
  if (!sBrowsingContextGroups) {
    return;
  }

  aGroups = ToArray(sBrowsingContextGroups->Values());
}

// For tests only.
void BrowsingContextGroup::ResetDialogAbuseState() {
  mDialogAbuseCount = 0;
  // Reset the timer.
  mLastDialogQuitTime =
      TimeStamp::Now() -
      TimeDuration::FromSeconds(DEFAULT_SUCCESSIVE_DIALOG_TIME_LIMIT);
}

bool BrowsingContextGroup::DialogsAreBeingAbused() {
  if (mLastDialogQuitTime.IsNull() || nsContentUtils::IsCallerChrome()) {
    return false;
  }

  TimeDuration dialogInterval(TimeStamp::Now() - mLastDialogQuitTime);
  if (dialogInterval.ToSeconds() <
      Preferences::GetInt("dom.successive_dialog_time_limit",
                          DEFAULT_SUCCESSIVE_DIALOG_TIME_LIMIT)) {
    mDialogAbuseCount++;

    return PopupBlocker::GetPopupControlState() > PopupBlocker::openAllowed ||
           mDialogAbuseCount > MAX_SUCCESSIVE_DIALOG_COUNT;
  }

  // Reset the abuse counter
  mDialogAbuseCount = 0;

  return false;
}

bool BrowsingContextGroup::IsPotentiallyCrossOriginIsolated() {
  return GetBrowsingContextGroupIdFlags(mId) &
         kPotentiallyCrossOriginIsolatedFlag;
}

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(BrowsingContextGroup, mContexts,
                                      mToplevels, mHosts, mSubscribers,
                                      mTimerEventQueue, mWorkerEventQueue,
                                      mDocGroups)

}  // namespace dom
}  // namespace mozilla