DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (7f9f804e9dbe)

VCS Links

Line Code
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 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
/* 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/PresShell.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/SessionStoreListener.h"
#include "mozilla/dom/SessionStoreUtils.h"
#include "mozilla/dom/SessionStoreUtilsBinding.h"
#include "mozilla/dom/StorageEvent.h"
#include "mozilla/dom/BrowserChild.h"
#include "mozilla/StaticPrefs_fission.h"
#include "nsGenericHTMLElement.h"
#include "nsDocShell.h"
#include "nsIAppWindow.h"
#include "nsIDocShell.h"
#include "nsIDocShellTreeOwner.h"
#include "nsImportModule.h"
#include "nsIPrefBranch.h"
#include "nsITimer.h"
#include "nsIWebProgress.h"
#include "nsIXPConnect.h"
#include "nsPresContext.h"
#include "nsPrintfCString.h"
#include "SessionStoreFunctions.h"

using namespace mozilla;
using namespace mozilla::dom;

// This pref controls whether or not we send updates to the parent on a timeout
// or not, and should only be used for tests or debugging.
static const char kTimeOutDisable[] =
    "browser.sessionstore.debug.no_auto_updates";
// Timeout for waiting an idle period to send data.
static const char kPrefInterval[] = "browser.sessionstore.interval";

NS_IMPL_CYCLE_COLLECTION(ContentSessionStore, mDocShell)
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(ContentSessionStore, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(ContentSessionStore, Release)

ContentSessionStore::ContentSessionStore(nsIDocShell* aDocShell)
    : mDocShell(aDocShell),
      mPrivateChanged(false),
      mIsPrivate(false),
      mScrollChanged(NO_CHANGE),
      mFormDataChanged(NO_CHANGE),
      mStorageStatus(NO_STORAGE),
      mDocCapChanged(false),
      mSHistoryInParent(StaticPrefs::fission_sessionHistoryInParent()),
      mSHistoryChanged(false),
      mSHistoryChangedFromParent(false) {
  MOZ_ASSERT(mDocShell);
  // Check that value at startup as it might have
  // been set before the frame script was loaded.
  if (NS_SUCCEEDED(nsDocShell::Cast(mDocShell)->GetUsePrivateBrowsing(
          &mPrivateChanged)) &&
      mPrivateChanged) {
    mIsPrivate = true;
  }
}

nsCString ContentSessionStore::CollectDocShellCapabilities() {
  bool allow;
  nsCString aRetVal;

#define TRY_ALLOWPROP(y)                        \
  PR_BEGIN_MACRO                                \
  nsresult rv = mDocShell->GetAllow##y(&allow); \
  if (NS_SUCCEEDED(rv) && !allow) {             \
    if (!aRetVal.IsEmpty()) {                   \
      aRetVal.Append(',');                      \
    }                                           \
    aRetVal.Append(#y);                         \
  }                                             \
  PR_END_MACRO

  TRY_ALLOWPROP(Plugins);
  // Bug 1328013 : Don't collect "AllowJavascript" property
  // TRY_ALLOWPROP(Javascript);
  TRY_ALLOWPROP(MetaRedirects);
  TRY_ALLOWPROP(Subframes);
  TRY_ALLOWPROP(Images);
  TRY_ALLOWPROP(Media);
  TRY_ALLOWPROP(DNSPrefetch);
  TRY_ALLOWPROP(WindowControl);
  TRY_ALLOWPROP(Auth);
  TRY_ALLOWPROP(ContentRetargeting);
  TRY_ALLOWPROP(ContentRetargetingOnChildren);
#undef TRY_ALLOWPROP
  return aRetVal;
}

void ContentSessionStore::OnPrivateModeChanged(bool aEnabled) {
  mPrivateChanged = true;
  mIsPrivate = aEnabled;
}

nsCString ContentSessionStore::GetDocShellCaps() {
  mDocCapChanged = false;
  return mDocCaps;
}

bool ContentSessionStore::GetPrivateModeEnabled() {
  mPrivateChanged = false;
  return mIsPrivate;
}

void ContentSessionStore::SetFullStorageNeeded() {
  // We need the entire session storage, reset the pending individual change
  ResetStorageChanges();
  mStorageStatus = FULLSTORAGE;
}

void ContentSessionStore::ResetStorageChanges() {
  mOrigins.Clear();
  mKeys.Clear();
  mValues.Clear();
}

void ContentSessionStore::OnDocumentStart() {
  mScrollChanged = PAGELOADEDSTART;
  mFormDataChanged = PAGELOADEDSTART;
  nsCString caps = CollectDocShellCapabilities();
  if (!mDocCaps.Equals(caps)) {
    mDocCaps = caps;
    mDocCapChanged = true;
  }

  SetFullStorageNeeded();

  if (mSHistoryInParent) {
    mSHistoryChanged = true;
  }
}

void ContentSessionStore::OnDocumentEnd() {
  mScrollChanged = WITH_CHANGE;
  SetFullStorageNeeded();

  if (mSHistoryInParent) {
    mSHistoryChanged = true;
  }
}

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TabListener)
  NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
  NS_INTERFACE_MAP_ENTRY(nsIObserver)
  NS_INTERFACE_MAP_ENTRY(nsIPrivacyTransitionObserver)
  NS_INTERFACE_MAP_ENTRY(nsIWebProgressListener)
  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMEventListener)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTION_WEAK(TabListener, mDocShell, mSessionStore,
                              mOwnerContent)
NS_IMPL_CYCLE_COLLECTING_ADDREF(TabListener)
NS_IMPL_CYCLE_COLLECTING_RELEASE(TabListener)

TabListener::TabListener(nsIDocShell* aDocShell, Element* aElement)
    : mDocShell(aDocShell),
      mSessionStore(new ContentSessionStore(aDocShell)),
      mOwnerContent(aElement),
      mProgressListenerRegistered(false),
      mEventListenerRegistered(false),
      mPrefObserverRegistered(false),
      mStorageObserverRegistered(false),
      mStorageChangeListenerRegistered(false),
      mUpdatedTimer(nullptr),
      mTimeoutDisabled(false),
      mUpdateInterval(15000),
      mEpoch(0),
      mSHistoryInParent(StaticPrefs::fission_sessionHistoryInParent()) {
  MOZ_ASSERT(mDocShell);
}

EventTarget* TabListener::GetEventTarget() {
  if (mOwnerContent) {
    return mOwnerContent;
  }

  nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(mDocShell);
  if (window) {
    return window->GetChromeEventHandler();
  }

  return nullptr;
}

nsresult TabListener::Init() {
  TabListener::UpdateSessionStore();
  nsresult rv = mDocShell->AddWeakPrivacyTransitionObserver(this);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIWebProgress> webProgress = do_QueryInterface(mDocShell);
  rv = webProgress->AddProgressListener(this,
                                        nsIWebProgress::NOTIFY_STATE_DOCUMENT);
  NS_ENSURE_SUCCESS(rv, rv);
  mProgressListenerRegistered = true;

  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID);
  NS_WARNING_ASSERTION(prefBranch, "no prefservice");
  if (prefBranch) {
    prefBranch->AddObserver(kTimeOutDisable, this, true);
    prefBranch->AddObserver(kPrefInterval, this, true);
    mPrefObserverRegistered = true;
  }

  nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  NS_WARNING_ASSERTION(obs, "no observer service");
  if (obs) {
    obs->AddObserver(this, "browser:purge-sessionStorage", true);
    mStorageObserverRegistered = true;
  }

  nsCOMPtr<EventTarget> eventTarget = GetEventTarget();
  if (!eventTarget) {
    return NS_OK;
  }
  eventTarget->AddSystemEventListener(NS_LITERAL_STRING("mozvisualscroll"),
                                      this, false);
  eventTarget->AddSystemEventListener(NS_LITERAL_STRING("input"), this, false);

  if (mSHistoryInParent) {
    eventTarget->AddSystemEventListener(NS_LITERAL_STRING("DOMTitleChanged"),
                                        this, false);
  }

  mEventListenerRegistered = true;
  eventTarget->AddSystemEventListener(
      NS_LITERAL_STRING("MozSessionStorageChanged"), this, false);
  mStorageChangeListenerRegistered = true;
  return NS_OK;
}

/* static */
void TabListener::TimerCallback(nsITimer* aTimer, void* aClosure) {
  auto listener = static_cast<TabListener*>(aClosure);
  listener->UpdateSessionStore();
  listener->StopTimerForUpdate();
}

void TabListener::StopTimerForUpdate() {
  if (mUpdatedTimer) {
    mUpdatedTimer->Cancel();
    mUpdatedTimer = nullptr;
  }
}

void TabListener::AddTimerForUpdate() {
  if (mUpdatedTimer) {
    return;
  }

  if (mTimeoutDisabled) {
    UpdateSessionStore();
    return;
  }

  NS_NewTimerWithFuncCallback(getter_AddRefs(mUpdatedTimer), TimerCallback,
                              this, mUpdateInterval, nsITimer::TYPE_ONE_SHOT,
                              "TabListener::TimerCallback");
}

NS_IMETHODIMP TabListener::PrivateModeChanged(bool aEnabled) {
  mSessionStore->OnPrivateModeChanged(aEnabled);
  AddTimerForUpdate();
  return NS_OK;
}

NS_IMETHODIMP TabListener::OnStateChange(nsIWebProgress* aWebProgress,
                                         nsIRequest* aRequest,
                                         uint32_t aStateFlags,
                                         nsresult aStatus) {
  if (!mSessionStore) {
    return NS_OK;
  }

  // Ignore state changes for subframes because we're only interested in the
  // top-document starting or stopping its load.
  bool isTopLevel = false;
  nsresult rv = aWebProgress->GetIsTopLevel(&isTopLevel);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!isTopLevel) {
    return NS_OK;
  }

  // The DOM Window ID getter here may throw if the inner or outer windows
  // aren't created yet or are destroyed at the time we're making this call
  // but that isn't fatal so ignore the exceptions here.
  uint64_t DOMWindowID = 0;
  Unused << aWebProgress->GetDOMWindowID(&DOMWindowID);
  nsCOMPtr<nsPIDOMWindowOuter> window = do_GetInterface(mDocShell);
  NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
  if (DOMWindowID != window->WindowID()) {
    return NS_OK;
  }

  // onStateChange will be fired when loading the initial about:blank URI for
  // a browser, which we don't actually care about. This is particularly for
  // the case of unrestored background tabs, where the content has not yet
  // been restored: we don't want to accidentally send any updates to the
  // parent when the about:blank placeholder page has loaded.
  if (!mDocShell->GetHasLoadedNonBlankURI()) {
    return NS_OK;
  }

  if (aStateFlags & (nsIWebProgressListener::STATE_START)) {
    mSessionStore->OnDocumentStart();
    ResetStorageChangeListener();
  } else if (aStateFlags & (nsIWebProgressListener::STATE_STOP)) {
    mSessionStore->OnDocumentEnd();
  }

  return NS_OK;
}

NS_IMETHODIMP
TabListener::HandleEvent(Event* aEvent) {
  EventTarget* target = aEvent->GetTarget();
  if (!target) {
    return NS_OK;
  }

  nsPIDOMWindowOuter* outer = target->GetOwnerGlobalForBindingsInternal();
  if (!outer) {
    return NS_OK;
  }

  nsIDocShell* docShell = outer->GetDocShell();
  if (!docShell) {
    return NS_OK;
  }

  bool isDynamic = false;
  nsresult rv = docShell->GetCreatedDynamically(&isDynamic);
  if (NS_FAILED(rv)) {
    return NS_OK;
  }

  if (isDynamic) {
    return NS_OK;
  }

  nsAutoString eventType;
  aEvent->GetType(eventType);
  if (eventType.EqualsLiteral("mozvisualscroll")) {
    mSessionStore->SetScrollPositionChanged();
    AddTimerForUpdate();
  } else if (eventType.EqualsLiteral("input")) {
    mSessionStore->SetFormDataChanged();
    AddTimerForUpdate();
  } else if (eventType.EqualsLiteral("MozSessionStorageChanged")) {
    auto event = static_cast<StorageEvent*>(aEvent);
    RefPtr<Storage> changingStorage = event->GetStorageArea();
    if (!changingStorage) {
      return NS_OK;
    }
    // How much data does DOMSessionStorage contain?
    int64_t storageUsage = changingStorage->GetOriginQuotaUsage();
    if (storageUsage > StaticPrefs::browser_sessionstore_dom_storage_limit()) {
      RemoveStorageChangeListener();
      mSessionStore->ResetStorageChanges();
      mSessionStore->ResetStorage();
      return NS_OK;
    }
    if (mSessionStore->AppendSessionStorageChange(event)) {
      AddTimerForUpdate();
    }
  } else if (eventType.EqualsLiteral("DOMTitleChanged")) {
    mSessionStore->SetSHistoryChanged();
    AddTimerForUpdate();
  }

  return NS_OK;
}

NS_IMETHODIMP TabListener::OnProgressChange(nsIWebProgress* aWebProgress,
                                            nsIRequest* aRequest,
                                            int32_t aCurSelfProgress,
                                            int32_t aMaxSelfProgress,
                                            int32_t aCurTotalProgress,
                                            int32_t aMaxTotalProgress) {
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP TabListener::OnLocationChange(nsIWebProgress* aWebProgress,
                                            nsIRequest* aRequest,
                                            nsIURI* aLocation,
                                            uint32_t aFlags) {
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP TabListener::OnStatusChange(nsIWebProgress* aWebProgress,
                                          nsIRequest* aRequest,
                                          nsresult aStatus,
                                          const char16_t* aMessage) {
  return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP TabListener::OnSecurityChange(nsIWebProgress* aWebProgress,
                                            nsIRequest* aRequest,
                                            uint32_t aState) {
  return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP TabListener::OnContentBlockingEvent(nsIWebProgress* aWebProgress,
                                                  nsIRequest* aRequest,
                                                  uint32_t aEvent) {
  return NS_ERROR_NOT_IMPLEMENTED;
}

nsresult TabListener::Observe(nsISupports* aSubject, const char* aTopic,
                              const char16_t* aData) {
  if (!strcmp(aTopic, "browser:purge-sessionStorage")) {
    mSessionStore->SetFullStorageNeeded();
    AddTimerForUpdate();
    return NS_OK;
  }

  if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
    nsCOMPtr<nsIPrefBranch> prefBranch = do_QueryInterface(aSubject);

    bool timeoutDisabled;
    if (NS_SUCCEEDED(
            prefBranch->GetBoolPref(kTimeOutDisable, &timeoutDisabled))) {
      if (mTimeoutDisabled != timeoutDisabled) {
        mTimeoutDisabled = timeoutDisabled;
        if (mUpdatedTimer) {
          StopTimerForUpdate();
          AddTimerForUpdate();
        }
      }
    }

    int32_t interval = 0;
    if (NS_SUCCEEDED(prefBranch->GetIntPref(kPrefInterval, &interval))) {
      if (mUpdateInterval != interval) {
        mUpdateInterval = interval;
        if (mUpdatedTimer) {
          StopTimerForUpdate();
          AddTimerForUpdate();
        }
      }
    }
    return NS_OK;
  }

  NS_ERROR("Unexpected topic");
  return NS_ERROR_UNEXPECTED;
}

nsCString CollectPosition(Document& aDocument) {
  PresShell* presShell = aDocument.GetPresShell();
  if (!presShell) {
    return EmptyCString();
  }
  nsPoint scrollPos = presShell->GetVisualViewportOffset();
  int scrollX = nsPresContext::AppUnitsToIntCSSPixels(scrollPos.x);
  int scrollY = nsPresContext::AppUnitsToIntCSSPixels(scrollPos.y);
  if ((scrollX != 0) || (scrollY != 0)) {
    return nsPrintfCString("%d,%d", scrollX, scrollY);
  }

  return EmptyCString();
}

int CollectPositions(BrowsingContext* aBrowsingContext,
                     nsTArray<nsCString>& aPositions,
                     nsTArray<int32_t>& aPositionDescendants) {
  nsPIDOMWindowOuter* window = aBrowsingContext->GetDOMWindow();
  if (!window) {
    return 0;
  }

  nsIDocShell* docShell = window->GetDocShell();
  if (!docShell || docShell->GetCreatedDynamically()) {
    return 0;
  }

  Document* document = window->GetDoc();
  if (!document) {
    return 0;
  }

  /* Collect data from current frame */
  aPositions.AppendElement(CollectPosition(*document));
  aPositionDescendants.AppendElement(0);
  unsigned long currentIdx = aPositions.Length() - 1;

  /* Collect data from all child frame */
  // This is not going to work for fission. Bug 1572084 for tracking it.
  for (auto& child : aBrowsingContext->GetChildren()) {
    aPositionDescendants[currentIdx] +=
        CollectPositions(child, aPositions, aPositionDescendants);
  }

  return aPositionDescendants[currentIdx] + 1;
}

void ContentSessionStore::GetScrollPositions(
    nsTArray<nsCString>& aPositions, nsTArray<int32_t>& aPositionDescendants) {
  if (mScrollChanged == PAGELOADEDSTART) {
    aPositionDescendants.AppendElement(0);
    aPositions.AppendElement(EmptyCString());
  } else {
    CollectPositions(mDocShell->GetBrowsingContext(), aPositions,
                     aPositionDescendants);
  }
  mScrollChanged = NO_CHANGE;
}

void CollectInput(Document& aDocument, InputFormData& aInput,
                  nsTArray<CollectedInputDataValue>& aIdVals,
                  nsTArray<CollectedInputDataValue>& aXPathVals) {
  PresShell* presShell = aDocument.GetPresShell();
  if (!presShell) {
    return;
  }

  uint16_t numXPath = 0;
  uint16_t numId = 0;

  // textarea element
  SessionStoreUtils::CollectFromTextAreaElement(aDocument, numXPath, numId,
                                                aXPathVals, aIdVals);
  // input element
  SessionStoreUtils::CollectFromInputElement(aDocument, numXPath, numId,
                                             aXPathVals, aIdVals);
  // select element
  SessionStoreUtils::CollectFromSelectElement(aDocument, numXPath, numId,
                                              aXPathVals, aIdVals);

  Element* bodyElement = aDocument.GetBody();
  if (aDocument.HasFlag(NODE_IS_EDITABLE) && bodyElement) {
    bodyElement->GetInnerHTML(aInput.innerHTML, IgnoreErrors());
  }
  if (aInput.innerHTML.IsEmpty() && numXPath == 0 && numId == 0) {
    return;
  }

  // Store the frame's current URL with its form data so that we can compare
  // it when restoring data to not inject form data into the wrong document.
  nsIURI* uri = aDocument.GetDocumentURI();
  if (uri) {
    uri->GetSpecIgnoringRef(aInput.url);
  }
  aInput.numId = numId;
  aInput.numXPath = numXPath;
}

int CollectInputs(BrowsingContext* aBrowsingContext,
                  nsTArray<InputFormData>& aInputs,
                  nsTArray<CollectedInputDataValue>& aIdVals,
                  nsTArray<CollectedInputDataValue>& aXPathVals) {
  nsPIDOMWindowOuter* window = aBrowsingContext->GetDOMWindow();
  if (!window) {
    return 0;
  }

  nsIDocShell* docShell = window->GetDocShell();
  if (!docShell || docShell->GetCreatedDynamically()) {
    return 0;
  }

  Document* document = window->GetDoc();
  if (!document) {
    return 0;
  }

  /* Collect data from current frame */
  InputFormData input;
  input.descendants = 0;
  input.numId = 0;
  input.numXPath = 0;
  CollectInput(*document, input, aIdVals, aXPathVals);
  aInputs.AppendElement(input);
  unsigned long currentIdx = aInputs.Length() - 1;

  /* Collect data from all child frame */
  // This is not going to work for fission. Bug 1572084 for tracking it.
  for (auto& child : aBrowsingContext->GetChildren()) {
    aInputs[currentIdx].descendants +=
        CollectInputs(child, aInputs, aIdVals, aXPathVals);
  }

  return aInputs[currentIdx].descendants + 1;
}

nsTArray<InputFormData> ContentSessionStore::GetInputs(
    nsTArray<CollectedInputDataValue>& aIdVals,
    nsTArray<CollectedInputDataValue>& aXPathVals) {
  nsTArray<InputFormData> inputs;
  if (mFormDataChanged == PAGELOADEDSTART) {
    mFormDataChanged = NO_CHANGE;
    InputFormData input;
    input.descendants = 0;
    input.innerHTML = EmptyString();
    input.url = EmptyCString();
    input.numId = 0;
    input.numXPath = 0;
    inputs.AppendElement(input);
  } else {
    mFormDataChanged = NO_CHANGE;
    CollectInputs(nsDocShell::Cast(mDocShell)->GetBrowsingContext(), inputs,
                  aIdVals, aXPathVals);
  }
  return inputs;
}

bool ContentSessionStore::AppendSessionStorageChange(StorageEvent* aEvent) {
  // We will collect the full SessionStore if mStorageStatus is FULLSTORAGE.
  // These partial changes can be skipped in this case.
  if (mStorageStatus == FULLSTORAGE) {
    return false;
  }

  nsAutoString origin;
  aEvent->GetUrl(origin);
  nsCOMPtr<nsIURI> newUri;
  nsresult rv =
      NS_NewURI(getter_AddRefs(newUri), NS_ConvertUTF16toUTF8(origin));
  if (NS_FAILED(rv)) {
    return false;
  }

  newUri->GetPrePath(*mOrigins.AppendElement());
  aEvent->GetKey(*mKeys.AppendElement());
  aEvent->GetNewValue(*mValues.AppendElement());
  mStorageStatus = STORAGECHANGE;
  return true;
}

bool ContentSessionStore::GetAndClearStorageChanges(
    nsTArray<nsCString>& aOrigins, nsTArray<nsString>& aKeys,
    nsTArray<nsString>& aValues) {
  MOZ_ASSERT(IsStorageUpdated());
  bool isFullStorage = false;

  if (mStorageStatus == RESET) {
    isFullStorage = true;
  } else if (mStorageStatus == FULLSTORAGE) {
    MOZ_ASSERT(mDocShell);
    SessionStoreUtils::CollectedSessionStorage(
        nsDocShell::Cast(mDocShell)->GetBrowsingContext(), aOrigins, aKeys,
        aValues);
    isFullStorage = true;
  } else if (mStorageStatus == STORAGECHANGE) {
    aOrigins.SwapElements(mOrigins);
    aKeys.SwapElements(mKeys);
    aValues.SwapElements(mValues);
  }

  ResetStorageChanges();
  mStorageStatus = NO_STORAGE;
  return isFullStorage;
}

bool TabListener::ForceFlushFromParent(uint32_t aFlushId, bool aIsFinal) {
  if (!XRE_IsParentProcess()) {
    return false;
  }
  if (!mSessionStore) {
    return false;
  }
  return UpdateSessionStore(aFlushId, aIsFinal);
}

void TabListener::UpdateSHistoryChanges(bool aImmediately) {
  mSessionStore->SetSHistoryFromParentChanged();
  if (aImmediately) {
    UpdateSessionStore();
  } else {
    AddTimerForUpdate();
  }
}

bool TabListener::UpdateSessionStore(uint32_t aFlushId, bool aIsFinal) {
  if (!aFlushId) {
    if (!mSessionStore || !mSessionStore->UpdateNeeded()) {
      return false;
    }
  }

  if (!XRE_IsParentProcess()) {
    BrowserChild* browserChild = BrowserChild::GetFrom(mDocShell);
    if (browserChild) {
      StopTimerForUpdate();
      return browserChild->UpdateSessionStore(aFlushId);
    }
    return false;
  }

  if (!mOwnerContent) {
    return false;
  }

  uint32_t chromeFlags = 0;
  nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
  mDocShell->GetTreeOwner(getter_AddRefs(treeOwner));
  if (!treeOwner) {
    return false;
  }
  nsCOMPtr<nsIAppWindow> window(do_GetInterface(treeOwner));
  if (!window) {
    return false;
  }
  if (window && NS_FAILED(window->GetChromeFlags(&chromeFlags))) {
    return false;
  }

  UpdateSessionStoreData data;
  if (mSessionStore->IsDocCapChanged()) {
    data.mDocShellCaps.Construct() = mSessionStore->GetDocShellCaps();
  }
  if (mSessionStore->IsPrivateChanged()) {
    data.mIsPrivate.Construct() = mSessionStore->GetPrivateModeEnabled();
  }
  if (mSessionStore->IsScrollPositionChanged()) {
    nsTArray<nsCString> positions;
    nsTArray<int> descendants;
    mSessionStore->GetScrollPositions(positions, descendants);
    data.mPositions.Construct(std::move(positions));
    data.mPositionDescendants.Construct(std::move(descendants));
  }
  if (mSessionStore->IsFormDataChanged()) {
    nsTArray<CollectedInputDataValue> dataWithId, dataWithXpath;
    nsTArray<InputFormData> inputs =
        mSessionStore->GetInputs(dataWithId, dataWithXpath);
    nsTArray<int> descendants, numId, numXPath;
    nsTArray<nsString> innerHTML;
    nsTArray<nsCString> url;

    if (dataWithId.Length() != 0) {
      SessionStoreUtils::ComposeInputData(dataWithId, data.mId.Construct());
    }
    if (dataWithXpath.Length() != 0) {
      SessionStoreUtils::ComposeInputData(dataWithXpath,
                                          data.mXpath.Construct());
    }

    for (const InputFormData& input : inputs) {
      descendants.AppendElement(input.descendants);
      numId.AppendElement(input.numId);
      numXPath.AppendElement(input.numXPath);
      innerHTML.AppendElement(input.innerHTML);
      url.AppendElement(input.url);
    }
    if (descendants.Length() != 0) {
      data.mInputDescendants.Construct(std::move(descendants));
      data.mNumId.Construct(std::move(numId));
      data.mNumXPath.Construct(std::move(numXPath));
      data.mInnerHTML.Construct(std::move(innerHTML));
      data.mUrl.Construct(std::move(url));
    }
  }
  if (mSessionStore->IsStorageUpdated()) {
    nsTArray<nsCString> origins;
    nsTArray<nsString> keys, values;
    data.mIsFullStorage.Construct() =
        mSessionStore->GetAndClearStorageChanges(origins, keys, values);
    data.mStorageOrigins.Construct(std::move(origins));
    data.mStorageKeys.Construct(std::move(keys));
    data.mStorageValues.Construct(std::move(values));
  }

  nsCOMPtr<nsISessionStoreFunctions> funcs =
      do_ImportModule("resource://gre/modules/SessionStoreFunctions.jsm");
  NS_ENSURE_TRUE(funcs, false);
  nsCOMPtr<nsIXPConnectWrappedJS> wrapped = do_QueryInterface(funcs);
  AutoJSAPI jsapi;
  MOZ_ALWAYS_TRUE(jsapi.Init(wrapped->GetJSObjectGlobal()));
  JS::Rooted<JS::Value> dataVal(jsapi.cx());
  bool ok = ToJSValue(jsapi.cx(), data, &dataVal);
  NS_ENSURE_TRUE(ok, false);

  nsresult rv = funcs->UpdateSessionStore(
      mOwnerContent, aFlushId, aIsFinal, mEpoch, dataVal,
      mSessionStore->GetAndClearSHistoryChanged());
  NS_ENSURE_SUCCESS(rv, false);
  StopTimerForUpdate();
  return true;
}

void TabListener::ResetStorageChangeListener() {
  if (mStorageChangeListenerRegistered) {
    return;
  }

  nsCOMPtr<EventTarget> eventTarget = GetEventTarget();
  if (!eventTarget) {
    return;
  }
  eventTarget->AddSystemEventListener(
      NS_LITERAL_STRING("MozSessionStorageChanged"), this, false);
  mStorageChangeListenerRegistered = true;
}

void TabListener::RemoveStorageChangeListener() {
  if (!mStorageChangeListenerRegistered) {
    return;
  }

  nsCOMPtr<EventTarget> eventTarget = GetEventTarget();
  if (eventTarget) {
    eventTarget->RemoveSystemEventListener(
        NS_LITERAL_STRING("MozSessionStorageChanged"), this, false);
    mStorageChangeListenerRegistered = false;
  }
}

void TabListener::RemoveListeners() {
  if (mProgressListenerRegistered) {
    nsCOMPtr<nsIWebProgress> webProgress = do_QueryInterface(mDocShell);
    if (webProgress) {
      webProgress->RemoveProgressListener(this);
      mProgressListenerRegistered = false;
    }
  }

  if (mEventListenerRegistered || mStorageChangeListenerRegistered) {
    nsCOMPtr<EventTarget> eventTarget = GetEventTarget();
    if (eventTarget) {
      if (mEventListenerRegistered) {
        eventTarget->RemoveSystemEventListener(
            NS_LITERAL_STRING("mozvisualscroll"), this, false);
        eventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("input"), this,
                                               false);
        if (mSHistoryInParent) {
          eventTarget->RemoveSystemEventListener(
              NS_LITERAL_STRING("DOMTitleChanged"), this, false);
        }
        mEventListenerRegistered = false;
      }
      if (mStorageChangeListenerRegistered) {
        eventTarget->RemoveSystemEventListener(
            NS_LITERAL_STRING("MozSessionStorageChanged"), this, false);
        mStorageChangeListenerRegistered = false;
      }
    }
  }

  if (mPrefObserverRegistered || mStorageObserverRegistered) {
    nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
    if (!obs) {
      return;
    }
    if (mPrefObserverRegistered) {
      obs->RemoveObserver(this, kTimeOutDisable);
      obs->RemoveObserver(this, kPrefInterval);
      mPrefObserverRegistered = false;
    }
    if (mStorageObserverRegistered) {
      obs->RemoveObserver(this, "browser:purge-sessionStorage");
      mStorageObserverRegistered = false;
    }
  }
}

TabListener::~TabListener() { RemoveListeners(); }