diff --git a/AUTHORS b/AUTHORS
index 3c996511..6714e69 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1094,3 +1094,4 @@
 Vivaldi Technologies AS <*@vivaldi.com>
 Yandex LLC <*@yandex-team.ru>
 Make Positive Provar Limited <*@provartesting.com>
+Jiaxun Wei <leuisken@gmail.com>
diff --git a/DEPS b/DEPS
index 4a99101d..24e4304 100644
--- a/DEPS
+++ b/DEPS
@@ -162,11 +162,11 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling Skia
   # and whatever else without interference from each other.
-  'skia_revision': '18531cde2ab757d82d3934fbac6c698e7b53cb3b',
+  'skia_revision': '9a8b846baf43752fa8cddbfa04b19b7707580d43',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling V8
   # and whatever else without interference from each other.
-  'v8_revision': 'f1aa36df853b9956b46f3d792b59255c3b6fff46',
+  'v8_revision': '0979c288600704fc58a7967a14fd71dea6cffe74',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling swarming_client
   # and whatever else without interference from each other.
@@ -174,7 +174,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling ANGLE
   # and whatever else without interference from each other.
-  'angle_revision': '17eaec1dd6fff05818d40b3d0e630b4b798c1123',
+  'angle_revision': 'e6582161b04beaa368f3081897912ede89d7800d',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling SwiftShader
   # and whatever else without interference from each other.
@@ -225,7 +225,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling catapult
   # and whatever else without interference from each other.
-  'catapult_revision': '033994d4a3bf0615cdc0892d1745835dbe0827f6',
+  'catapult_revision': '2ad535693f0fc84a0d97883caf5214d8bfed6889',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling libFuzzer
   # and whatever else without interference from each other.
@@ -293,11 +293,11 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling feed
   # and whatever else without interference from each other.
-  'shaderc_revision': '5903ef1f95a0acdbbd3ae645af1a6d6b30320f10',
+  'shaderc_revision': '68b6857ac09df396b51c740876654e9efca97f53',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling feed
   # and whatever else without interference from each other.
-  'dawn_revision': '785ec66b66a3577e4f17306a10ab30b7f92c49ae',
+  'dawn_revision': 'ae4dbeb178420e4088153069c2d6184b34d4d394',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling feed
   # and whatever else without interference from each other.
@@ -853,7 +853,7 @@
 
   # Build tools for Chrome OS. Note: This depends on third_party/pyelftools.
   'src/third_party/chromite': {
-      'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'fc8396f2c0eeeb8a295be6e4519a8e2a70d313e1',
+      'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '88b2cf90060b01ba5fea18028226d36d812fe912',
       'condition': 'checkout_linux',
   },
 
@@ -1425,7 +1425,7 @@
     Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'f4ddbafcf24befc473497eaa0d83016baafdff52',
 
   'src/third_party/webrtc':
-    Var('webrtc_git') + '/src.git' + '@' + '6ed60e39dc5f3140637ce9f4e438ea07d82d6f4c',
+    Var('webrtc_git') + '/src.git' + '@' + 'f0be5b53808e2f2d1ba8616ef21fd596a20037e2',
 
   'src/third_party/xdg-utils': {
       'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d',
@@ -1487,7 +1487,7 @@
     Var('chromium_git') + '/v8/v8.git' + '@' +  Var('v8_revision'),
 
   'src-internal': {
-    'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@b1ba053d48b780119b0683308bdd106ca35ee62e',
+    'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@244590c778649a4589ef937ddb7dd24f57465913',
     'condition': 'checkout_src_internal',
   },
 
diff --git a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java
index 1f93921..443f0cd 100644
--- a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java
+++ b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java
@@ -106,7 +106,8 @@
         final boolean ignoreVisibilityForImportance = true;
         ChildProcessCreationParams.set(getWebViewPackageName(), isExternalService,
                 LibraryProcessType.PROCESS_WEBVIEW_CHILD, bindToCaller,
-                ignoreVisibilityForImportance);
+                ignoreVisibilityForImportance, null /* privilegedServicesName */,
+                null /* sandboxedServicesName */);
     }
 
     /**
diff --git a/android_webview/tools/system_webview_shell/apk/src/org/chromium/webview_shell/WebPlatformTestsActivity.java b/android_webview/tools/system_webview_shell/apk/src/org/chromium/webview_shell/WebPlatformTestsActivity.java
index eab683e..fcb78142 100644
--- a/android_webview/tools/system_webview_shell/apk/src/org/chromium/webview_shell/WebPlatformTestsActivity.java
+++ b/android_webview/tools/system_webview_shell/apk/src/org/chromium/webview_shell/WebPlatformTestsActivity.java
@@ -164,6 +164,7 @@
         settings.setSupportMultipleWindows(true);
         // Respect "viewport" HTML meta tag. This is false by default, but set to false to be clear.
         settings.setUseWideViewPort(false);
+        settings.setDomStorageEnabled(true);
     }
 
     private void setUpMainWebView(String url) {
diff --git a/ash/app_list/app_list_controller_impl.cc b/ash/app_list/app_list_controller_impl.cc
index 61d2527..fd2a91b 100644
--- a/ash/app_list/app_list_controller_impl.cc
+++ b/ash/app_list/app_list_controller_impl.cc
@@ -120,6 +120,19 @@
       Shell::Get()->session_controller()->GetLastActiveUserPrefService();
   prefs->SetBoolean(prefs::kAssistantPrivacyInfoDismissedInLauncher, true);
 }
+
+// Whether a window will be shown over the applist when shown in tablet mode.
+bool HasVisibleWindows() {
+  std::vector<aura::Window*> window_list =
+      ash::Shell::Get()->mru_window_tracker()->BuildMruWindowList(
+          ash::DesksMruType::kActiveDesk);
+  for (auto* window : window_list) {
+    if (window->TargetVisibility())
+      return true;
+  }
+  return false;
+}
+
 }  // namespace
 
 AppListControllerImpl::AppListControllerImpl()
@@ -444,6 +457,10 @@
   return presenter_.GetWindow();
 }
 
+bool AppListControllerImpl::IsVisible() {
+  return last_visible_;
+}
+
 ////////////////////////////////////////////////////////////////////////////////
 // app_list::AppListModelObserver:
 
@@ -514,11 +531,7 @@
 // Methods used in Ash
 
 bool AppListControllerImpl::GetTargetVisibility() const {
-  return presenter_.GetTargetVisibility();
-}
-
-bool AppListControllerImpl::IsVisible() const {
-  return presenter_.IsVisible();
+  return last_target_visible_;
 }
 
 void AppListControllerImpl::Show(int64_t display_id,
@@ -857,8 +870,7 @@
   app_list::RecordAppListAppLaunched(
       AppListLaunchedFrom::kLaunchedFromShelf,
       recorded_app_list_view_state.value_or(GetAppListViewState()),
-      IsTabletMode(),
-      recorded_home_launcher_shown.value_or(presenter_.home_launcher_shown()));
+      IsTabletMode(), recorded_home_launcher_shown.value_or(last_visible_));
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -1200,7 +1212,7 @@
     app_list::AppLaunchedMetricParams* metric_params) {
   metric_params->app_list_view_state = GetAppListViewState();
   metric_params->is_tablet_mode = IsTabletMode();
-  metric_params->home_launcher_shown = presenter_.home_launcher_shown();
+  metric_params->home_launcher_shown = last_visible_;
 }
 
 gfx::Rect AppListControllerImpl::SnapBoundsToDisplayEdge(
@@ -1214,8 +1226,7 @@
 void AppListControllerImpl::RecordAppLaunched(
     AppListLaunchedFrom launched_from) {
   app_list::RecordAppListAppLaunched(launched_from, GetAppListViewState(),
-                                     IsTabletMode(),
-                                     presenter_.home_launcher_shown());
+                                     IsTabletMode(), last_visible_);
 }
 
 void AppListControllerImpl::AddObserver(AppListControllerObserver* observer) {
@@ -1229,7 +1240,28 @@
 
 void AppListControllerImpl::NotifyAppListVisibilityChanged(bool visible,
                                                            int64_t display_id) {
-  if (!visible) {
+  const bool is_home_launcher = IsTabletMode();
+
+  bool real_visibility = visible;
+  if (is_home_launcher) {
+    // HomeLauncher is only visible when no other app windows are visible.
+    real_visibility &= !HasVisibleWindows();
+  }
+
+  DCHECK_EQ(last_target_visible_, real_visibility)
+      << "Visibility notifications should follow target visibility "
+         "notifications.";
+
+  // Skip adjacent same changes.
+  if (last_visible_ == real_visibility &&
+      last_visible_display_id_ == display_id) {
+    return;
+  }
+
+  last_visible_ = real_visibility;
+  last_visible_display_id_ = display_id;
+
+  if (!real_visibility) {
     presenter_.GetView()
         ->search_box_view()
         ->ClearSearchAndDeactivateSearchBox();
@@ -1237,16 +1269,35 @@
 
   // Notify chrome of visibility changes.
   if (client_)
-    client_->OnAppListVisibilityChanged(visible);
+    client_->OnAppListVisibilityChanged(real_visibility);
 
   for (auto& observer : observers_)
-    observer.OnAppListVisibilityChanged(visible, display_id);
+    observer.OnAppListVisibilityChanged(real_visibility, display_id);
 }
 
-void AppListControllerImpl::NotifyAppListTargetVisibilityChanged(bool visible) {
+void AppListControllerImpl::NotifyAppListTargetVisibilityChanged(
+    bool visible,
+    int64_t display_id) {
+  const bool is_home_launcher = IsTabletMode();
+
+  bool real_target_visibility = visible;
+  if (is_home_launcher) {
+    // HomeLauncher is only visible when no other app windows are visible.
+    real_target_visibility &= !HasVisibleWindows();
+  }
+
+  // Skip adjacent same changes.
+  if (last_target_visible_ == real_target_visibility &&
+      last_target_visible_display_id_ == display_id) {
+    return;
+  }
+
+  last_target_visible_ = real_target_visibility;
+  last_target_visible_display_id_ = display_id;
+
   // Notify chrome of target visibility changes.
   if (client_)
-    client_->OnAppListTargetVisibilityChanged(visible);
+    client_->OnAppListTargetVisibilityChanged(real_target_visibility);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
diff --git a/ash/app_list/app_list_controller_impl.h b/ash/app_list/app_list_controller_impl.h
index 2e146f1..0ab8289e 100644
--- a/ash/app_list/app_list_controller_impl.h
+++ b/ash/app_list/app_list_controller_impl.h
@@ -33,6 +33,7 @@
 #include "ash/wm/overview/overview_observer.h"
 #include "base/observer_list.h"
 #include "components/sync/model/string_ordinal.h"
+#include "ui/display/types/display_constants.h"
 
 class PrefRegistrySimple;
 
@@ -120,11 +121,11 @@
   void ResolveOemFolderPosition(
       const syncer::StringOrdinal& preferred_oem_position,
       ResolveOemFolderPositionCallback callback) override;
-
   void DismissAppList() override;
   void GetAppInfoDialogBounds(GetAppInfoDialogBoundsCallback callback) override;
   void ShowAppList() override;
   aura::Window* GetWindow() override;
+  bool IsVisible() override;
 
   // app_list::AppListModelObserver:
   void OnAppListItemAdded(app_list::AppListItem* item) override;
@@ -138,7 +139,6 @@
 
   // Methods used in ash:
   bool GetTargetVisibility() const;
-  bool IsVisible() const;
   void Show(int64_t display_id,
             app_list::AppListShowSource show_source,
             base::TimeTicks event_time_stamp);
@@ -215,9 +215,9 @@
   void AddObserver(AppListControllerObserver* observer);
   void RemoveObserver(AppListControllerObserver* obsever);
 
-  // AppList visibility announcements are for clamshell mode AppList.
+  // Notifies observers of AppList visibility changes.
   void NotifyAppListVisibilityChanged(bool visible, int64_t display_id);
-  void NotifyAppListTargetVisibilityChanged(bool visible);
+  void NotifyAppListTargetVisibilityChanged(bool visible, int64_t display_id);
 
   // ShellObserver:
   void OnShelfAlignmentChanged(aura::Window* root_window) override;
@@ -374,6 +374,14 @@
   // Whether to immediately dismiss the AppListView.
   bool should_dismiss_immediately_ = false;
 
+  // The last target visibility change and its display id.
+  bool last_target_visible_ = false;
+  int64_t last_target_visible_display_id_ = display::kInvalidDisplayId;
+
+  // The last visibility change and its display id.
+  bool last_visible_ = false;
+  int64_t last_visible_display_id_ = display::kInvalidDisplayId;
+
   // Used in mojo callings to specify the profile whose app list data is
   // read/written by Ash side through IPC. Notice that in multi-profile mode,
   // each profile has its own AppListModelUpdater to manipulate app list items.
diff --git a/ash/app_list/app_list_controller_impl_unittest.cc b/ash/app_list/app_list_controller_impl_unittest.cc
index 5427acf..1ec031ae 100644
--- a/ash/app_list/app_list_controller_impl_unittest.cc
+++ b/ash/app_list/app_list_controller_impl_unittest.cc
@@ -19,6 +19,7 @@
 #include "ash/public/cpp/presentation_time_recorder.h"
 #include "ash/public/cpp/shelf_types.h"
 #include "ash/shelf/shelf.h"
+#include "ash/shelf/shelf_layout_manager.h"
 #include "ash/shelf/shelf_widget.h"
 #include "ash/shell.h"
 #include "ash/system/unified/unified_system_tray_test_api.h"
@@ -730,6 +731,9 @@
   EXPECT_FALSE(IsTabletMode());
   base::RunLoop().RunUntilIdle();
   EXPECT_EQ(AppListViewState::kClosed, GetAppListView()->app_list_state());
+  EXPECT_FALSE(AshTestBase::GetPrimaryShelf()
+                   ->shelf_layout_manager()
+                   ->is_app_list_visible());
 
   // Check metrics initial values.
   histogram_tester_.ExpectTotalCount(
@@ -750,7 +754,6 @@
   ui::test::EventGenerator* generator = GetEventGenerator();
   generator->GestureScrollSequence(shelf_center, target_point,
                                    base::TimeDelta::FromMicroseconds(500), 1);
-  base::RunLoop().RunUntilIdle();
   EXPECT_EQ(AppListViewState::kFullscreenAllApps,
             GetAppListView()->app_list_state());
   histogram_tester_.ExpectTotalCount(
diff --git a/ash/app_list/app_list_controller_observer.h b/ash/app_list/app_list_controller_observer.h
index 920e69b..c98dec9 100644
--- a/ash/app_list/app_list_controller_observer.h
+++ b/ash/app_list/app_list_controller_observer.h
@@ -12,7 +12,11 @@
 
 class ASH_EXPORT AppListControllerObserver : public base::CheckedObserver {
  public:
-  // Called when the AppList is shown or dismissed.
+  // Called when the AppList target visibility changes.
+  virtual void OnAppListTargetVisibilityChanged(bool shown,
+                                                int64_t display_id) {}
+
+  // Called when the AppList visibility changes.
   virtual void OnAppListVisibilityChanged(bool shown, int64_t display_id) {}
 };
 
diff --git a/ash/app_list/app_list_presenter_delegate_impl.cc b/ash/app_list/app_list_presenter_delegate_impl.cc
index 3214475..fcebf2f2 100644
--- a/ash/app_list/app_list_presenter_delegate_impl.cc
+++ b/ash/app_list/app_list_presenter_delegate_impl.cc
@@ -162,8 +162,14 @@
   controller_->NotifyAppListVisibilityChanged(visible, display_id);
 }
 
-void AppListPresenterDelegateImpl::OnTargetVisibilityChanged(bool visible) {
-  controller_->NotifyAppListTargetVisibilityChanged(visible);
+void AppListPresenterDelegateImpl::OnTargetVisibilityChanged(
+    bool visible,
+    int64_t display_id) {
+  controller_->NotifyAppListTargetVisibilityChanged(visible, display_id);
+}
+
+bool AppListPresenterDelegateImpl::IsVisible() {
+  return controller_->IsVisible();
 }
 
 void AppListPresenterDelegateImpl::OnDisplayMetricsChanged(
@@ -290,7 +296,7 @@
     return;
 
   // If the home launcher is not shown in tablet mode, ignore events.
-  if (IsTabletMode() && !presenter_->home_launcher_shown())
+  if (IsTabletMode() && !IsVisible())
     return;
 
   // Don't absorb the first event for the search box while it is open
diff --git a/ash/app_list/app_list_presenter_delegate_impl.h b/ash/app_list/app_list_presenter_delegate_impl.h
index b7ba202..2eaed5a 100644
--- a/ash/app_list/app_list_presenter_delegate_impl.h
+++ b/ash/app_list/app_list_presenter_delegate_impl.h
@@ -55,8 +55,8 @@
   bool GetOnScreenKeyboardShown() override;
   aura::Window* GetRootWindowForDisplayId(int64_t display_id) override;
   void OnVisibilityChanged(bool visible, int64_t display_id) override;
-  void OnTargetVisibilityChanged(bool visible) override;
-
+  void OnTargetVisibilityChanged(bool visible, int64_t display_id) override;
+  bool IsVisible() override;
   // DisplayObserver overrides:
   void OnDisplayMetricsChanged(const display::Display& display,
                                uint32_t changed_metrics) override;
diff --git a/ash/app_list/app_list_presenter_delegate_unittest.cc b/ash/app_list/app_list_presenter_delegate_unittest.cc
index a7e978bc..031937f 100644
--- a/ash/app_list/app_list_presenter_delegate_unittest.cc
+++ b/ash/app_list/app_list_presenter_delegate_unittest.cc
@@ -59,6 +59,7 @@
 #include "ui/aura/client/aura_constants.h"
 #include "ui/aura/test/test_windows.h"
 #include "ui/aura/window.h"
+#include "ui/base/ui_base_types.h"
 #include "ui/compositor/scoped_animation_duration_scale_mode.h"
 #include "ui/display/display.h"
 #include "ui/display/manager/display_manager.h"
@@ -66,6 +67,7 @@
 #include "ui/display/test/display_manager_test_api.h"
 #include "ui/events/test/event_generator.h"
 #include "ui/views/controls/textfield/textfield.h"
+#include "ui/wm/core/window_util.h"
 
 namespace ash {
 namespace {
@@ -895,7 +897,8 @@
             shelf_layout_manager->GetShelfBackgroundType());
 }
 
-// Tests the shelf background type is as expected when in tablet mode.
+// Tests the shelf background type is as expected when a window is created after
+// going to tablet mode.
 TEST_F(AppListPresenterDelegateTest, ShelfBackgroundWithHomeLauncher) {
   // Enter tablet mode to display the home launcher.
   GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId());
@@ -908,6 +911,7 @@
 
   // Add a window. It should be maximized because it is in tablet mode.
   auto window = CreateTestWindow();
+  wm::ActivateWindow(window.get());
   EXPECT_EQ(ShelfBackgroundType::SHELF_BACKGROUND_MAXIMIZED,
             shelf_layout_manager->GetShelfBackgroundType());
 }
@@ -2625,7 +2629,7 @@
   GetAppListTestHelper()->CheckVisibility(true);
 }
 
-// Tests that moving focus outside app list window cannot dismiss it.
+// Tests that moving focus outside app list window can dismiss it.
 TEST_F(AppListPresenterDelegateHomeLauncherTest, FocusOutToDismiss) {
   // Show app list in non-tablet mode. Move focus to another window.
   GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId());
@@ -2635,10 +2639,21 @@
   GetAppListTestHelper()->WaitUntilIdle();
   GetAppListTestHelper()->CheckVisibility(false);
 
-  // Show app list in tablet mode. Move focus to another window.
+  // Go to tablet mode with a focused window, the AppList should not be visible.
   EnableTabletMode(true);
-  GetAppListTestHelper()->CheckVisibility(true);
+  GetAppListTestHelper()->WaitUntilIdle();
+  GetAppListTestHelper()->CheckVisibility(false);
+
+  // Refocusing the already focused window should change nothing.
   wm::ActivateWindow(window.get());
+
+  GetAppListTestHelper()->WaitUntilIdle();
+  GetAppListTestHelper()->CheckVisibility(false);
+
+  // Minimizing the focused window with no remaining windows should result in a
+  // shown applist.
+  window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED);
+
   GetAppListTestHelper()->WaitUntilIdle();
   GetAppListTestHelper()->CheckVisibility(true);
 }
@@ -2761,27 +2776,24 @@
        VisibilityDuringWallpaperPreview) {
   WallpaperControllerTestApi wallpaper_test_api(
       Shell::Get()->wallpaper_controller());
-  std::unique_ptr<aura::Window> wallpaper_picker_window(
-      CreateTestWindow(gfx::Rect(0, 0, 100, 100)));
 
   // The app list is hidden in the beginning.
   GetAppListTestHelper()->CheckVisibility(false);
   // Open wallpaper picker and start preview. Verify the app list remains
   // hidden.
-  WindowState::Get(wallpaper_picker_window.get())->Activate();
   wallpaper_test_api.StartWallpaperPreview();
   GetAppListTestHelper()->CheckVisibility(false);
   // Enable tablet mode. Verify the app list is still hidden because wallpaper
   // preview is active.
   EnableTabletMode(true);
-  EXPECT_FALSE(GetAppListView()->GetWidget()->IsVisible());
+  GetAppListTestHelper()->CheckVisibility(false);
   // End preview by confirming the wallpaper. Verify the app list is shown.
   wallpaper_test_api.EndWallpaperPreview(true /*confirm_preview_wallpaper=*/);
   GetAppListTestHelper()->CheckVisibility(true);
 
   // Start preview again. Verify the app list is hidden.
   wallpaper_test_api.StartWallpaperPreview();
-  EXPECT_FALSE(GetAppListView()->GetWidget()->IsVisible());
+  GetAppListTestHelper()->CheckVisibility(false);
   // End preview by canceling the wallpaper. Verify the app list is shown.
   wallpaper_test_api.EndWallpaperPreview(false /*confirm_preview_wallpaper=*/);
   GetAppListTestHelper()->CheckVisibility(true);
@@ -2793,12 +2805,12 @@
   OverviewController* overview_controller = Shell::Get()->overview_controller();
   overview_controller->StartOverview();
   EXPECT_TRUE(overview_controller->InOverviewSession());
-  EXPECT_FALSE(GetAppListView()->GetWidget()->IsVisible());
+  GetAppListTestHelper()->CheckVisibility(false);
   // Disable overview mode. Verify the app list is still hidden because
   // wallpaper preview is still active.
   overview_controller->EndOverview();
   EXPECT_FALSE(overview_controller->InOverviewSession());
-  EXPECT_FALSE(GetAppListView()->GetWidget()->IsVisible());
+  GetAppListTestHelper()->CheckVisibility(false);
   // End preview by confirming the wallpaper. Verify the app list is shown.
   wallpaper_test_api.EndWallpaperPreview(true /*confirm_preview_wallpaper=*/);
   GetAppListTestHelper()->CheckVisibility(true);
@@ -3006,7 +3018,7 @@
   std::unique_ptr<aura::Window> non_fullscreen_window(
       CreateTestWindow(gfx::Rect(0, 0, 100, 100)));
   non_fullscreen_window->Show();
-  GetAppListTestHelper()->CheckVisibility(true);
+  GetAppListTestHelper()->CheckVisibility(false);
   EXPECT_TRUE(test_helper.GetBackdropWindow());
 }
 
@@ -3035,7 +3047,7 @@
 
   // Show app list in tablet mode. It should not be active.
   EnableTabletMode(true);
-  GetAppListTestHelper()->CheckVisibility(true);
+  GetAppListTestHelper()->CheckVisibility(false);
   EXPECT_EQ(window.get(), window_util::GetActiveWindow());
 }
 
diff --git a/ash/app_list/presenter/app_list_presenter_delegate.h b/ash/app_list/presenter/app_list_presenter_delegate.h
index cf52acb..0350e52 100644
--- a/ash/app_list/presenter/app_list_presenter_delegate.h
+++ b/ash/app_list/presenter/app_list_presenter_delegate.h
@@ -57,7 +57,10 @@
   virtual void OnVisibilityChanged(bool visible, int64_t display_id) = 0;
 
   // Called when the app list target visibility changes.
-  virtual void OnTargetVisibilityChanged(bool visible) = 0;
+  virtual void OnTargetVisibilityChanged(bool visible, int64_t display_id) = 0;
+
+  // Whether the AppList is visible.
+  virtual bool IsVisible() = 0;
 };
 
 }  // namespace app_list
diff --git a/ash/app_list/presenter/app_list_presenter_impl.cc b/ash/app_list/presenter/app_list_presenter_impl.cc
index 112ea5b..94f1ce94 100644
--- a/ash/app_list/presenter/app_list_presenter_impl.cc
+++ b/ash/app_list/presenter/app_list_presenter_impl.cc
@@ -98,6 +98,7 @@
   }
 
   is_target_visibility_show_ = true;
+  NotifyTargetVisibilityChanged(GetTargetVisibility(), display_id);
   RequestPresentationTime(display_id, event_time_stamp);
 
   if (!view_) {
@@ -107,10 +108,7 @@
     SetView(view);
   }
   delegate_->ShowForDisplay(display_id);
-  if (delegate_->IsTabletMode())
-    home_launcher_shown_ = true;
 
-  NotifyTargetVisibilityChanged(GetTargetVisibility());
   NotifyVisibilityChanged(GetTargetVisibility(), display_id);
 }
 
@@ -154,9 +152,9 @@
     view_->GetWidget()->Deactivate();
 
   delegate_->OnClosing();
-  view_->SetState(ash::AppListViewState::kClosed);
 
-  NotifyTargetVisibilityChanged(GetTargetVisibility());
+  NotifyTargetVisibilityChanged(GetTargetVisibility(), GetDisplayId());
+  view_->SetState(ash::AppListViewState::kClosed);
   base::RecordAction(base::UserMetricsAction("Launcher_Dismiss"));
 }
 
@@ -196,7 +194,7 @@
 }
 
 bool AppListPresenterImpl::IsVisible() const {
-  return view_ && view_->GetWidget()->IsVisible();
+  return delegate_->IsVisible();
 }
 
 bool AppListPresenterImpl::GetTargetVisibility() const {
@@ -297,17 +295,11 @@
 
 void AppListPresenterImpl::OnTabletModeChanged(bool started) {
   if (started) {
-    if (GetTargetVisibility()) {
-      DCHECK(IsVisible());
+    if (GetTargetVisibility())
       view_->OnTabletModeChanged(true);
-    }
-    // The AppList widget is shown without being focused in tablet mode, so
-    // check for visibility, not focus.
-    home_launcher_shown_ = GetWindow() && GetWindow()->IsVisible();
   } else {
     if (IsVisible())
       view_->OnTabletModeChanged(false);
-    home_launcher_shown_ = false;
   }
 }
 
@@ -354,23 +346,12 @@
 
 void AppListPresenterImpl::NotifyVisibilityChanged(bool visible,
                                                    int64_t display_id) {
-  // Skip adjacent same changes.
-  if (last_visible_ == visible && last_display_id_ == display_id)
-    return;
-  last_visible_ = visible;
-  last_display_id_ = display_id;
-
-  // Notify the Shell and its observers of the app list visibility change.
   delegate_->OnVisibilityChanged(visible, display_id);
 }
 
-void AppListPresenterImpl::NotifyTargetVisibilityChanged(bool visible) {
-  // Skip adjacent same changes.
-  if (last_target_visible_ == visible)
-    return;
-  last_target_visible_ = visible;
-
-  delegate_->OnTargetVisibilityChanged(visible);
+void AppListPresenterImpl::NotifyTargetVisibilityChanged(bool visible,
+                                                         int64_t display_id) {
+  delegate_->OnTargetVisibilityChanged(visible, display_id);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -389,14 +370,14 @@
 
     if (delegate_->IsTabletMode()) {
       const bool is_shown = !app_list_lost_focus;
-      if (is_shown != home_launcher_shown_) {
-        home_launcher_shown_ = is_shown;
-        if (home_launcher_shown_)
+      if (is_shown != delegate_->IsVisible()) {
+        if (is_shown)
           view_->OnHomeLauncherGainingFocusWithoutAnimation();
         else
           HandleCloseOpenSearchBox();
 
-        NotifyVisibilityChanged(home_launcher_shown_, GetDisplayId());
+        NotifyTargetVisibilityChanged(is_shown, GetDisplayId());
+        NotifyVisibilityChanged(is_shown, GetDisplayId());
       }
     }
 
@@ -445,6 +426,7 @@
 void AppListPresenterImpl::OnWidgetVisibilityChanged(views::Widget* widget,
                                                      bool visible) {
   DCHECK_EQ(view_->GetWidget(), widget);
+  NotifyTargetVisibilityChanged(visible, GetDisplayId());
   NotifyVisibilityChanged(visible, GetDisplayId());
 }
 
diff --git a/ash/app_list/presenter/app_list_presenter_impl.h b/ash/app_list/presenter/app_list_presenter_impl.h
index d709d34..c1919a9 100644
--- a/ash/app_list/presenter/app_list_presenter_impl.h
+++ b/ash/app_list/presenter/app_list_presenter_impl.h
@@ -36,10 +36,10 @@
 // animation. While the UI is visible, it monitors things such as app list
 // activation state to auto dismiss the UI.
 class APP_LIST_PRESENTER_EXPORT AppListPresenterImpl
-    : public aura::client::FocusChangeObserver,
+    : public ash::PaginationModelObserver,
+      public aura::client::FocusChangeObserver,
       public ui::ImplicitAnimationObserver,
-      public views::WidgetObserver,
-      public ash::PaginationModelObserver {
+      public views::WidgetObserver {
  public:
   // Callback which fills out the passed settings object. Used by
   // UpdateYPositionAndOpacityForHomeLauncher so different callers can do
@@ -121,9 +121,6 @@
   // Called when tablet mode starts and ends.
   void OnTabletModeChanged(bool started);
 
-  // Returns whether home launcher is currently shown.
-  bool home_launcher_shown() const { return home_launcher_shown_; }
-
  private:
   // Sets the app list view and attempts to show it.
   void SetView(AppListView* view);
@@ -136,10 +133,7 @@
   int64_t GetDisplayId();
 
   void NotifyVisibilityChanged(bool visible, int64_t display_id);
-  void NotifyTargetVisibilityChanged(bool visible);
-  void NotifyHomeLauncherTargetPositionChanged(bool showing,
-                                               int64_t display_id);
-  void NotifyHomeLauncherAnimationComplete(bool shown, int64_t display_id);
+  void NotifyTargetVisibilityChanged(bool visible, int64_t display_id);
 
   // aura::client::FocusChangeObserver overrides:
   void OnWindowFocused(aura::Window* gained_focus,
@@ -179,19 +173,6 @@
   // Cached bounds of |view_| for snapping back animation after over-scroll.
   gfx::Rect view_bounds_;
 
-  // The last target visibility change.
-  bool last_target_visible_ = false;
-
-  // The last visibility change and its display id.
-  bool last_visible_ = false;
-  int64_t last_display_id_ = display::kInvalidDisplayId;
-
-  // If true, dismiss the app list immediately.
-  bool dismiss_without_animation_ = false;
-
-  // Whether the home launcher is currently shown.
-  bool home_launcher_shown_ = false;
-
   DISALLOW_COPY_AND_ASSIGN(AppListPresenterImpl);
 };
 
diff --git a/ash/app_list/presenter/app_list_presenter_impl_unittest.cc b/ash/app_list/presenter/app_list_presenter_impl_unittest.cc
index 6a3dc0a..943226fd 100644
--- a/ash/app_list/presenter/app_list_presenter_impl_unittest.cc
+++ b/ash/app_list/presenter/app_list_presenter_impl_unittest.cc
@@ -60,7 +60,8 @@
     return container_->GetRootWindow();
   }
   void OnVisibilityChanged(bool visible, int64_t display_id) override {}
-  void OnTargetVisibilityChanged(bool visible) override {}
+  void OnTargetVisibilityChanged(bool visible, int64_t display_id) override {}
+  bool IsVisible() override { return false; }
 
  private:
   aura::Window* container_;
diff --git a/ash/assistant/ui/main_stage/animated_container_view.cc b/ash/assistant/ui/main_stage/animated_container_view.cc
index f57b2f6..034e2c3 100644
--- a/ash/assistant/ui/main_stage/animated_container_view.cc
+++ b/ash/assistant/ui/main_stage/animated_container_view.cc
@@ -113,6 +113,10 @@
 }
 
 void AnimatedContainerView::FadeOutViews() {
+  // If there's already an animation in progress, there's nothing for us to do.
+  if (fade_out_in_progress_)
+    return;
+
   // We don't allow processing of events while waiting for the next query
   // response. The contents will be faded out, so it should not be interactive.
   set_can_process_events_within_subtree(false);
diff --git a/ash/public/cpp/app_list/app_list_controller.h b/ash/public/cpp/app_list/app_list_controller.h
index 9b93d9a..a65ee04 100644
--- a/ash/public/cpp/app_list/app_list_controller.h
+++ b/ash/public/cpp/app_list/app_list_controller.h
@@ -170,6 +170,9 @@
   // Returns the app list window or nullptr if it is not visible.
   virtual aura::Window* GetWindow() = 0;
 
+  // Returns whether the AppList is visible.
+  virtual bool IsVisible() = 0;
+
  protected:
   AppListController();
   virtual ~AppListController();
diff --git a/ash/session/session_controller_impl.cc b/ash/session/session_controller_impl.cc
index 7de40e2..fef5776 100644
--- a/ash/session/session_controller_impl.cc
+++ b/ash/session/session_controller_impl.cc
@@ -392,7 +392,6 @@
   lock_state_controller->SetLockScreenDisplayedCallback(
       base::BindOnce(&SessionControllerImpl::OnLockAnimationFinished,
                      weak_ptr_factory_.GetWeakPtr()));
-  lock_state_controller->OnStartingLock();
 }
 
 void SessionControllerImpl::NotifyChromeLockAnimationsComplete() {
diff --git a/ash/shelf/shelf_layout_manager.cc b/ash/shelf/shelf_layout_manager.cc
index 87e2f6c8..30f9337 100644
--- a/ash/shelf/shelf_layout_manager.cc
+++ b/ash/shelf/shelf_layout_manager.cc
@@ -633,7 +633,7 @@
   if (IsHomeScreenAvailable()) {
     // If the home launcher is shown, being animated, or dragged, show the
     // default background.
-    if (is_home_launcher_shown_ || home_launcher_animation_state_ == kShowing)
+    if (is_app_list_visible_ || home_launcher_animation_state_ == kShowing)
       return SHELF_BACKGROUND_DEFAULT;
   } else if (is_app_list_visible_) {
     return maximized ? SHELF_BACKGROUND_MAXIMIZED_WITH_APP_LIST
@@ -785,6 +785,14 @@
   overview_suspend_visibility_update_.reset();
 }
 
+void ShelfLayoutManager::OnAppListTargetVisibilityChanged(bool shown,
+                                                          int64_t display_id) {
+  if (!IsTabletModeEnabled())
+    return;
+
+  OnHomeLauncherTargetPositionChanged(shown, display_id);
+}
+
 void ShelfLayoutManager::OnAppListVisibilityChanged(bool shown,
                                                     int64_t display_id) {
   // Shell may be under destruction.
@@ -795,8 +803,8 @@
     return;
 
   if (IsTabletModeEnabled()) {
-    is_home_launcher_shown_ = shown;
-    home_launcher_animation_state_ = HomeLauncherAnimationState::kFinished;
+    OnHomeLauncherAnimationComplete(shown, display_id);
+    return;
   }
 
   const bool should_update_visibility_state = shown != is_app_list_visible_;
@@ -811,6 +819,9 @@
 void ShelfLayoutManager::OnHomeLauncherTargetPositionChanged(
     bool showing,
     int64_t display_id) {
+  if (!IsTabletModeEnabled())
+    return;
+
   // Shell may be under destruction.
   if (!shelf_widget_ || !shelf_widget_->GetNativeWindow())
     return;
@@ -819,9 +830,9 @@
     return;
 
   HomeLauncherAnimationState new_animation_state;
-  if (is_home_launcher_shown_ && !showing) {
+  if (is_app_list_visible_ && !showing) {
     new_animation_state = kHiding;
-  } else if (!is_home_launcher_shown_ && showing) {
+  } else if (!is_app_list_visible_ && showing) {
     new_animation_state = kShowing;
   } else {
     // No valid animation state.
@@ -839,6 +850,9 @@
 
 void ShelfLayoutManager::OnHomeLauncherAnimationComplete(bool shown,
                                                          int64_t display_id) {
+  if (!IsTabletModeEnabled())
+    return;
+
   // Shell may be under destruction.
   if (!shelf_widget_ || !shelf_widget_->GetNativeWindow())
     return;
@@ -846,8 +860,8 @@
   if (display_.id() != display_id)
     return;
 
-  const bool should_update_visibility_state = is_home_launcher_shown_ != shown;
-  is_home_launcher_shown_ = shown;
+  const bool should_update_visibility_state = is_app_list_visible_ != shown;
+  is_app_list_visible_ = shown;
   home_launcher_animation_state_ = HomeLauncherAnimationState::kFinished;
 
   if (should_update_visibility_state)
@@ -1044,7 +1058,7 @@
         case kHiding:
           return HotseatState::kHidden;
         case kFinished:
-          if (is_home_launcher_shown_)
+          if (is_app_list_visible_)
             return HotseatState::kShown;
           if (Shell::Get()->overview_controller() &&
               Shell::Get()->overview_controller()->InOverviewSession()) {
@@ -1817,7 +1831,7 @@
     drag_status_ = previous_drag_status;
   }
 
-  if (is_home_launcher_shown_)
+  if (is_app_list_visible_)
     return true;
 
   return StartShelfDrag(gesture_in_screen);
diff --git a/ash/shelf/shelf_layout_manager.h b/ash/shelf/shelf_layout_manager.h
index 07adf81..717cdfcf 100644
--- a/ash/shelf/shelf_layout_manager.h
+++ b/ash/shelf/shelf_layout_manager.h
@@ -180,6 +180,8 @@
   void OnOverviewModeEndingAnimationComplete(bool canceled) override;
 
   // AppListControllerObserver:
+  void OnAppListTargetVisibilityChanged(bool shown,
+                                        int64_t display_id) override;
   void OnAppListVisibilityChanged(bool shown, int64_t display_id) override;
 
   // HomeLauncherGestureHandlerObserver:
@@ -227,6 +229,7 @@
   }
 
   bool updating_bounds() const { return updating_bounds_; }
+  bool is_app_list_visible() const { return is_app_list_visible_; }
   ShelfAutoHideState auto_hide_state() const { return state_.auto_hide_state; }
 
   // TODO(harrym|oshima): These templates will be moved to a new Shelf class.
@@ -457,15 +460,9 @@
   Shelf* shelf_;
 
   // Whether the app list is visible. This is maintained by
-  // OnAppListVisibilityChanged. Used to determine AppList visibility in
-  // clamshell mode.
+  // OnAppListVisibilityChanged and OnHomeLauncherAnimationComplete.
   bool is_app_list_visible_ = false;
 
-  // Whether the HomeLauncher is shown. This is maintained by
-  // OnHomeLauncherAnimationComplete. Used to determine AppList visibility in
-  // tablet mode.
-  bool is_home_launcher_shown_ = false;
-
   enum HomeLauncherAnimationState {
     kFinished,
     kShowing,
diff --git a/ash/shelf/shelf_layout_manager_unittest.cc b/ash/shelf/shelf_layout_manager_unittest.cc
index 4d43d91..107ee66 100644
--- a/ash/shelf/shelf_layout_manager_unittest.cc
+++ b/ash/shelf/shelf_layout_manager_unittest.cc
@@ -2412,7 +2412,7 @@
   window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED);
   EXPECT_EQ(SHELF_BACKGROUND_MAXIMIZED, GetShelfWidget()->GetBackgroundType());
 
-  Shell::Get()->lock_state_controller()->StartLockAnimationAndLockImmediately();
+  Shell::Get()->lock_state_controller()->LockWithoutAnimation();
   EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType());
 }
 
diff --git a/ash/shelf/shelf_view.cc b/ash/shelf/shelf_view.cc
index f2c3351..3608326 100644
--- a/ash/shelf/shelf_view.cc
+++ b/ash/shelf/shelf_view.cc
@@ -759,8 +759,8 @@
   // AppListViewState before the app was launched.
   recorded_app_list_view_state_ =
       Shell::Get()->app_list_controller()->GetAppListViewState();
-  recorded_home_launcher_shown_ =
-      Shell::Get()->app_list_controller()->presenter()->home_launcher_shown();
+  app_list_visibility_before_app_launch_ =
+      Shell::Get()->app_list_controller()->IsVisible();
 
   // Run AfterItemSelected directly if the item has no delegate (ie. in tests).
   const ShelfItem& item = model_->items()[last_pressed_index_];
@@ -2300,7 +2300,7 @@
   if (action == SHELF_ACTION_NEW_WINDOW_CREATED ||
       action == SHELF_ACTION_WINDOW_ACTIVATED) {
     Shell::Get()->app_list_controller()->RecordShelfAppLaunched(
-        recorded_app_list_view_state_, recorded_home_launcher_shown_);
+        recorded_app_list_view_state_, app_list_visibility_before_app_launch_);
   }
 
   // The app list handles its own ink drop effect state changes.
diff --git a/ash/shelf/shelf_view.h b/ash/shelf/shelf_view.h
index 2b0196f5..06e48c2 100644
--- a/ash/shelf/shelf_view.h
+++ b/ash/shelf/shelf_view.h
@@ -702,10 +702,10 @@
   // before AppListViewState changes.
   ash::AppListViewState recorded_app_list_view_state_;
 
-  // Whether home launcher was shown before a button press, used to record app
-  // launching metrics. This is recorded in case home_launcher_shown_ is changed
+  // Whether the applist was shown before a button press, used to record app
+  // launching metrics. This is recorded because AppList visibility can change
   // before the metric is recorded.
-  bool recorded_home_launcher_shown_ = false;
+  bool app_list_visibility_before_app_launch_ = false;
 
   // Whether this view should focus its last focusable child (instead of its
   // first) when focused.
diff --git a/ash/system/overview/overview_button_tray_unittest.cc b/ash/system/overview/overview_button_tray_unittest.cc
index 494cec4..43d84bb0 100644
--- a/ash/system/overview/overview_button_tray_unittest.cc
+++ b/ash/system/overview/overview_button_tray_unittest.cc
@@ -28,6 +28,7 @@
 #include "base/test/metrics/user_action_tester.h"
 #include "base/time/time.h"
 #include "ui/aura/client/aura_constants.h"
+#include "ui/aura/client/window_types.h"
 #include "ui/aura/window.h"
 #include "ui/compositor/layer_tree_owner.h"
 #include "ui/compositor/scoped_animation_duration_scale_mode.h"
@@ -357,12 +358,9 @@
 // tablet mode with a system modal window open, and that it hides once
 // the user exits tablet mode.
 TEST_F(OverviewButtonTrayTest, VisibilityChangesForSystemModalWindow) {
-  // TODO(jonross): When CreateTestWindow*() have been unified, use the
-  // appropriate method to replace this setup. (crbug.com/483503)
-  std::unique_ptr<aura::Window> window = window_factory::NewWindow();
+  std::unique_ptr<aura::Window> window =
+      CreateTestWindow(gfx::Rect(), aura::client::WINDOW_TYPE_NORMAL);
   window->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_SYSTEM);
-  window->SetType(aura::client::WINDOW_TYPE_NORMAL);
-  window->Init(ui::LAYER_TEXTURED);
   window->Show();
   ParentWindowInPrimaryRootWindow(window.get());
 
@@ -398,9 +396,10 @@
   // Splitview is only available in tablet mode.
   TabletModeControllerTestApi().EnterTabletMode();
 
+  // We want the order in the MRU list to be |window2|, |window1|, |window3|.
+  std::unique_ptr<aura::Window> window3 = CreateTestWindow();
   std::unique_ptr<aura::Window> window1 = CreateTestWindow();
   std::unique_ptr<aura::Window> window2 = CreateTestWindow();
-  std::unique_ptr<aura::Window> window3 = CreateTestWindow();
 
   // Enter splitview mode. Snap |window1| to the left, this will be the default
   // splitview window.
@@ -410,7 +409,6 @@
   split_view_controller->SnapWindow(window1.get(), SplitViewController::LEFT);
   split_view_controller->SnapWindow(window2.get(), SplitViewController::RIGHT);
   ASSERT_EQ(window1.get(), split_view_controller->GetDefaultSnappedWindow());
-  EXPECT_EQ(window2.get(), window_util::GetActiveWindow());
 
   // Verify that after double tapping, we have switched to |window3|, even
   // though |window1| is more recently used.
diff --git a/ash/wm/lock_state_controller.cc b/ash/wm/lock_state_controller.cc
index e9c15d1..cf9e05ce 100644
--- a/ash/wm/lock_state_controller.cc
+++ b/ash/wm/lock_state_controller.cc
@@ -61,12 +61,6 @@
 constexpr base::TimeDelta kLockFailTimeout =
     base::TimeDelta::FromSeconds(8 * kTimeoutMultiplier);
 
-// When the button has been held continuously from the unlocked state, amount of
-// time that we wait after the screen locker window is shown before starting the
-// pre-shutdown animation.
-constexpr base::TimeDelta kLockToShutdownTimeout =
-    base::TimeDelta::FromMilliseconds(150);
-
 // Additional time to wait after starting the fast-close shutdown animation
 // before actually requesting shutdown, to give the animation time to finish.
 constexpr base::TimeDelta kShutdownRequestDelay =
@@ -103,27 +97,28 @@
 void LockStateController::StartLockAnimation() {
   if (animating_lock_)
     return;
-  can_cancel_lock_animation_ = true;
 
-  StartCancellablePreLockAnimation();
-}
-
-void LockStateController::StartLockThenShutdownAnimation(
-    ShutdownReason shutdown_reason) {
-  shutdown_after_lock_ = true;
-  shutdown_reason_ = shutdown_reason;
-  StartLockAnimation();
+  animating_lock_ = true;
+  StoreUnlockedProperties();
+  VLOG(1) << "StartLockAnimation";
+  PreLockAnimation(SessionStateAnimator::ANIMATION_SPEED_UNDOABLE, true);
+  DispatchCancelMode();
+  OnLockStateEvent(LockStateObserver::EVENT_PRELOCK_ANIMATION_STARTED);
 }
 
 void LockStateController::StartShutdownAnimation(ShutdownReason reason) {
   shutdown_reason_ = reason;
-  StartCancellableShutdownAnimation();
-}
 
-void LockStateController::StartLockAnimationAndLockImmediately() {
-  if (animating_lock_)
-    return;
-  StartImmediatePreLockAnimation(true /* request_lock_on_completion */);
+  Shell* shell = Shell::Get();
+  // Hide cursor, but let it reappear if the mouse moves.
+  if (shell->cursor_manager())
+    shell->cursor_manager()->HideCursor();
+
+  animator_->StartAnimation(
+      SessionStateAnimator::ROOT_CONTAINER,
+      SessionStateAnimator::ANIMATION_GRAYSCALE_BRIGHTNESS,
+      SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN);
+  StartPreShutdownAnimationTimer();
 }
 
 void LockStateController::LockWithoutAnimation() {
@@ -146,34 +141,37 @@
   return shutting_down_;
 }
 
-bool LockStateController::CanCancelLockAnimation() {
-  return can_cancel_lock_animation_;
-}
-
 void LockStateController::CancelLockAnimation() {
-  if (!CanCancelLockAnimation())
-    return;
-  shutdown_after_lock_ = false;
+  VLOG(1) << "CancelLockAnimation";
   animating_lock_ = false;
-  CancelPreLockAnimation();
+  Shell::Get()->wallpaper_controller()->UpdateWallpaperBlur(false);
+  base::Closure next_animation_starter =
+      base::Bind(&LockStateController::LockAnimationCancelled,
+                 weak_ptr_factory_.GetWeakPtr());
+  SessionStateAnimator::AnimationSequence* animation_sequence =
+      animator_->BeginAnimationSequence(next_animation_starter);
+
+  animation_sequence->StartAnimation(
+      SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS,
+      SessionStateAnimator::ANIMATION_UNDO_LIFT,
+      SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS);
+  animation_sequence->StartAnimation(
+      SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN,
+      SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS);
+  AnimateWallpaperHidingIfNecessary(
+      SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS,
+      animation_sequence);
+
+  animation_sequence->EndSequence();
 }
 
 bool LockStateController::CanCancelShutdownAnimation() {
-  return pre_shutdown_timer_.IsRunning() || shutdown_after_lock_ ||
-         lock_to_shutdown_timer_.IsRunning();
+  return pre_shutdown_timer_.IsRunning();
 }
 
 void LockStateController::CancelShutdownAnimation() {
   if (!CanCancelShutdownAnimation())
     return;
-  if (lock_to_shutdown_timer_.IsRunning()) {
-    lock_to_shutdown_timer_.Stop();
-    return;
-  }
-  if (shutdown_after_lock_) {
-    shutdown_after_lock_ = false;
-    return;
-  }
 
   animator_->StartAnimation(
       SessionStateAnimator::ROOT_CONTAINER,
@@ -182,14 +180,6 @@
   pre_shutdown_timer_.Stop();
 }
 
-void LockStateController::OnStartingLock() {
-  if (shutting_down_ || system_is_locked_)
-    return;
-  if (animating_lock_)
-    return;
-  StartImmediatePreLockAnimation(false /* request_lock_on_completion */);
-}
-
 void LockStateController::RequestShutdown(ShutdownReason reason) {
   if (shutting_down_)
     return;
@@ -215,7 +205,10 @@
 void LockStateController::SetLockScreenDisplayedCallback(
     base::OnceClosure callback) {
   DCHECK(lock_screen_displayed_callback_.is_null());
-  lock_screen_displayed_callback_ = std::move(callback);
+  if (system_is_locked_ && !animating_lock_)
+    std::move(callback).Run();
+  else
+    lock_screen_displayed_callback_ = std::move(callback);
 }
 
 void LockStateController::OnHostCloseRequested(aura::WindowTreeHost* host) {
@@ -274,19 +267,6 @@
   LOG(FATAL) << "Screen lock took too long; crashing intentionally";
 }
 
-void LockStateController::StartLockToShutdownTimer() {
-  DCHECK(shutdown_reason_);
-  shutdown_after_lock_ = false;
-  lock_to_shutdown_timer_.Stop();
-  lock_to_shutdown_timer_.Start(FROM_HERE, kLockToShutdownTimeout, this,
-                                &LockStateController::OnLockToShutdownTimeout);
-}
-
-void LockStateController::OnLockToShutdownTimeout() {
-  DCHECK(system_is_locked_);
-  StartCancellableShutdownAnimation();
-}
-
 void LockStateController::StartPreShutdownAnimationTimer() {
   pre_shutdown_timer_.Stop();
   pre_shutdown_timer_.Start(
@@ -330,39 +310,6 @@
   shutdown_controller_->ShutDownOrReboot(*shutdown_reason_);
 }
 
-void LockStateController::StartCancellableShutdownAnimation() {
-  Shell* shell = Shell::Get();
-  // Hide cursor, but let it reappear if the mouse moves.
-  if (shell->cursor_manager())
-    shell->cursor_manager()->HideCursor();
-
-  animator_->StartAnimation(
-      SessionStateAnimator::ROOT_CONTAINER,
-      SessionStateAnimator::ANIMATION_GRAYSCALE_BRIGHTNESS,
-      SessionStateAnimator::ANIMATION_SPEED_SHUTDOWN);
-  StartPreShutdownAnimationTimer();
-}
-
-void LockStateController::StartImmediatePreLockAnimation(
-    bool request_lock_on_completion) {
-  VLOG(1) << "StartImmediatePreLockAnimation " << request_lock_on_completion;
-  animating_lock_ = true;
-  StoreUnlockedProperties();
-  PreLockAnimation(SessionStateAnimator::ANIMATION_SPEED_MOVE_WINDOWS,
-                   request_lock_on_completion);
-  DispatchCancelMode();
-  OnLockStateEvent(LockStateObserver::EVENT_LOCK_ANIMATION_STARTED);
-}
-
-void LockStateController::StartCancellablePreLockAnimation() {
-  animating_lock_ = true;
-  StoreUnlockedProperties();
-  VLOG(1) << "StartCancellablePreLockAnimation";
-  PreLockAnimation(SessionStateAnimator::ANIMATION_SPEED_UNDOABLE, true);
-  DispatchCancelMode();
-  OnLockStateEvent(LockStateObserver::EVENT_PRELOCK_ANIMATION_STARTED);
-}
-
 void LockStateController::PreLockAnimation(
     SessionStateAnimator::AnimationSpeed speed,
     bool request_lock_on_completion) {
@@ -388,29 +335,6 @@
   animation_sequence->EndSequence();
 }
 
-void LockStateController::CancelPreLockAnimation() {
-  VLOG(1) << "CancelPreLockAnimation";
-  Shell::Get()->wallpaper_controller()->UpdateWallpaperBlur(false);
-  base::Closure next_animation_starter =
-      base::Bind(&LockStateController::LockAnimationCancelled,
-                 weak_ptr_factory_.GetWeakPtr());
-  SessionStateAnimator::AnimationSequence* animation_sequence =
-      animator_->BeginAnimationSequence(next_animation_starter);
-
-  animation_sequence->StartAnimation(
-      SessionStateAnimator::NON_LOCK_SCREEN_CONTAINERS,
-      SessionStateAnimator::ANIMATION_UNDO_LIFT,
-      SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS);
-  animation_sequence->StartAnimation(
-      SessionStateAnimator::SHELF, SessionStateAnimator::ANIMATION_FADE_IN,
-      SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS);
-  AnimateWallpaperHidingIfNecessary(
-      SessionStateAnimator::ANIMATION_SPEED_UNDO_MOVE_WINDOWS,
-      animation_sequence);
-
-  animation_sequence->EndSequence();
-}
-
 void LockStateController::StartPostLockAnimation() {
   VLOG(1) << "StartPostLockAnimation";
   base::Closure next_animation_starter =
@@ -470,13 +394,11 @@
 }
 
 void LockStateController::LockAnimationCancelled() {
-  can_cancel_lock_animation_ = false;
   RestoreUnlockedProperties();
 }
 
 void LockStateController::PreLockAnimationFinished(bool request_lock) {
   VLOG(1) << "PreLockAnimationFinished";
-  can_cancel_lock_animation_ = false;
 
   // Don't do anything (including starting the lock-fail timer) if the screen
   // was already locked while the animation was going.
@@ -487,13 +409,7 @@
   }
 
   if (request_lock) {
-    if (shutdown_after_lock_) {
-      base::RecordAction(
-          base::UserMetricsAction("Accel_LockScreen_PowerButton"));
-    } else {
-      base::RecordAction(
-          base::UserMetricsAction("Accel_LockScreen_LockButton"));
-    }
+    base::RecordAction(base::UserMetricsAction("Accel_LockScreen_LockButton"));
     Shell::Get()->session_controller()->LockScreen();
   }
 
@@ -512,10 +428,6 @@
     std::move(lock_screen_displayed_callback_).Run();
 
   CHECK(!views::MenuController::GetActiveInstance());
-  if (shutdown_after_lock_) {
-    shutdown_after_lock_ = false;
-    StartLockToShutdownTimer();
-  }
 }
 
 void LockStateController::UnlockAnimationAfterUIDestroyedFinished() {
diff --git a/ash/wm/lock_state_controller.h b/ash/wm/lock_state_controller.h
index f8abb65..3a5535d 100644
--- a/ash/wm/lock_state_controller.h
+++ b/ash/wm/lock_state_controller.h
@@ -29,17 +29,13 @@
 // Displays onscreen animations and locks or suspends the system in response to
 // the power button being pressed or released.
 // Lock workflow:
-// Entry points:
+// Entry point:
 //  * StartLockAnimation (bool shutdown after lock) - starts lock that can be
 //    cancelled.
-//  * StartLockAnimationAndLockImmediately (bool shutdown after lock) - starts
-//    uninterruptible lock animation.
-// This leads to call of either StartImmediatePreLockAnimation or
-// StartCancellablePreLockAnimation. Once they complete
-// PreLockAnimationFinished is called, and system lock is requested.
-// Once system locks and lock UI is created, OnLockStateChanged is called, and
-// StartPostLockAnimation is called. In PostLockAnimationFinished two
-// things happen : EVENT_LOCK_ANIMATION_FINISHED notification is sent (it
+// Once it completes, PreLockAnimationFinished is called, and system lock is
+// requested. Once system locks and lock UI is created, OnLockStateChanged is
+// called, and StartPostLockAnimation is called. In PostLockAnimationFinished
+// two things happen : EVENT_LOCK_ANIMATION_FINISHED notification is sent (it
 // triggers third part of animation within lock UI), and check for continuing to
 // shutdown is made.
 //
@@ -62,21 +58,12 @@
   void AddObserver(LockStateObserver* observer);
   void RemoveObserver(LockStateObserver* observer);
 
-  // Starts locking (with slow animation) that can be cancelled.
+  // Starts locking (with slow pre-lock animation) that can be cancelled.
   void StartLockAnimation();
 
-  // Starts locking (with slow animation) that can be cancelled.
-  // After locking and |kLockToShutdownTimeoutMs| StartShutdownAnimation()
-  // will be called unless CancelShutdownAnimation() is called.
-  // |shutdown_reason| gives the reason for shutdown.
-  void StartLockThenShutdownAnimation(ShutdownReason shutdown_reason);
-
   // Starts shutting down (with slow animation) that can be cancelled.
   void StartShutdownAnimation(ShutdownReason reason);
 
-  // Starts usual lock animation, but locks immediately.
-  void StartLockAnimationAndLockImmediately();
-
   // Starts locking without slow animation.
   void LockWithoutAnimation();
 
@@ -87,9 +74,6 @@
   // Returns true if we are shutting down.
   bool ShutdownRequested();
 
-  // Returns true if we are within cancellable lock timeframe.
-  bool CanCancelLockAnimation();
-
   // Cancels locking and reverts lock animation.
   void CancelLockAnimation();
 
@@ -99,9 +83,6 @@
   // Cancels shutting down and reverts shutdown animation.
   void CancelShutdownAnimation();
 
-  // Called when Chrome gets a request to display the lock screen.
-  void OnStartingLock();
-
   // Displays the shutdown animation and requests a system shutdown or system
   // restart depending on the the state of the |RebootOnShutdown| device policy.
   void RequestShutdown(ShutdownReason reason);
@@ -136,12 +117,6 @@
   // Reverts the pre-lock animation, reports the error.
   void OnLockFailTimeout();
 
-  // Starts timer for gap between lock and shutdown.
-  void StartLockToShutdownTimer();
-
-  // Calls StartShutdownAnimation().
-  void OnLockToShutdownTimeout();
-
   // Starts timer for undoable shutdown animation.
   void StartPreShutdownAnimationTimer();
 
@@ -156,19 +131,8 @@
   // Request that the machine be shut down.
   void OnRealPowerTimeout();
 
-  // Starts shutdown animation that can be cancelled and starts pre-shutdown
-  // timer.
-  void StartCancellableShutdownAnimation();
-
-  // If |request_lock_on_completion| is true, a lock request will be sent
-  // after the pre-lock animation completes.  (The pre-lock animation is
-  // also displayed in response to already-in-progress lock requests; in
-  // these cases an additional lock request is undesirable.)
-  void StartImmediatePreLockAnimation(bool request_lock_on_completion);
-  void StartCancellablePreLockAnimation();
   void PreLockAnimation(SessionStateAnimator::AnimationSpeed speed,
                         bool request_lock_on_completion);
-  void CancelPreLockAnimation();
   void StartPostLockAnimation();
   // This method calls |callback| when animation completes.
   void StartUnlockAnimationBeforeUIDestroyed(base::OnceClosure callback);
@@ -215,9 +179,6 @@
   // Indicates that controller displays lock animation.
   bool animating_lock_ = false;
 
-  // Indicates that lock animation can be undone.
-  bool can_cancel_lock_animation_ = false;
-
   // Indicates whether post lock animation should be immediate.
   bool post_lock_immediate_animation_ = false;
 
@@ -233,11 +194,6 @@
   // assume that our request got dropped.
   base::OneShotTimer lock_fail_timer_;
 
-  // Started when the screen is locked while the power button is held.  Adds a
-  // delay between the appearance of the lock screen and the beginning of the
-  // pre-shutdown animation.
-  base::OneShotTimer lock_to_shutdown_timer_;
-
   // Started when we begin displaying the pre-shutdown animation.  When it
   // fires, we start the shutdown animation and get ready to request shutdown.
   base::OneShotTimer pre_shutdown_timer_;
diff --git a/ash/wm/lock_state_controller_test_api.h b/ash/wm/lock_state_controller_test_api.h
index d0336f9..6a4b2fe5 100644
--- a/ash/wm/lock_state_controller_test_api.h
+++ b/ash/wm/lock_state_controller_test_api.h
@@ -22,9 +22,6 @@
   bool lock_fail_timer_is_running() const {
     return controller_->lock_fail_timer_.IsRunning();
   }
-  bool lock_to_shutdown_timer_is_running() const {
-    return controller_->lock_to_shutdown_timer_.IsRunning();
-  }
   bool shutdown_timer_is_running() const {
     return controller_->pre_shutdown_timer_.IsRunning();
   }
@@ -32,18 +29,11 @@
     return controller_->real_shutdown_timer_.IsRunning();
   }
   bool is_animating_lock() const { return controller_->animating_lock_; }
-  bool is_lock_cancellable() const {
-    return controller_->CanCancelLockAnimation();
-  }
 
   void trigger_lock_fail_timeout() {
     controller_->OnLockFailTimeout();
     controller_->lock_fail_timer_.Stop();
   }
-  void trigger_lock_to_shutdown_timeout() {
-    controller_->OnLockToShutdownTimeout();
-    controller_->lock_to_shutdown_timer_.Stop();
-  }
   void trigger_shutdown_timeout() {
     controller_->OnPreShutdownAnimationTimeout();
     controller_->pre_shutdown_timer_.Stop();
diff --git a/ash/wm/lock_state_controller_unittest.cc b/ash/wm/lock_state_controller_unittest.cc
index 4592b62..1331d36 100644
--- a/ash/wm/lock_state_controller_unittest.cc
+++ b/ash/wm/lock_state_controller_unittest.cc
@@ -316,7 +316,6 @@
   EXPECT_TRUE(power_button_test_api_->IsMenuOpened());
 
   // We shouldn't progress towards the shutdown state, however.
-  EXPECT_FALSE(lock_state_test_api_->lock_to_shutdown_timer_is_running());
   EXPECT_FALSE(lock_state_test_api_->shutdown_timer_is_running());
 
   ReleasePowerButton();
@@ -468,6 +467,7 @@
   ExpectPostLockAnimationFinished();
 }
 
+#if 0
 // When the screen is locked without going through the usual power-button
 // slow-close path (e.g. via the wrench menu), test that we still show the
 // fast-close animation.
@@ -482,6 +482,7 @@
   test_animator_->CompleteAllAnimations(true);
   EXPECT_FALSE(Shell::Get()->session_controller()->IsScreenLocked());
 }
+#endif
 
 // When we hear that the process is exiting but we haven't had a chance to
 // display an animation, we should just blank the screen.
diff --git a/ash/wm/overview/overview_session.cc b/ash/wm/overview/overview_session.cc
index 6ecc005..f5ce6e5 100644
--- a/ash/wm/overview/overview_session.cc
+++ b/ash/wm/overview/overview_session.cc
@@ -650,10 +650,21 @@
   if (canceled)
     return;
   if (overview_focus_widget_) {
-    if (should_focus_overview)
+    if (should_focus_overview) {
       overview_focus_widget_->Show();
-    else
+    } else {
       overview_focus_widget_->ShowInactive();
+
+      // Check if the active window is in overview. There is at least one
+      // workflow where it will be: the active window is being dragged, and the
+      // previous window carries over from clamshell mode to tablet split view.
+      if (IsWindowInOverview(window_util::GetActiveWindow())) {
+        // We do not want an active window in overview. It will cause blatantly
+        // broken behavior as in the video linked in crbug.com/992223.
+        wm::ActivateWindow(
+            Shell::Get()->split_view_controller()->GetDefaultSnappedWindow());
+      }
+    }
   }
   Shell::Get()->overview_controller()->DelayedUpdateRoundedCornersAndShadow();
 }
diff --git a/ash/wm/overview/overview_window_drag_controller.cc b/ash/wm/overview/overview_window_drag_controller.cc
index 6ab063bc..dbdbc2f 100644
--- a/ash/wm/overview/overview_window_drag_controller.cc
+++ b/ash/wm/overview/overview_window_drag_controller.cc
@@ -716,9 +716,11 @@
 
   // |item_| will be deleted after SplitViewController::SnapWindow().
   DCHECK(!Shell::Get()->split_view_controller()->IsDividerAnimating());
-  split_view_controller_->SnapWindow(item_->GetWindow(), snap_position,
+  aura::Window* window = item_->GetWindow();
+  split_view_controller_->SnapWindow(window, snap_position,
                                      /*use_divider_spawn_animation=*/true);
   item_ = nullptr;
+  wm::ActivateWindow(window);
 }
 
 }  // namespace ash
diff --git a/ash/wm/splitview/split_view_controller.cc b/ash/wm/splitview/split_view_controller.cc
index 6dec3f0..458f918d 100644
--- a/ash/wm/splitview/split_view_controller.cc
+++ b/ash/wm/splitview/split_view_controller.cc
@@ -422,9 +422,8 @@
 
     OnWindowSnapped(window);
   } else {
-    // Otherwise, try to snap it first. It will be activated later after the
-    // window is snapped. The split view state will also be updated after the
-    // window is snapped.
+    // Otherwise, try to snap it first. The split view state will be updated
+    // after the window is snapped.
     const WMEvent event((snap_position == LEFT) ? WM_EVENT_SNAP_LEFT
                                                 : WM_EVENT_SNAP_RIGHT);
     WindowState::Get(window)->OnWMEvent(&event);
@@ -1524,7 +1523,7 @@
 void SplitViewController::OnWindowSnapped(aura::Window* window) {
   RestoreTransformIfApplicable(window);
   UpdateSplitViewStateAndNotifyObservers();
-  ActivateSnappedWindowAndUpdateStacking(window);
+  UpdateWindowStackingAfterSnap(window);
 
   // If there are two window snapped in clamshell mode, splitview mode is ended.
   if (state_ == SplitViewState::kBothSnapped &&
@@ -1719,16 +1718,19 @@
   }
 }
 
-void SplitViewController::ActivateSnappedWindowAndUpdateStacking(
-    aura::Window* window) {
-  aura::Window* other_window =
-      window == left_window_ ? right_window_ : left_window_;
-  if (other_window) {
-    DCHECK(window == left_window_ || window == right_window_);
-    other_window->parent()->StackChildAtTop(other_window);
+void SplitViewController::UpdateWindowStackingAfterSnap(
+    aura::Window* newly_snapped) {
+  if (split_view_divider_)
+    split_view_divider_->SetAlwaysOnTop(true);
+
+  aura::Window* other_snapped =
+      newly_snapped == left_window_ ? right_window_ : left_window_;
+  if (other_snapped) {
+    DCHECK(newly_snapped == left_window_ || newly_snapped == right_window_);
+    other_snapped->parent()->StackChildAtTop(other_snapped);
   }
 
-  wm::ActivateWindow(window);
+  newly_snapped->parent()->StackChildAtTop(newly_snapped);
 }
 
 void SplitViewController::SetWindowsTransformDuringResizing() {
@@ -1899,6 +1901,7 @@
       // location. Note if there is already a window at |desired_snap_postion|,
       // SnapWindow() will put the previous snapped window in overview.
       SnapWindow(window, GetSnapPosition(window, last_location_in_screen));
+      wm::ActivateWindow(window);
     } else {
       // Restore the dragged window's transform first if it's not identity. It
       // needs to be called before the transformed window's bounds change so
@@ -1934,6 +1937,7 @@
     // |desired_snap_position| in overview.
     SnapWindow(window, desired_snap_position,
                /*use_divider_spawn_animation=*/!initiator_window);
+    wm::ActivateWindow(window);
 
     if (!was_splitview_active) {
       // If splitview mode was not active before snapping the dragged
diff --git a/ash/wm/splitview/split_view_controller.h b/ash/wm/splitview/split_view_controller.h
index 2e493ff..d8eeea0 100644
--- a/ash/wm/splitview/split_view_controller.h
+++ b/ash/wm/splitview/split_view_controller.h
@@ -337,11 +337,8 @@
   // Restores |window| transform to identity transform if applicable.
   void RestoreTransformIfApplicable(aura::Window* window);
 
-  // Activates the newly snapped window |window| and updates window stacking. In
-  // clamshell mode, if there is only one overview window and you drag and snap
-  // it to enter split view, then this function is called after split view mode
-  // has already been ended. Then it just activates |window|.
-  void ActivateSnappedWindowAndUpdateStacking(aura::Window* window);
+  // Called after |newly_snapped| gets snapped. Updates window stacking.
+  void UpdateWindowStackingAfterSnap(aura::Window* newly_snapped);
 
   // During resizing, it's possible that the resizing bounds of the snapped
   // window is smaller than its minimum bounds, in this case we apply a
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc
index 746872a..98131e85 100644
--- a/ash/wm/splitview/split_view_controller_unittest.cc
+++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -472,6 +472,11 @@
 
   // 2 - Then test two snapped window scenario.
   std::unique_ptr<aura::Window> window2(CreateWindow(bounds));
+  // Reactivate |window1| because it is the one that we will be maximizing and
+  // fullscreening. When |window1| goes out of scope at the end of the test, it
+  // will be a full screen window, and if it is not the active window, then the
+  // destructor will cause a |DCHECK| failure in |ash::WindowState::Get|.
+  wm::ActivateWindow(window1.get());
   split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT);
   split_view_controller()->SnapWindow(window2.get(),
                                       SplitViewController::RIGHT);
@@ -555,10 +560,14 @@
   EXPECT_EQ(split_view_controller()->InSplitViewMode(), true);
   EXPECT_EQ(split_view_controller()->state(), SplitViewState::kLeftSnapped);
   EXPECT_EQ(split_view_controller()->left_window(), window1.get());
+  // Activate |window1| in preparation to verify that it stays active when
+  // overview mode is ended.
+  wm::ActivateWindow(window1.get());
 
   ToggleOverview();
   EXPECT_EQ(split_view_controller()->state(), SplitViewState::kBothSnapped);
   EXPECT_EQ(split_view_controller()->right_window(), window3.get());
+  EXPECT_TRUE(wm::IsActiveWindow(window1.get()));
   CheckOverviewEnterExitHistogram("ExitInSplitView", {1, 0}, {0, 1});
 }
 
@@ -2842,6 +2851,7 @@
   EXPECT_EQ(split_view_controller()->state(), SplitViewState::kBothSnapped);
   EXPECT_FALSE(Shell::Get()->overview_controller()->InOverviewSession());
   EXPECT_TRUE(window1->GetProperty(kCanAttachToAnotherWindowKey));
+  EXPECT_EQ(window1.get(), window_util::GetActiveWindow());
 
   EndSplitView();
   EXPECT_FALSE(split_view_controller()->InSplitViewMode());
@@ -3695,8 +3705,8 @@
   EXPECT_TRUE(window3->IsVisible());
   EXPECT_TRUE(window4->IsVisible());
 
-  if (IsTabletMode())
-    EXPECT_TRUE(Shell::Get()->app_list_controller()->IsVisible());
+  // Home launcher should be shown because none of these windows are activated.
+  EXPECT_TRUE(Shell::Get()->app_list_controller()->IsVisible());
 
   // 1) Start dragging |window1|. |window2| is the source window.
   std::unique_ptr<WindowResizer> resizer =
@@ -3710,9 +3720,8 @@
   EXPECT_FALSE(window3->IsVisible());
   EXPECT_FALSE(window4->IsVisible());
 
-  // Test that home launcher should be dismissed.
-  if (IsTabletMode())
-    EXPECT_FALSE(Shell::Get()->app_list_controller()->IsVisible());
+  // Test that home launcher is not shown because a window is active.
+  EXPECT_FALSE(Shell::Get()->app_list_controller()->IsVisible());
 
   // Test that during dragging, we could not show a hidden window.
   window3->Show();
@@ -3725,9 +3734,8 @@
   EXPECT_TRUE(window3->IsVisible());
   EXPECT_TRUE(window4->IsVisible());
 
-  // Test that home launcher should be reshown.
-  if (IsTabletMode())
-    EXPECT_TRUE(Shell::Get()->app_list_controller()->IsVisible());
+  // Test that home launcher is still not shown, because a window is active.
+  EXPECT_FALSE(Shell::Get()->app_list_controller()->IsVisible());
 }
 
 // Tests that the dragged window should be the active and top window if overview
diff --git a/ash/wm/splitview/split_view_divider.cc b/ash/wm/splitview/split_view_divider.cc
index 98f9fec6..a1e7237 100644
--- a/ash/wm/splitview/split_view_divider.cc
+++ b/ash/wm/splitview/split_view_divider.cc
@@ -331,6 +331,22 @@
                                   is_dragging);
 }
 
+void SplitViewDivider::SetAlwaysOnTop(bool on_top) {
+  if (on_top) {
+    divider_widget_->SetZOrderLevel(ui::ZOrderLevel::kFloatingUIElement);
+
+    // Special handling when put divider into always_on_top container. We want
+    // to put it at the bottom so it won't block other always_on_top windows.
+    aura::Window* always_on_top_container =
+        Shell::GetContainer(divider_widget_->GetNativeWindow()->GetRootWindow(),
+                            kShellWindowId_AlwaysOnTopContainer);
+    always_on_top_container->StackChildAtBottom(
+        divider_widget_->GetNativeWindow());
+  } else {
+    divider_widget_->SetZOrderLevel(ui::ZOrderLevel::kNormal);
+  }
+}
+
 void SplitViewDivider::AddObservedWindow(aura::Window* window) {
   if (!base::Contains(observed_windows_, window)) {
     window->AddObserver(this);
@@ -447,20 +463,4 @@
   divider_widget_->Show();
 }
 
-void SplitViewDivider::SetAlwaysOnTop(bool on_top) {
-  if (on_top) {
-    divider_widget_->SetZOrderLevel(ui::ZOrderLevel::kFloatingUIElement);
-
-    // Special handling when put divider into always_on_top container. We want
-    // to put it at the bottom so it won't block other always_on_top windows.
-    aura::Window* always_on_top_container =
-        Shell::GetContainer(divider_widget_->GetNativeWindow()->GetRootWindow(),
-                            kShellWindowId_AlwaysOnTopContainer);
-    always_on_top_container->StackChildAtBottom(
-        divider_widget_->GetNativeWindow());
-  } else {
-    divider_widget_->SetZOrderLevel(ui::ZOrderLevel::kNormal);
-  }
-}
-
 }  // namespace ash
diff --git a/ash/wm/splitview/split_view_divider.h b/ash/wm/splitview/split_view_divider.h
index eb9eb80..6822e2f 100644
--- a/ash/wm/splitview/split_view_divider.h
+++ b/ash/wm/splitview/split_view_divider.h
@@ -67,6 +67,8 @@
   // position.
   gfx::Rect GetDividerBoundsInScreen(bool is_dragging);
 
+  void SetAlwaysOnTop(bool on_top);
+
   void AddObservedWindow(aura::Window* window);
   void RemoveObservedWindow(aura::Window* window);
 
@@ -97,7 +99,6 @@
 
  private:
   void CreateDividerWidget(aura::Window* root_window);
-  void SetAlwaysOnTop(bool on_top);
 
   SplitViewController* controller_;
 
diff --git a/ash/wm/tablet_mode/tablet_mode_controller_unittest.cc b/ash/wm/tablet_mode/tablet_mode_controller_unittest.cc
index 92280eda..7d8a93c 100644
--- a/ash/wm/tablet_mode/tablet_mode_controller_unittest.cc
+++ b/ash/wm/tablet_mode/tablet_mode_controller_unittest.cc
@@ -28,6 +28,7 @@
 #include "ash/wm/splitview/split_view_controller.h"
 #include "ash/wm/splitview/split_view_utils.h"
 #include "ash/wm/tablet_mode/tablet_mode_controller_test_api.h"
+#include "ash/wm/toplevel_window_event_handler.h"
 #include "ash/wm/window_util.h"
 #include "ash/wm/wm_event.h"
 #include "base/command_line.h"
@@ -49,6 +50,7 @@
 #include "ui/events/devices/input_device.h"
 #include "ui/events/event_handler.h"
 #include "ui/events/test/event_generator.h"
+#include "ui/gfx/geometry/point.h"
 #include "ui/gfx/geometry/vector3d_f.h"
 #include "ui/message_center/message_center.h"
 #include "ui/wm/core/window_util.h"
@@ -1181,6 +1183,7 @@
   EXPECT_EQ(left_window.get(), split_view_controller->left_window());
   EXPECT_EQ(right_window.get(), split_view_controller->right_window());
   EXPECT_FALSE(Shell::Get()->overview_controller()->InOverviewSession());
+  EXPECT_EQ(left_window.get(), window_util::GetActiveWindow());
 }
 
 // Test that if before tablet mode, the active window is snapped on the right
@@ -1198,6 +1201,7 @@
   EXPECT_EQ(left_window.get(), split_view_controller->left_window());
   EXPECT_EQ(right_window.get(), split_view_controller->right_window());
   EXPECT_FALSE(Shell::Get()->overview_controller()->InOverviewSession());
+  EXPECT_EQ(right_window.get(), window_util::GetActiveWindow());
 }
 
 // Test that if before tablet mode, the active window is an ARC window snapped
@@ -1257,7 +1261,7 @@
   EXPECT_EQ(SplitViewState::kLeftSnapped, split_view_controller->state());
   EXPECT_EQ(parent.get(), split_view_controller->left_window());
   EXPECT_TRUE(Shell::Get()->overview_controller()->InOverviewSession());
-  EXPECT_EQ(parent.get(), window_util::GetActiveWindow());
+  EXPECT_EQ(child.get(), window_util::GetActiveWindow());
 }
 
 // Test that if before tablet mode, the active window is the app list and the
@@ -1284,15 +1288,12 @@
   SplitViewController* split_view_controller =
       Shell::Get()->split_view_controller();
   std::unique_ptr<aura::Window> dragged_window = CreateTestWindow();
-  WindowState* dragged_window_state = WindowState::Get(dragged_window.get());
-  dragged_window_state->CreateDragDetails(
-      gfx::Point(), HTNOWHERE,
-      ::wm::WindowMoveSource::WINDOW_MOVE_SOURCE_MOUSE);
-  dragged_window_state->OnDragStarted(HTNOWHERE);
-  ASSERT_TRUE(dragged_window_state->is_dragged());
   std::unique_ptr<aura::Window> snapped_window =
       CreateDesktopWindowSnappedLeft();
   wm::ActivateWindow(dragged_window.get());
+  ASSERT_TRUE(Shell::Get()->toplevel_window_event_handler()->AttemptToStartDrag(
+      dragged_window.get(), gfx::Point(), HTCAPTION,
+      ash::ToplevelWindowEventHandler::EndClosure()));
   tablet_mode_controller()->SetEnabledForTest(true);
   EXPECT_EQ(SplitViewState::kLeftSnapped, split_view_controller->state());
   EXPECT_EQ(snapped_window.get(), split_view_controller->left_window());
@@ -1320,6 +1321,30 @@
   EXPECT_EQ(snapped_window.get(), window_util::GetActiveWindow());
 }
 
+// Test that if before tablet mode, the active window is being dragged and the
+// previous window is a transient child of a window snapped on the left, then
+// split view is activated with the parent on the left.
+TEST_F(TabletModeControllerTest,
+       StartTabletActiveDraggedPreviousTransientChildOfLeftSnap) {
+  SplitViewController* split_view_controller =
+      Shell::Get()->split_view_controller();
+  std::unique_ptr<aura::Window> dragged_window = CreateTestWindow();
+  std::unique_ptr<aura::Window> parent = CreateDesktopWindowSnappedLeft();
+  std::unique_ptr<aura::Window> child =
+      CreateTestWindow(gfx::Rect(), aura::client::WINDOW_TYPE_POPUP);
+  ::wm::AddTransientChild(parent.get(), child.get());
+  wm::ActivateWindow(child.get());
+  wm::ActivateWindow(dragged_window.get());
+  ASSERT_TRUE(Shell::Get()->toplevel_window_event_handler()->AttemptToStartDrag(
+      dragged_window.get(), gfx::Point(), HTCAPTION,
+      ash::ToplevelWindowEventHandler::EndClosure()));
+  tablet_mode_controller()->SetEnabledForTest(true);
+  EXPECT_EQ(SplitViewState::kLeftSnapped, split_view_controller->state());
+  EXPECT_EQ(parent.get(), split_view_controller->left_window());
+  EXPECT_TRUE(Shell::Get()->overview_controller()->InOverviewSession());
+  EXPECT_EQ(parent.get(), window_util::GetActiveWindow());
+}
+
 // Test that if before tablet mode, the active window is snapped on the left but
 // does not meet the requirements to be snapped in split view, and the previous
 // window is snapped on the right, then split view is not activated.
@@ -1440,15 +1465,16 @@
   EXPECT_EQ(right_window.get(), window_util::GetActiveWindow());
 }
 
-// Test that if overview is triggered on entering tablet mode, then the app list
-// can still be successfully shown and actually seen.
-TEST_F(TabletModeControllerTest, AppListWorksAfterEnteringTabletForOverview) {
+// Test that when entering tablet mode with a left snapped window, the applist
+// is not visible because overview is shown.
+TEST_F(TabletModeControllerTest,
+       AppListNotSeenAfterEnteringTabletModeWithLeftSnappedWindow) {
   AppListControllerImpl* app_list_controller =
       Shell::Get()->app_list_controller();
   std::unique_ptr<aura::Window> window = CreateDesktopWindowSnappedLeft();
   tablet_mode_controller()->SetEnabledForTest(true);
   app_list_controller->ShowAppList();
-  EXPECT_TRUE(app_list_controller->IsVisible());
+  EXPECT_FALSE(app_list_controller->IsVisible());
 }
 
 // Test that if both the active window and the previous window are snapped on
diff --git a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
index ad100e5..2ba02f7 100644
--- a/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
+++ b/base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java
@@ -5,6 +5,7 @@
 package org.chromium.base.process_launcher;
 
 import android.app.Service;
+import android.content.Context;
 import android.content.Intent;
 import android.os.Binder;
 import android.os.Bundle;
@@ -49,10 +50,13 @@
  *
  * Subclasses must also provide a delegate in this class constructor. That delegate is responsible
  * for loading native libraries and running the main entry point of the service.
+ *
+ * This class does not directly inherit from Service because the logic may be used by a Service
+ * implementation which cannot directly inherit from this class (e.g. for WebLayer child services).
  */
 @JNINamespace("base::android")
 @MainDex
-public abstract class ChildProcessService extends Service {
+public class ChildProcessService {
     private static final String MAIN_THREAD_NAME = "ChildProcessMain";
     private static final String TAG = "ChildProcessService";
 
@@ -60,6 +64,8 @@
     private static boolean sCreateCalled;
 
     private final ChildProcessServiceDelegate mDelegate;
+    private final Service mService;
+    private final Context mApplicationContext;
 
     private final Object mBinderLock = new Object();
     private final Object mLibraryInitializedLock = new Object();
@@ -91,8 +97,11 @@
     // Interface to send notifications to the parent process.
     private IParentProcess mParentProcess;
 
-    public ChildProcessService(ChildProcessServiceDelegate delegate) {
+    public ChildProcessService(
+            ChildProcessServiceDelegate delegate, Service service, Context applicationContext) {
         mDelegate = delegate;
+        mService = service;
+        mApplicationContext = applicationContext;
     }
 
     // Binder object used by clients for this service.
@@ -182,9 +191,7 @@
      * Loads Chrome's native libraries and initializes a ChildProcessService.
      */
     // For sCreateCalled check.
-    @Override
     public void onCreate() {
-        super.onCreate();
         Log.i(TAG, "Creating new ChildProcessService pid=%d", Process.myPid());
         if (sCreateCalled) {
             throw new RuntimeException("Illegal child process reuse.");
@@ -273,9 +280,7 @@
         mMainThread.start();
     }
 
-    @Override
     public void onDestroy() {
-        super.onDestroy();
         Log.i(TAG, "Destroying ChildProcessService pid=%d", Process.myPid());
         System.exit(0);
     }
@@ -288,7 +293,6 @@
      * @param intent The intent that was used to bind to the service.
      * @return the binder used by the client to setup the connection.
      */
-    @Override
     public IBinder onBind(Intent intent) {
         if (mServiceBound) return mBinder;
 
@@ -296,7 +300,7 @@
         // Otherwise the system may keep it around and available for a reconnect. The child
         // processes do not currently support reconnect; they must be initialized from scratch every
         // time.
-        stopSelf();
+        mService.stopSelf();
 
         mBindToCallerCheck =
                 intent.getBooleanExtra(ChildProcessConstants.EXTRA_BIND_TO_CALLER, false);
@@ -333,6 +337,10 @@
         }
     }
 
+    private Context getApplicationContext() {
+        return mApplicationContext;
+    }
+
     @NativeMethods
     interface Natives {
         /**
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc
index cef4641..14adbfc 100644
--- a/base/logging_unittest.cc
+++ b/base/logging_unittest.cc
@@ -40,6 +40,7 @@
 #include <fuchsia/logger/cpp/fidl.h>
 #include <fuchsia/logger/cpp/fidl_test_base.h>
 #include <lib/fidl/cpp/binding.h>
+#include <lib/sys/cpp/component_context.h>
 #include <lib/zx/channel.h>
 #include <lib/zx/event.h>
 #include <lib/zx/exception.h>
@@ -51,8 +52,8 @@
 #include <zircon/syscalls/exception.h>
 #include <zircon/types.h>
 
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 #endif  // OS_FUCHSIA
 
 namespace logging {
@@ -1008,8 +1009,9 @@
         std::make_unique<fuchsia::logger::LogFilterOptions>();
     options->tags = {"base_unittests__exec"};
     fuchsia::logger::LogPtr logger =
-        base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-            ->ConnectToService<fuchsia::logger::Log>();
+        base::fuchsia::ComponentContextForCurrentProcess()
+            ->svc()
+            ->Connect<fuchsia::logger::Log>();
     logger->DumpLogs(binding.NewBinding(), std::move(options));
     listener.RunUntilDone();
   } while (!listener.DidReceiveString(kLogMessage, &logged_message));
diff --git a/base/test/android/java/src/org/chromium/base/MultiprocessTestClientService.java b/base/test/android/java/src/org/chromium/base/MultiprocessTestClientService.java
index 9b50001..db6ba7f 100644
--- a/base/test/android/java/src/org/chromium/base/MultiprocessTestClientService.java
+++ b/base/test/android/java/src/org/chromium/base/MultiprocessTestClientService.java
@@ -4,11 +4,35 @@
 
 package org.chromium.base;
 
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+
 import org.chromium.base.process_launcher.ChildProcessService;
 
 /** The service implementation used to host all multiprocess test client code. */
-public class MultiprocessTestClientService extends ChildProcessService {
-    public MultiprocessTestClientService() {
-        super(new MultiprocessTestClientServiceDelegate());
+public class MultiprocessTestClientService extends Service {
+    private ChildProcessService mService;
+
+    public MultiprocessTestClientService() {}
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mService = new ChildProcessService(
+                new MultiprocessTestClientServiceDelegate(), this, getApplicationContext());
+        mService.onCreate();
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        mService.onDestroy();
+        mService = null;
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return mService.onBind(intent);
     }
 }
diff --git a/base/time/time_exploded_posix.cc b/base/time/time_exploded_posix.cc
index 0655703a..7683d13 100644
--- a/base/time/time_exploded_posix.cc
+++ b/base/time/time_exploded_posix.cc
@@ -26,8 +26,9 @@
 
 #if defined(OS_FUCHSIA)
 #include <fuchsia/deprecatedtimezone/cpp/fidl.h>
+#include <lib/sys/cpp/component_context.h>
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 #include "base/no_destructor.h"
 #include "base/numerics/clamped_math.h"
 #endif
@@ -72,11 +73,16 @@
 #elif defined(OS_FUCHSIA)
 typedef time_t SysTime;
 
+fuchsia::deprecatedtimezone::TimezoneSyncPtr ConnectTimeZoneServiceSync() {
+  fuchsia::deprecatedtimezone::TimezoneSyncPtr timezone;
+  base::fuchsia::ComponentContextForCurrentProcess()->svc()->Connect(
+      timezone.NewRequest());
+  return timezone;
+}
+
 SysTime GetTimezoneOffset(SysTime utc_time) {
   static base::NoDestructor<fuchsia::deprecatedtimezone::TimezoneSyncPtr>
-      timezone(
-          base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-              ->ConnectToServiceSync<fuchsia::deprecatedtimezone::Timezone>());
+      timezone(ConnectTimeZoneServiceSync());
 
   int64_t milliseconds_since_epoch =
       base::ClampMul(utc_time, base::Time::kMillisecondsPerSecond);
diff --git a/build/android/resource_sizes.py b/build/android/resource_sizes.py
index 4af059c..da74d91f 100755
--- a/build/android/resource_sizes.py
+++ b/build/android/resource_sizes.py
@@ -216,6 +216,22 @@
   return output
 
 
+def _ReportDfmSizes(zip_obj, report_func):
+  sizes = collections.defaultdict(int)
+  for info in zip_obj.infolist():
+    # Looks for paths like splits/vr-master.apk, splits/vr-hi.apk.
+    name_parts = info.filename.split('/')
+    if name_parts[0] == 'splits' and len(name_parts) == 2:
+      name_parts = name_parts[1].split('-')
+      if len(name_parts) == 2:
+        module_name, config_name = name_parts
+        if module_name != 'base' and config_name[:-4] in ('master', 'hi'):
+          sizes[module_name] += info.file_size
+
+  for module_name, size in sorted(sizes.iteritems()):
+    report_func('DFM_' + module_name, 'Size with hindi', size, 'bytes')
+
+
 class _FileGroup(object):
   """Represents a category that apk files can fall into."""
 
@@ -359,6 +375,7 @@
     with zipfile.ZipFile(apks_path) as z:
       hindi_apk_info = z.getinfo('splits/base-hi.apk')
       total_apk_size += hindi_apk_info.file_size
+      _ReportDfmSizes(z, report_func)
 
   total_install_size = total_apk_size
   total_install_size_android_go = total_apk_size
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni
index 64399ca4f..2bee4f8 100644
--- a/build/config/android/internal_rules.gni
+++ b/build/config/android/internal_rules.gni
@@ -1435,9 +1435,13 @@
         rebase_path(invoker.java_sources_file, root_build_dir),
         "--jacococli-jar",
         rebase_path(_jacococli_jar, root_build_dir),
-        "--files-to-instrument",
-        rebase_path(coverage_instrumentation_input_file, root_build_dir),
       ]
+      if (coverage_instrumentation_input_file != "") {
+        args += [
+          "--files-to-instrument",
+          rebase_path(coverage_instrumentation_input_file, root_build_dir),
+        ]
+      }
     }
   }
 
diff --git a/build/config/chromeos/rules.gni b/build/config/chromeos/rules.gni
index d5b6090..0a54078 100644
--- a/build/config/chromeos/rules.gni
+++ b/build/config/chromeos/rules.gni
@@ -13,7 +13,8 @@
 declare_args() {
   # Determines if we're running tests on VMs or on devices.
   # TODO(crbug.com/866062): Is there a better way to do this?
-  cros_is_vm = cros_board == "amd64-generic" || cros_board == "betty"
+  cros_is_vm = cros_board == "amd64-generic" || cros_board == "betty" ||
+               cros_board == "betty-pi-arc"
 }
 
 # Ensure that if one is set, the other is as well.
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1
index 37eb925..5c1b0c7 100644
--- a/build/fuchsia/linux.sdk.sha1
+++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@
-8901928169136896688
\ No newline at end of file
+8901901291826520800
\ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1
index 20376c126..89f1da5 100644
--- a/build/fuchsia/mac.sdk.sha1
+++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@
-8901930379926316864
\ No newline at end of file
+8901900807158070336
\ No newline at end of file
diff --git a/cc/BUILD.gn b/cc/BUILD.gn
index cc0424a..1dac8be 100644
--- a/cc/BUILD.gn
+++ b/cc/BUILD.gn
@@ -280,6 +280,8 @@
     "trees/compositor_mode.h",
     "trees/damage_tracker.cc",
     "trees/damage_tracker.h",
+    "trees/de_jelly_state.cc",
+    "trees/de_jelly_state.h",
     "trees/debug_rect_history.cc",
     "trees/debug_rect_history.h",
     "trees/draw_property_utils.cc",
diff --git a/cc/layers/layer.cc b/cc/layers/layer.cc
index 41a22e6..220aeba 100644
--- a/cc/layers/layer.cc
+++ b/cc/layers/layer.cc
@@ -18,7 +18,6 @@
 #include "base/time/time.h"
 #include "base/trace_event/trace_event.h"
 #include "cc/base/simple_enclosed_region.h"
-#include "cc/input/main_thread_scrolling_reason.h"
 #include "cc/layers/layer_client.h"
 #include "cc/layers/layer_impl.h"
 #include "cc/layers/picture_layer.h"
@@ -68,7 +67,6 @@
     gfx::ScrollOffset scroll_offset;
     gfx::Size scroll_container_bounds;
     int mirror_count;
-    uint32_t main_thread_scrolling_reasons;
     Region non_fast_scrollable_region;
     TouchActionRegion touch_action_region;
     ElementId element_id;
@@ -115,9 +113,7 @@
       background_color(0),
       backdrop_filter_quality(1.0f),
       corner_radii({0, 0, 0, 0}),
-      mirror_count(0),
-      main_thread_scrolling_reasons(
-          MainThreadScrollingReason::kNotScrollingOnMain) {}
+      mirror_count(0) {}
 
 Layer::Inputs::~Inputs() = default;
 
@@ -1077,54 +1073,6 @@
   return inputs_.user_scrollable_vertical;
 }
 
-uint32_t Layer::GetMainThreadScrollingReasons() const {
-  // When using layer lists, main thread scrolling reasons are stored in scroll
-  // nodes.
-  if (layer_tree_host() && layer_tree_host()->IsUsingLayerLists()) {
-    auto& scroll_tree = layer_tree_host()->property_trees()->scroll_tree;
-    if (auto* scroll_node = scroll_tree.Node(scroll_tree_index_))
-      return scroll_node->main_thread_scrolling_reasons;
-    return MainThreadScrollingReason::kNotScrollingOnMain;
-  }
-  return inputs_.main_thread_scrolling_reasons;
-}
-
-void Layer::AddMainThreadScrollingReasons(
-    uint32_t main_thread_scrolling_reasons) {
-  DCHECK(IsPropertyChangeAllowed());
-  DCHECK(main_thread_scrolling_reasons);
-
-  // When layer lists are used, the main thread scrolling reasons should be set
-  // on property tree nodes directly.
-  // TODO(pdr): Uncomment this check when https://crbug.com/919969 is fixed.
-  // DCHECK(!layer_tree_host() || !layer_tree_host()->IsUsingLayerLists());
-
-  // Layer should only see non-transient scrolling reasons. Transient scrolling
-  // reasons are computed per hit test.
-  DCHECK(MainThreadScrollingReason::MainThreadCanSetScrollReasons(
-      main_thread_scrolling_reasons));
-  uint32_t new_reasons =
-      inputs_.main_thread_scrolling_reasons | main_thread_scrolling_reasons;
-  if (inputs_.main_thread_scrolling_reasons == new_reasons)
-    return;
-  inputs_.main_thread_scrolling_reasons = new_reasons;
-  SetPropertyTreesNeedRebuild();
-  SetNeedsCommit();
-}
-
-void Layer::ClearMainThreadScrollingReasons(
-    uint32_t main_thread_scrolling_reasons_to_clear) {
-  DCHECK(IsPropertyChangeAllowed());
-  DCHECK(main_thread_scrolling_reasons_to_clear);
-  uint32_t new_reasons = ~main_thread_scrolling_reasons_to_clear &
-                         inputs_.main_thread_scrolling_reasons;
-  if (new_reasons == inputs_.main_thread_scrolling_reasons)
-    return;
-  inputs_.main_thread_scrolling_reasons = new_reasons;
-  SetPropertyTreesNeedRebuild();
-  SetNeedsCommit();
-}
-
 void Layer::SetNonFastScrollableRegion(const Region& region) {
   DCHECK(IsPropertyChangeAllowed());
   if (inputs_.non_fast_scrollable_region == region)
diff --git a/cc/layers/layer.h b/cc/layers/layer.h
index a9aaa92..36f26a21 100644
--- a/cc/layers/layer.h
+++ b/cc/layers/layer.h
@@ -377,19 +377,6 @@
   bool GetUserScrollableHorizontal() const;
   bool GetUserScrollableVertical() const;
 
-  // Set or get if this layer is able to be scrolled on the compositor thread.
-  // This only applies for layers that are marked as scrollable, not for layers
-  // that are moved by a scroll parent. When any reason is present, the layer
-  // will not be scrolled on the compositor thread. The reasons are a set of
-  // bitflags from MainThreadScrollingReason, used to track the reason for
-  // debugging and reporting.
-  // AddMainThreadScrollingReasons() is used to add flags to the current set,
-  // and ClearMainThreadScrollingReasons() removes flags from the current set.
-  void AddMainThreadScrollingReasons(uint32_t main_thread_scrolling_reasons);
-  void ClearMainThreadScrollingReasons(
-      uint32_t main_thread_scrolling_reasons_to_clear);
-  uint32_t GetMainThreadScrollingReasons() const;
-
   // Set or get an area of this layer within which initiating a scroll can not
   // be done from the compositor thread. Within this area, if the user attempts
   // to start a scroll, the events must be sent to the main thread and processed
@@ -937,7 +924,6 @@
 
     int mirror_count;
 
-    uint32_t main_thread_scrolling_reasons;
     Region non_fast_scrollable_region;
 
     TouchActionRegion touch_action_region;
diff --git a/cc/layers/layer_unittest.cc b/cc/layers/layer_unittest.cc
index 7446eaa..cd17611 100644
--- a/cc/layers/layer_unittest.cc
+++ b/cc/layers/layer_unittest.cc
@@ -13,7 +13,6 @@
 #include "cc/animation/animation_id_provider.h"
 #include "cc/animation/keyframed_animation_curve.h"
 #include "cc/base/math_util.h"
-#include "cc/input/main_thread_scrolling_reason.h"
 #include "cc/layers/layer_impl.h"
 #include "cc/layers/picture_layer.h"
 #include "cc/layers/solid_color_scrollbar_layer.h"
@@ -918,58 +917,6 @@
   EXPECT_TRUE(LayerNeedsDisplay(test_layer.get()));
 }
 
-TEST_F(LayerTest, TestSettingMainThreadScrollingReason) {
-  scoped_refptr<Layer> test_layer = Layer::Create();
-  EXPECT_SET_NEEDS_FULL_TREE_SYNC(1,
-                                  layer_tree_host_->SetRootLayer(test_layer));
-  EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetIsDrawable(true));
-
-  // sanity check of initial test condition
-  EXPECT_FALSE(LayerNeedsDisplay(test_layer.get()));
-
-  uint32_t reasons = 0, reasons_to_clear = 0, reasons_after_clearing = 0;
-  reasons |= MainThreadScrollingReason::kThreadedScrollingDisabled;
-  reasons |= MainThreadScrollingReason::kHandlingScrollFromMainThread;
-  reasons |= MainThreadScrollingReason::kScrollbarScrolling;
-
-  reasons_to_clear |= MainThreadScrollingReason::kHandlingScrollFromMainThread;
-
-  reasons_after_clearing |=
-      MainThreadScrollingReason::kThreadedScrollingDisabled;
-  reasons_after_clearing |= MainThreadScrollingReason::kScrollbarScrolling;
-
-  // Check that the reasons are added correctly.
-  EXPECT_SET_NEEDS_COMMIT(
-      1, test_layer->AddMainThreadScrollingReasons(
-             MainThreadScrollingReason::kThreadedScrollingDisabled));
-  EXPECT_SET_NEEDS_COMMIT(
-      1, test_layer->AddMainThreadScrollingReasons(
-             MainThreadScrollingReason::kHandlingScrollFromMainThread));
-  EXPECT_SET_NEEDS_COMMIT(1,
-                          test_layer->AddMainThreadScrollingReasons(
-                              MainThreadScrollingReason::kScrollbarScrolling));
-  EXPECT_EQ(reasons, test_layer->GetMainThreadScrollingReasons());
-
-  // Check that the reasons can be selectively cleared.
-  EXPECT_SET_NEEDS_COMMIT(
-      1, test_layer->ClearMainThreadScrollingReasons(reasons_to_clear));
-  EXPECT_EQ(reasons_after_clearing,
-            test_layer->GetMainThreadScrollingReasons());
-
-  // Check that clearing non-set reasons doesn't set needs commit.
-  reasons_to_clear = 0;
-  reasons_to_clear |= MainThreadScrollingReason::kFrameOverlay;
-  EXPECT_SET_NEEDS_COMMIT(
-      0, test_layer->ClearMainThreadScrollingReasons(reasons_to_clear));
-  EXPECT_EQ(reasons_after_clearing,
-            test_layer->GetMainThreadScrollingReasons());
-
-  // Check that adding an existing condition doesn't set needs commit.
-  EXPECT_SET_NEEDS_COMMIT(
-      0, test_layer->AddMainThreadScrollingReasons(
-             MainThreadScrollingReason::kThreadedScrollingDisabled));
-}
-
 TEST_F(LayerTest, CheckPropertyChangeCausesCorrectBehavior) {
   scoped_refptr<Layer> test_layer = Layer::Create();
   EXPECT_SET_NEEDS_FULL_TREE_SYNC(1,
@@ -1002,9 +949,6 @@
   EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetUserScrollable(true, false));
   EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetScrollOffset(
       gfx::ScrollOffset(10, 10)));
-  EXPECT_SET_NEEDS_COMMIT(
-      1, test_layer->AddMainThreadScrollingReasons(
-             MainThreadScrollingReason::kThreadedScrollingDisabled));
   EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetNonFastScrollableRegion(
       Region(gfx::Rect(1, 1, 2, 2))));
   EXPECT_SET_NEEDS_COMMIT(1, test_layer->SetTransform(
diff --git a/cc/layers/render_surface_impl.cc b/cc/layers/render_surface_impl.cc
index 464eaf40..287ce4a 100644
--- a/cc/layers/render_surface_impl.cc
+++ b/cc/layers/render_surface_impl.cc
@@ -20,6 +20,7 @@
 #include "cc/trees/layer_tree_impl.h"
 #include "cc/trees/occlusion.h"
 #include "cc/trees/transform_node.h"
+#include "components/viz/common/display/de_jelly.h"
 #include "components/viz/common/quads/content_draw_quad_base.h"
 #include "components/viz/common/quads/debug_border_draw_quad.h"
 #include "components/viz/common/quads/render_pass.h"
@@ -246,6 +247,9 @@
   } else {
     clipped_accumulated_rect_in_target_space = clip_rect();
   }
+  if (layer_tree_impl_->settings().allow_de_jelly_effect) {
+    clipped_accumulated_rect_in_target_space.Inset(0, -viz::MaxDeJellyHeight());
+  }
   clipped_accumulated_rect_in_target_space.Intersect(
       accumulated_rect_in_target_space);
 
diff --git a/cc/metrics/compositor_frame_reporter.cc b/cc/metrics/compositor_frame_reporter.cc
index d01cada..433190e9 100644
--- a/cc/metrics/compositor_frame_reporter.cc
+++ b/cc/metrics/compositor_frame_reporter.cc
@@ -51,22 +51,21 @@
 // This value should be recalculate in case of changes to the number of values
 // in CompositorFrameReporter::MissedFrameReportTypes or in
 // CompositorFrameReporter::StageType
-constexpr int kMaxHistogramIndex = 2 * kMissedFrameReportTypeCount *
+constexpr int kMaxHistogramIndex = kMissedFrameReportTypeCount *
                                    kFrameSequenceTrackerTypeCount *
                                    kStageTypeCount;
 constexpr int kHistogramMin = 1;
 constexpr int kHistogramMax = 350000;
 constexpr int kHistogramBucketCount = 50;
 
-std::string HistogramName(const char* compositor_type,
-                          const int report_type_index,
+std::string HistogramName(const int report_type_index,
                           const int frame_sequence_tracker_type_index,
                           const int stage_type_index) {
   std::string tracker_type_name = FrameSequenceTracker::
       kFrameSequenceTrackerTypeNames[frame_sequence_tracker_type_index];
   if (!tracker_type_name.empty())
     tracker_type_name += ".";
-  return base::StrCat({compositor_type, "CompositorLatency.",
+  return base::StrCat({"CompositorLatency.",
                        kReportTypeNames[report_type_index], tracker_type_name,
                        kStageNames[stage_type_index]});
 }
@@ -192,12 +191,10 @@
   const int frame_sequence_tracker_type_index =
       static_cast<int>(frame_sequence_tracker_type);
   const int histogram_index =
-      ((stage_type_index * kFrameSequenceTrackerTypeCount +
-        frame_sequence_tracker_type_index) *
-           kMissedFrameReportTypeCount +
-       report_type_index) *
-          2 +
-      (is_single_threaded_ ? 1 : 0);
+      (stage_type_index * kFrameSequenceTrackerTypeCount +
+       frame_sequence_tracker_type_index) *
+          kMissedFrameReportTypeCount +
+      report_type_index;
 
   CHECK_LT(stage_type_index, kStageTypeCount);
   CHECK_GE(stage_type_index, 0);
@@ -206,16 +203,14 @@
   CHECK_LT(histogram_index, kMaxHistogramIndex);
   CHECK_GE(histogram_index, 0);
 
-  const char* compositor_type = is_single_threaded_ ? "SingleThreaded" : "";
-
   STATIC_HISTOGRAM_POINTER_GROUP(
-      HistogramName(compositor_type, report_type_index,
-                    frame_sequence_tracker_type_index, stage_type_index),
+      HistogramName(report_type_index, frame_sequence_tracker_type_index,
+                    stage_type_index),
       histogram_index, kMaxHistogramIndex,
       AddTimeMicrosecondsGranularity(time_delta),
       base::Histogram::FactoryGet(
-          HistogramName(compositor_type, report_type_index,
-                        frame_sequence_tracker_type_index, stage_type_index),
+          HistogramName(report_type_index, frame_sequence_tracker_type_index,
+                        stage_type_index),
           kHistogramMin, kHistogramMax, kHistogramBucketCount,
           base::HistogramBase::kUmaTargetedHistogramFlag));
 }
diff --git a/cc/trees/de_jelly_state.cc b/cc/trees/de_jelly_state.cc
new file mode 100644
index 0000000..be5e965
--- /dev/null
+++ b/cc/trees/de_jelly_state.cc
@@ -0,0 +1,167 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "cc/trees/de_jelly_state.h"
+
+#include "cc/trees/layer_tree_impl.h"
+#include "cc/trees/scroll_node.h"
+#include "cc/trees/transform_node.h"
+#include "components/viz/common/display/de_jelly.h"
+
+namespace cc {
+
+DeJellyState::DeJellyState() = default;
+DeJellyState::~DeJellyState() = default;
+
+void DeJellyState::AdvanceFrame(LayerTreeImpl* layer_tree_impl) {
+  if (!layer_tree_impl->settings().allow_de_jelly_effect)
+    return;
+
+  should_de_jelly_ = false;
+
+  // Move the |new_transforms_| from the previous draw into
+  // |previous_transforms_|.
+  std::swap(previous_transforms_, new_transforms_);
+  new_transforms_.clear();
+
+  // Make sure we have an active scroll node. Otherwise we won't perform any
+  // de-jelly.
+  ScrollNode* current_scroll =
+      layer_tree_impl->property_trees()->scroll_tree.Node(
+          layer_tree_impl->property_trees()
+              ->scroll_tree.currently_scrolling_node());
+  if (!current_scroll) {
+    new_scroll_node_transform_.reset();
+    return;
+  }
+
+  scroll_transform_node_ = current_scroll->transform_id;
+
+  // Check to make sure the ToScreen transform of our scroll node is not a
+  // complex transform (doesn't work well with de-jelly). Also make sure the
+  // scale is not changing.
+  base::Optional<gfx::Transform> previous_scroll_transform =
+      new_scroll_node_transform_;
+  new_scroll_node_transform_ =
+      layer_tree_impl->property_trees()->transform_tree.ToScreen(
+          current_scroll->transform_id);
+  if (!previous_scroll_transform ||
+      !previous_scroll_transform->IsScaleOrTranslation() ||
+      !new_scroll_node_transform_->IsScaleOrTranslation() ||
+      new_scroll_node_transform_->Scale2d() !=
+          previous_scroll_transform->Scale2d()) {
+    return;
+  }
+
+  // Don't attempt de-jelly while the omnibox is transitioning in or out. There
+  // is no correct way to handle this.
+  float top_controls_shown_ratio =
+      layer_tree_impl->top_controls_shown_ratio()->Current(
+          true /* is_active_tree */);
+  if (top_controls_shown_ratio != 0.0f && top_controls_shown_ratio != 1.0f)
+    return;
+
+  // We've passed our initial checks, allow de-jelly in UpdateSharedQuadState.
+  should_de_jelly_ = true;
+}
+
+void DeJellyState::UpdateSharedQuadState(LayerTreeImpl* layer_tree_impl,
+                                         int transform_id,
+                                         viz::RenderPass* target_render_pass) {
+  if (!should_de_jelly_)
+    return;
+  DCHECK(layer_tree_impl->settings().allow_de_jelly_effect);
+
+  viz::SharedQuadState* state =
+      target_render_pass->shared_quad_state_list.back();
+  state->de_jelly_delta_y = 0.0f;
+
+  // Check if |transform_id| is a child of our |scroll_transform_node_|
+  // and if it scrolls (is not sticky or fixed).
+  bool does_not_scroll = false;
+  auto node_id = transform_id;
+  while (node_id != scroll_transform_node_ && node_id != kInvalidNodeId) {
+    auto* current_node =
+        layer_tree_impl->property_trees()->transform_tree.Node(node_id);
+
+    // Position fixed.
+    if (current_node->moved_by_outer_viewport_bounds_delta_y) {
+      does_not_scroll = true;
+      break;
+    }
+    // Position sticky.
+    if (current_node->sticky_position_constraint_id > -1) {
+      const StickyPositionNodeData* sticky_data =
+          layer_tree_impl->property_trees()
+              ->transform_tree.GetStickyPositionData(node_id);
+      if (sticky_data &&
+          sticky_data->total_containing_block_sticky_offset.y() > 0.0f) {
+        does_not_scroll = true;
+        break;
+      }
+    }
+
+    node_id = current_node->parent_id;
+  }
+  does_not_scroll |= node_id == kInvalidNodeId;
+  if (does_not_scroll)
+    return;
+
+  // Get the current node's ToScreen transform.
+  gfx::Transform transform =
+      layer_tree_impl->property_trees()->transform_tree.ToScreen(transform_id);
+  new_transforms_[transform_id] = transform;
+
+  // Get the previous transform (if any).
+  const auto& found = previous_transforms_.find(transform_id);
+  if (found == previous_transforms_.end()) {
+    return;
+  }
+
+  // Calculate the delta of point (0, 0) from the previous frame.
+  gfx::Transform previous_transform = found->second;
+  gfx::PointF new_point(0, 0);
+  transform.TransformPoint(&new_point);
+  gfx::PointF old_point(0, 0);
+  previous_transform.TransformPoint(&old_point);
+  float delta_y = old_point.y() - new_point.y();
+  if (delta_y == 0.0f) {
+    return;
+  }
+
+  // To minimize jarring visible effects, we de-jelly differently at
+  // different magnitudes of |delta_y|. This is controlled by three variables:
+  // kLinearDeJellyStart, kFixedDeJellyStart, kZeroDeJellyStart.
+  //                              _____________
+  //                  |     |    _/|           |
+  // de_jelly_delta_y |     |  _/  |           |
+  //                  |_____|_/    |           |_______________
+  //                  +----------------------------------------
+  //                        kLinear   kFixed          kZero
+  //
+  const float kLinearDeJellyStart = 2.0f;
+  const float kFixedDeJellyStart =
+      viz::MaxDeJellyHeight() + kLinearDeJellyStart;
+  const float kZeroDeJellyStart = 100.0f + kLinearDeJellyStart;
+  float sign = std::abs(delta_y) / delta_y;
+  float de_jelly_delta_y = std::abs(delta_y);
+  if (de_jelly_delta_y > kZeroDeJellyStart) {
+    de_jelly_delta_y = 0.0f;
+  } else if (de_jelly_delta_y > kFixedDeJellyStart) {
+    de_jelly_delta_y = kFixedDeJellyStart - kLinearDeJellyStart;
+  } else if (de_jelly_delta_y > kLinearDeJellyStart) {
+    de_jelly_delta_y = std::max(0.0f, de_jelly_delta_y - kLinearDeJellyStart);
+  } else {
+    de_jelly_delta_y = 0.0f;
+  }
+  // Re-apply the sign.
+  de_jelly_delta_y *= sign;
+  if (de_jelly_delta_y == 0.0f) {
+    return;
+  }
+
+  state->de_jelly_delta_y = de_jelly_delta_y;
+}
+
+}  // namespace cc
diff --git a/cc/trees/de_jelly_state.h b/cc/trees/de_jelly_state.h
new file mode 100644
index 0000000..00c83a4c
--- /dev/null
+++ b/cc/trees/de_jelly_state.h
@@ -0,0 +1,51 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CC_TREES_DE_JELLY_STATE_H_
+#define CC_TREES_DE_JELLY_STATE_H_
+
+#include <map>
+
+#include "base/containers/flat_map.h"
+#include "base/no_destructor.h"
+#include "base/optional.h"
+#include "cc/cc_export.h"
+#include "ui/gfx/transform.h"
+
+namespace viz {
+class SharedQuadState;
+class RenderPass;
+}  // namespace viz
+
+namespace cc {
+class LayerTreeImpl;
+
+// Helper class which tracks the movement of layers and renderpasses
+// and computes the |de_jelly_delta_y| for their SharedQuadState.
+class CC_EXPORT DeJellyState {
+ public:
+  DeJellyState();
+  ~DeJellyState();
+
+  // Called once per frame to move tracking structure to the next frame and
+  // determine if we should apply de-jelly at all.
+  void AdvanceFrame(LayerTreeImpl* layer_tree_impl);
+
+  // Populates |de_jelly_delta_y| for the most recent SharedQuadState on
+  // |target_render_pass|.
+  void UpdateSharedQuadState(LayerTreeImpl* layer_tree_impl,
+                             int transform_id,
+                             viz::RenderPass* target_render_pass);
+
+ private:
+  bool should_de_jelly_ = false;
+  int scroll_transform_node_ = 0;
+  base::Optional<gfx::Transform> new_scroll_node_transform_;
+  std::map<int, gfx::Transform> previous_transforms_;
+  std::map<int, gfx::Transform> new_transforms_;
+};
+
+}  // namespace cc
+
+#endif  // CC_TREES_DE_JELLY_STATE_H_
diff --git a/cc/trees/draw_property_utils.cc b/cc/trees/draw_property_utils.cc
index 5a41d0c..ff9a8c68 100644
--- a/cc/trees/draw_property_utils.cc
+++ b/cc/trees/draw_property_utils.cc
@@ -22,6 +22,7 @@
 #include "cc/trees/property_tree_builder.h"
 #include "cc/trees/scroll_node.h"
 #include "cc/trees/transform_node.h"
+#include "components/viz/common/display/de_jelly.h"
 #include "ui/gfx/geometry/rect_conversions.h"
 
 namespace cc {
@@ -642,6 +643,9 @@
   clip_in_layer_space.Offset(-layer->offset_to_transform_parent());
 
   gfx::Rect visible_rect = ToEnclosingClipRect(clip_in_layer_space);
+  if (layer->layer_tree_impl()->settings().allow_de_jelly_effect) {
+    visible_rect.Inset(0.0f, -viz::MaxDeJellyHeight());
+  }
   visible_rect.Intersect(layer_content_rect);
   return visible_rect;
 }
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc
index 9b33a564..0a9a54d 100644
--- a/cc/trees/layer_tree_host_impl.cc
+++ b/cc/trees/layer_tree_host_impl.cc
@@ -1228,6 +1228,9 @@
       active_tree()->property_trees()->effect_tree.HasCopyRequests();
   bool have_missing_animated_tiles = false;
 
+  // Advance our de-jelly state. This is a no-op if de-jelly is not active.
+  de_jelly_state_.AdvanceFrame(active_tree_.get());
+
   for (EffectTreeLayerListIterator it(active_tree());
        it.state() != EffectTreeLayerListIterator::State::END; ++it) {
     auto target_render_pass_id = it.target_render_surface()->id();
@@ -1251,6 +1254,11 @@
       if (render_surface->contributes_to_drawn_surface()) {
         render_surface->AppendQuads(draw_mode, target_render_pass,
                                     &append_quads_data);
+        if (settings_.allow_de_jelly_effect) {
+          de_jelly_state_.UpdateSharedQuadState(
+              active_tree_.get(), render_surface->TransformTreeIndex(),
+              target_render_pass);
+        }
       }
     } else if (it.state() == EffectTreeLayerListIterator::State::LAYER) {
       LayerImpl* layer = it.current_layer();
@@ -1262,6 +1270,11 @@
           frame->may_contain_video = true;
 
         layer->AppendQuads(target_render_pass, &append_quads_data);
+        if (settings_.allow_de_jelly_effect) {
+          de_jelly_state_.UpdateSharedQuadState(active_tree_.get(),
+                                                layer->transform_tree_index(),
+                                                target_render_pass);
+        }
       }
 
       rendering_stats_instrumentation_->AddVisibleContentArea(
diff --git a/cc/trees/layer_tree_host_impl.h b/cc/trees/layer_tree_host_impl.h
index 08185ce..c5bfb94 100644
--- a/cc/trees/layer_tree_host_impl.h
+++ b/cc/trees/layer_tree_host_impl.h
@@ -40,6 +40,7 @@
 #include "cc/tiles/image_decode_cache.h"
 #include "cc/tiles/tile_manager.h"
 #include "cc/trees/animated_paint_worklet_tracker.h"
+#include "cc/trees/de_jelly_state.h"
 #include "cc/trees/layer_tree_frame_sink_client.h"
 #include "cc/trees/layer_tree_host.h"
 #include "cc/trees/layer_tree_mutator.h"
@@ -1277,6 +1278,9 @@
   // invalidating PaintWorklets as the property values change.
   AnimatedPaintWorkletTracker paint_worklet_tracker_;
 
+  // Helper for de-jelly logic.
+  DeJellyState de_jelly_state_;
+
   // Must be the last member to ensure this is destroyed first in the
   // destruction order and invalidates all weak pointers.
   base::WeakPtrFactory<LayerTreeHostImpl> weak_factory_{this};
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc
index 6742dda..44261f42 100644
--- a/cc/trees/layer_tree_host_unittest.cc
+++ b/cc/trees/layer_tree_host_unittest.cc
@@ -966,13 +966,13 @@
     switch (layer_tree_host()->SourceFrameNumber()) {
       case 1:
         child_->SetForceRenderSurfaceForTesting(true);
-        child_->AddMainThreadScrollingReasons(
-            MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects);
+        // Add a non-fast region to ensure a scroll node is created.
+        child_->SetNonFastScrollableRegion(Region(gfx::Rect(50, 50, 50, 50)));
         break;
       case 2:
         child_->SetForceRenderSurfaceForTesting(false);
-        child_->ClearMainThreadScrollingReasons(
-            MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects);
+        // Remove the non-fast region to ensure a scroll node is removed.
+        child_->SetNonFastScrollableRegion(Region());
         break;
     }
   }
diff --git a/cc/trees/layer_tree_host_unittest_scroll.cc b/cc/trees/layer_tree_host_unittest_scroll.cc
index 8df1a975..bbf1adcb 100644
--- a/cc/trees/layer_tree_host_unittest_scroll.cc
+++ b/cc/trees/layer_tree_host_unittest_scroll.cc
@@ -1220,7 +1220,9 @@
 class LayerTreeHostScrollTestImplScrollUnderMainThreadScrollingParent
     : public LayerTreeHostScrollTest {
  public:
-  LayerTreeHostScrollTestImplScrollUnderMainThreadScrollingParent() = default;
+  LayerTreeHostScrollTestImplScrollUnderMainThreadScrollingParent() {
+    SetUseLayerLists();
+  }
 
   void BeginTest() override { PostSetNeedsCommitToMainThread(); }
 
diff --git a/cc/trees/layer_tree_settings.h b/cc/trees/layer_tree_settings.h
index 18d99c3..2c4a9f3 100644
--- a/cc/trees/layer_tree_settings.h
+++ b/cc/trees/layer_tree_settings.h
@@ -172,6 +172,9 @@
   // When false, we do not check for occlusion and all quads are drawn.
   // Defaults to true.
   bool enable_occlusion = true;
+
+  // Whether experimental de-jelly effect is allowed.
+  bool allow_de_jelly_effect = false;
 };
 
 class CC_EXPORT LayerListSettings : public LayerTreeSettings {
diff --git a/cc/trees/property_tree.h b/cc/trees/property_tree.h
index 01b096e..788ba617 100644
--- a/cc/trees/property_tree.h
+++ b/cc/trees/property_tree.h
@@ -395,6 +395,7 @@
   int CurrentlyScrollingNodeId() const;
 #endif
   void set_currently_scrolling_node(int scroll_node_id);
+  int currently_scrolling_node() const { return currently_scrolling_node_id_; }
   gfx::Transform ScreenSpaceTransform(int scroll_node_id) const;
 
   gfx::Vector2dF ClampScrollToMaxScrollOffset(ScrollNode* node, LayerTreeImpl*);
diff --git a/cc/trees/property_tree_builder.cc b/cc/trees/property_tree_builder.cc
index 5cb5415..601f6d9 100644
--- a/cc/trees/property_tree_builder.cc
+++ b/cc/trees/property_tree_builder.cc
@@ -37,10 +37,8 @@
   int scroll_tree_parent;
   int closest_ancestor_with_cached_render_surface;
   int closest_ancestor_with_copy_request;
-  uint32_t main_thread_scrolling_reasons;
   SkColor safe_opaque_background_color;
   bool should_flatten;
-  bool scroll_tree_parent_created_by_uninheritable_criteria;
   bool animation_axis_aligned_since_render_target;
   bool not_axis_aligned_since_last_clip;
   gfx::Transform compound_transform_since_render_target;
@@ -646,21 +644,9 @@
   bool scrollable = layer->scrollable();
   bool contains_non_fast_scrollable_region =
       !layer->non_fast_scrollable_region().IsEmpty();
-  uint32_t main_thread_scrolling_reasons =
-      layer->GetMainThreadScrollingReasons();
 
-  bool scroll_node_uninheritable_criteria =
-      is_root || scrollable || contains_non_fast_scrollable_region;
-  bool has_different_main_thread_scrolling_reasons =
-      main_thread_scrolling_reasons !=
-      data_from_ancestor.main_thread_scrolling_reasons;
   bool requires_node =
-      scroll_node_uninheritable_criteria ||
-      (main_thread_scrolling_reasons !=
-           MainThreadScrollingReason::kNotScrollingOnMain &&
-       (has_different_main_thread_scrolling_reasons ||
-        data_from_ancestor
-            .scroll_tree_parent_created_by_uninheritable_criteria));
+      is_root || scrollable || contains_non_fast_scrollable_region;
 
   int node_id;
   if (!requires_node) {
@@ -669,7 +655,6 @@
   } else {
     ScrollNode node;
     node.scrollable = scrollable;
-    node.main_thread_scrolling_reasons = main_thread_scrolling_reasons;
     node.bounds = layer->bounds();
     node.container_bounds = layer->scroll_container_bounds();
     node.offset_to_transform_parent = layer->offset_to_transform_parent();
@@ -682,10 +667,7 @@
 
     node_id = scroll_tree_.Insert(node, parent_id);
     data_for_children->scroll_tree_parent = node_id;
-    data_for_children->main_thread_scrolling_reasons =
-        node.main_thread_scrolling_reasons;
-    data_for_children->scroll_tree_parent_created_by_uninheritable_criteria =
-        scroll_node_uninheritable_criteria;
+
     // For animation subsystem purposes, if this layer has a compositor element
     // id, we build a map from that id to this scroll node.
     if (layer->element_id()) {
@@ -805,10 +787,6 @@
   data_for_recursion.closest_ancestor_with_copy_request =
       EffectTree::kInvalidNodeId;
   data_for_recursion.should_flatten = false;
-  data_for_recursion.main_thread_scrolling_reasons =
-      MainThreadScrollingReason::kNotScrollingOnMain;
-  data_for_recursion.scroll_tree_parent_created_by_uninheritable_criteria =
-      true;
   data_for_recursion.compound_transform_since_render_target = gfx::Transform();
   data_for_recursion.animation_axis_aligned_since_render_target = true;
   data_for_recursion.not_axis_aligned_since_last_clip = false;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/MonochromeApplication.java b/chrome/android/java/src/org/chromium/chrome/browser/MonochromeApplication.java
index 1d6bdfde..823a2a5 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/MonochromeApplication.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/MonochromeApplication.java
@@ -40,6 +40,7 @@
         boolean bindToCaller = false;
         boolean ignoreVisibilityForImportance = false;
         ChildProcessCreationParams.set(getPackageName(), true /* isExternalService */,
-                LibraryProcessType.PROCESS_CHILD, bindToCaller, ignoreVisibilityForImportance);
+                LibraryProcessType.PROCESS_CHILD, bindToCaller, ignoreVisibilityForImportance,
+                null /* privilegedServicesName */, null /* sandboxedServicesName */);
     }
 }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/crash/PureJavaExceptionReporter.java b/chrome/android/java/src/org/chromium/chrome/browser/crash/PureJavaExceptionReporter.java
index 1d99073..844c4f6 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/crash/PureJavaExceptionReporter.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/crash/PureJavaExceptionReporter.java
@@ -180,9 +180,7 @@
         if (ChromeVersionInfo.isBetaBuild()) {
             return "beta";
         }
-        if (ChromeVersionInfo.isStableBuild()) {
-            return "stable";
-        }
+        // An empty string indicates the stable channel.
         return "";
     }
 
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java
index a84007f8..92d5936 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/SigninManager.java
@@ -519,7 +519,8 @@
         }
 
         // Trigger token requests via native.
-        mIdentityMutator.reloadAccountsFromSystem();
+        mIdentityMutator.reloadAllAccountsFromSystemWithPrimaryAccount(
+                mSignInState.mCoreAccountInfo.getId());
 
         if (mSignInState.isInteractive()) {
             // If signin was a user action, record that it succeeded.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java
index 004832c3..f1db7d9 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java
@@ -942,6 +942,7 @@
     @Override
     public void setSheetOffset(float offset, boolean shouldAnimate) {
         cancelAnimation();
+        if (mSheetContent == null) return;
 
         if (shouldAnimate) {
             float velocityY = getCurrentOffsetPx() - offset;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java
index 4f8465b91..04c73e7a 100644
--- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java
+++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr/VrBrowserControllerInputTest.java
@@ -23,6 +23,7 @@
 import org.junit.runner.RunWith;
 
 import org.chromium.base.test.util.CommandLineFlags;
+import org.chromium.base.test.util.DisabledTest;
 import org.chromium.base.test.util.Restriction;
 import org.chromium.chrome.browser.ChromeSwitches;
 import org.chromium.chrome.browser.history.HistoryPage;
@@ -357,6 +358,7 @@
      * Verifies that swiping up/down on the Daydream controller's touchpad
      * scrolls a native page while in the VR browser.
      */
+    @DisabledTest(message = "crbug.com/1005835")
     @Test
     @MediumTest
     public void testControllerScrollingNative() throws InterruptedException {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/signin/SigninManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/signin/SigninManagerTest.java
index 21efd081..c0499d14 100644
--- a/chrome/android/junit/src/org/chromium/chrome/browser/signin/SigninManagerTest.java
+++ b/chrome/android/junit/src/org/chromium/chrome/browser/signin/SigninManagerTest.java
@@ -221,7 +221,7 @@
                 .when(mIdentityManager)
                 .findExtendedAccountInfoForAccountWithRefreshTokenByEmailAddress(any());
         doReturn(true).when(mIdentityMutator).setPrimaryAccount(any());
-        doNothing().when(mIdentityMutator).reloadAccountsFromSystem();
+        doNothing().when(mIdentityMutator).reloadAllAccountsFromSystemWithPrimaryAccount(any());
 
         mSigninManager.onFirstRunCheckDone(); // Allow sign-in.
 
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd
index 00eca7d..d11c8dd1 100644
--- a/chrome/app/generated_resources.grd
+++ b/chrome/app/generated_resources.grd
@@ -9917,6 +9917,9 @@
       <message name="IDS_WEBAUTHN_TRANSPORT_POPUP_BLE" desc="Menu item text. The user selects this to verify their identity on a web site (i.e. sign in) using a security key (an external physical device for user authentication) connected to the user's computer over Bluetooth Low Energy.">
         Verify via Bluetooth
       </message>
+      <message name="IDS_WEBAUTHN_TRANSPORT_POPUP_PAIR_PHONE" desc="Menu item text. The user selects this to begin the process of pairing with a previously unknown smartphone.">
+        Pair with new phone
+      </message>
       <message name="IDS_WEBAUTHN_TRANSPORT_POPUP_ANOTHER_BLE" desc="Menu item text. The user selects this to verify their identity on a web site (i.e. sign in) using a Bluetooth security key (an external physical device for user authentication connected over Bluetooth Low Energy) that they haven't used on this computer before.">
         Add another Bluetooth security key
       </message>
@@ -9935,6 +9938,12 @@
       <message name="IDS_WEBAUTHN_CABLE_ACTIVATE_DESCRIPTION" desc="Contents of the dialog shown when the user tries to sign-in using a phone as a security key.">
         A notification was sent to your phone to confirm it's you.
       </message>
+      <message name="IDS_WEBAUTHN_CABLE_QR_TITLE" desc="Title of a dialog that contains a QR-code for the user to scan with a mobile phone app. A QR code is a type of barcode that can be read using a smartphone's camera.">
+        Pair new phone
+      </message>
+      <message name="IDS_WEBAUTHN_CABLE_QR_DESCRIPTION" desc="Description text in a dialog that contains a QR-code for the user to scan with a mobile phone app. A QR code is a type of barcode that can be read using a smartphone's camera.">
+        Scan the QR code with a compatible authenticator app on your phone.
+      </message>
 
       <!-- WebAuthn authenticator PIN entry/setup -->
       <message name="IDS_WEBAUTHN_PIN_ENTRY_TITLE" desc="Title of the dialog shown when instructing the user to enter the PIN code to use a security key (an external physical device for user authentication) with their computer.">
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp
index 27888da..313ae00f 100644
--- a/chrome/app/settings_strings.grdp
+++ b/chrome/app/settings_strings.grdp
@@ -3919,6 +3919,12 @@
     <message name="IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_TOOLTIP" desc="Tooltip for the primary account in accounts list in Settings describing how to sign out.">
       To sign out of the primary account on this device, click the time on your screen. In the menu that appears, click "Sign out".
     </message>
+    <message name="IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_TEXT" desc="Text for 'secondary accounts disabled' message in Settings page.">
+      Your administrator has disabled the addition of more Google Accounts
+    </message>
+    <message name="IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_CHILD_TEXT" desc="Text for 'secondary accounts disabled' message for child accounts in Settings page.">
+      Addition of more Google Accounts is disabled
+    </message>
     <message name="IDS_SETTINGS_ACCOUNT_MANAGER_SIGNED_OUT_ACCOUNT_PLACEHOLDER" desc="Placeholder text for the full name of a signed out account in Account Manager.">
       Sign in again
     </message>
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_CHILD_TEXT.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_CHILD_TEXT.png.sha1
new file mode 100644
index 0000000..2533f8a8
--- /dev/null
+++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_CHILD_TEXT.png.sha1
@@ -0,0 +1 @@
+a48d2f1e1daec23b6d1eaa419798e4d7a6f3288f
\ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_TEXT.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_TEXT.png.sha1
new file mode 100644
index 0000000..a05dd755f
--- /dev/null
+++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_TEXT.png.sha1
@@ -0,0 +1 @@
+5deacda50fb0c81717c34c677eaf6aec31ca3c3d
\ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn
index 46a1059..5792bda0 100644
--- a/chrome/browser/BUILD.gn
+++ b/chrome/browser/BUILD.gn
@@ -5768,6 +5768,8 @@
     sources += [
       "extensions/fake_safe_browsing_database_manager.cc",
       "extensions/fake_safe_browsing_database_manager.h",
+      "safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.cc",
+      "safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.h",
     ]
   }
 
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc
index f4b3899..e48e277 100644
--- a/chrome/browser/about_flags.cc
+++ b/chrome/browser/about_flags.cc
@@ -4203,11 +4203,10 @@
      FEATURE_VALUE_TYPE(printing::kAdvancedPpdAttributes)},
 #endif  // defined(OS_CHROMEOS)
 
-    {"enable-forbid-sync-xhr-in-page-dismissal",
-     flag_descriptions::kForbidSyncXHRInPageDismissalName,
-     flag_descriptions::kForbidSyncXHRInPageDismissalDescription,
-     kOsAll | kDeprecated,
-     FEATURE_VALUE_TYPE(blink::features::kForbidSyncXHRInPageDismissal)},
+    {"allow-sync-xhr-in-page-dismissal",
+     flag_descriptions::kAllowSyncXHRInPageDismissalName,
+     flag_descriptions::kAllowSyncXHRInPageDismissalDescription, kOsAll,
+     FEATURE_VALUE_TYPE(blink::features::kAllowSyncXHRInPageDismissal)},
 
     {"form-controls-refresh", flag_descriptions::kFormControlsRefreshName,
      flag_descriptions::kFormControlsRefreshDescription, kOsAll,
diff --git a/chrome/browser/android/autofill_assistant/assistant_collect_user_data_delegate.cc b/chrome/browser/android/autofill_assistant/assistant_collect_user_data_delegate.cc
index 283a16b..aa79361 100644
--- a/chrome/browser/android/autofill_assistant/assistant_collect_user_data_delegate.cc
+++ b/chrome/browser/android/autofill_assistant/assistant_collect_user_data_delegate.cc
@@ -13,10 +13,24 @@
 #include "chrome/browser/autofill/android/personal_data_manager_android.h"
 #include "chrome/browser/autofill/personal_data_manager_factory.h"
 #include "chrome/browser/profiles/profile_manager.h"
+#include "components/autofill/core/browser/autofill_data_util.h"
 
 using base::android::AttachCurrentThread;
 using base::android::JavaParamRef;
 
+namespace {
+// Converts a java string to native. Returns an empty string if input is null.
+std::string SafeConvertJavaStringToNative(
+    JNIEnv* env,
+    const base::android::JavaParamRef<jstring>& jstring) {
+  std::string native_string;
+  if (jstring) {
+    base::android::ConvertJavaStringToUTF8(env, jstring, &native_string);
+  }
+  return native_string;
+}
+}  // namespace
+
 namespace autofill_assistant {
 
 AssistantCollectUserDataDelegate::AssistantCollectUserDataDelegate(
@@ -38,23 +52,27 @@
     const base::android::JavaParamRef<jstring>& jpayer_name,
     const base::android::JavaParamRef<jstring>& jpayer_phone,
     const base::android::JavaParamRef<jstring>& jpayer_email) {
-  std::string name;
-  std::string phone;
-  std::string email;
+  std::string name = SafeConvertJavaStringToNative(env, jpayer_name);
+  std::string phone = SafeConvertJavaStringToNative(env, jpayer_phone);
+  std::string email = SafeConvertJavaStringToNative(env, jpayer_email);
 
-  if (jpayer_name) {
-    base::android::ConvertJavaStringToUTF8(env, jpayer_name, &name);
-  }
-
-  if (jpayer_phone) {
-    base::android::ConvertJavaStringToUTF8(env, jpayer_phone, &phone);
-  }
-
-  if (jpayer_email) {
-    base::android::ConvertJavaStringToUTF8(env, jpayer_email, &email);
-  }
-
-  ui_controller_->OnContactInfoChanged(name, phone, email);
+  auto contact_profile = std::make_unique<autofill::AutofillProfile>();
+  contact_profile->SetRawInfo(autofill::ServerFieldType::NAME_FULL,
+                              base::UTF8ToUTF16(name));
+  autofill::data_util::NameParts parts =
+      autofill::data_util::SplitName(base::UTF8ToUTF16(name));
+  contact_profile->SetRawInfo(autofill::ServerFieldType::NAME_FIRST,
+                              parts.given);
+  contact_profile->SetRawInfo(autofill::ServerFieldType::NAME_MIDDLE,
+                              parts.middle);
+  contact_profile->SetRawInfo(autofill::ServerFieldType::NAME_LAST,
+                              parts.family);
+  contact_profile->SetRawInfo(autofill::ServerFieldType::EMAIL_ADDRESS,
+                              base::UTF8ToUTF16(email));
+  contact_profile->SetRawInfo(
+      autofill::ServerFieldType::PHONE_HOME_WHOLE_NUMBER,
+      base::UTF8ToUTF16(phone));
+  ui_controller_->OnContactInfoChanged(std::move(contact_profile));
 }
 
 void AssistantCollectUserDataDelegate::OnShippingAddressChanged(
@@ -85,19 +103,6 @@
   autofill::PersonalDataManagerAndroid::PopulateNativeCreditCardFromJava(
       jcard, env, card.get());
 
-  auto guid = card->billing_address_id();
-  if (!guid.empty()) {
-    autofill::AutofillProfile* profile =
-        autofill::PersonalDataManagerFactory::GetForProfile(
-            ProfileManager::GetLastUsedProfile())
-            ->GetProfileByGUID(guid);
-    if (profile != nullptr) {
-      auto billing_address =
-          std::make_unique<autofill::AutofillProfile>(*profile);
-      ui_controller_->OnBillingAddressChanged(std::move(billing_address));
-    }
-  }
-
   ui_controller_->OnCreditCardChanged(std::move(card));
 }
 
@@ -120,10 +125,7 @@
     JNIEnv* env,
     const base::android::JavaParamRef<jobject>& jcaller,
     const base::android::JavaParamRef<jstring>& jidentifier) {
-  std::string identifier;
-  if (jidentifier) {
-    base::android::ConvertJavaStringToUTF8(env, jidentifier, &identifier);
-  }
+  std::string identifier = SafeConvertJavaStringToNative(env, jidentifier);
   ui_controller_->OnLoginChoiceChanged(identifier);
 }
 
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.cc b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
index 49d1315..4ab4514 100644
--- a/chrome/browser/android/autofill_assistant/ui_controller_android.cc
+++ b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
@@ -700,15 +700,9 @@
   ui_delegate_->SetShippingAddress(std::move(address));
 }
 
-void UiControllerAndroid::OnBillingAddressChanged(
-    std::unique_ptr<autofill::AutofillProfile> address) {
-  ui_delegate_->SetBillingAddress(std::move(address));
-}
-
-void UiControllerAndroid::OnContactInfoChanged(std::string name,
-                                               std::string phone,
-                                               std::string email) {
-  ui_delegate_->SetContactInfo(name, phone, email);
+void UiControllerAndroid::OnContactInfoChanged(
+    std::unique_ptr<autofill::AutofillProfile> profile) {
+  ui_delegate_->SetContactInfo(std::move(profile));
 }
 
 void UiControllerAndroid::OnCreditCardChanged(
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.h b/chrome/browser/android/autofill_assistant/ui_controller_android.h
index c317f63..fc6506b 100644
--- a/chrome/browser/android/autofill_assistant/ui_controller_android.h
+++ b/chrome/browser/android/autofill_assistant/ui_controller_android.h
@@ -115,11 +115,7 @@
   // Called by AssistantCollectUserDataDelegate:
   void OnShippingAddressChanged(
       std::unique_ptr<autofill::AutofillProfile> address);
-  void OnBillingAddressChanged(
-      std::unique_ptr<autofill::AutofillProfile> address);
-  void OnContactInfoChanged(std::string name,
-                            std::string phone,
-                            std::string email);
+  void OnContactInfoChanged(std::unique_ptr<autofill::AutofillProfile> profile);
   void OnCreditCardChanged(std::unique_ptr<autofill::CreditCard> card);
   void OnTermsAndConditionsChanged(TermsAndConditionsState state);
   void OnLoginChoiceChanged(std::string identifier);
diff --git a/chrome/browser/chromeos/crostini/ansible/ansible_management_service.cc b/chrome/browser/chromeos/crostini/ansible/ansible_management_service.cc
index 393abb0..a7a3f8cb 100644
--- a/chrome/browser/chromeos/crostini/ansible/ansible_management_service.cc
+++ b/chrome/browser/chromeos/crostini/ansible/ansible_management_service.cc
@@ -145,7 +145,7 @@
 
   vm_tools::cicerone::ApplyAnsiblePlaybookRequest request;
   request.set_owner_id(CryptohomeIdForProfile(profile_));
-  request.set_vm_name(std::move(kCrostiniDefaultContainerName));
+  request.set_vm_name(std::move(kCrostiniDefaultVmName));
   request.set_container_name(std::move(kCrostiniDefaultContainerName));
   request.set_playbook(std::move(playbook));
 
diff --git a/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.cc b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.cc
index 26f6fcbc..0054bc52 100644
--- a/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.cc
+++ b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.cc
@@ -31,8 +31,20 @@
     SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback) {
   DCHECK(!enable_user_input || attempts_left);
   DCHECK_GE(attempts_left, -1);
+  // There must be either no active PIN request, or the active request for which
+  // the PIN has already been entered.
   DCHECK(!pin_entered_callback_);
-  DCHECK(!pin_dialog_closed_callback_);
+
+  if (is_request_running() || !enable_user_input) {
+    // Don't allow re-requesting the PIN in the same dialog after an error,
+    // since the UI doesn't currently handle this in a user-friendly way.
+    // TODO(crbug.com/1001288): Remove this after the proper UI error feedback
+    // gets implemented in Ash.
+    if (is_request_running())
+      CloseSecurityTokenPinDialog();
+    std::move(pin_dialog_closed_callback).Run();
+    return;
+  }
 
   Reset();
 
@@ -63,17 +75,23 @@
 }
 
 void SecurityTokenPinDialogHostAshImpl::CloseSecurityTokenPinDialog() {
+  DCHECK(is_request_running());
+
   Reset();
   ash::LoginScreen::Get()->ClearSecurityTokenPinRequest();
 }
 
 void SecurityTokenPinDialogHostAshImpl::OnUserInputReceived(
     const std::string& user_input) {
+  DCHECK(is_request_running());
   DCHECK(!user_input.empty());
+
   std::move(pin_entered_callback_).Run(user_input);
 }
 
 void SecurityTokenPinDialogHostAshImpl::OnClosed() {
+  DCHECK(is_request_running());
+
   auto closed_callback = std::move(pin_dialog_closed_callback_);
   Reset();
   std::move(closed_callback).Run();
diff --git a/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h
index 829036f..1bbc139 100644
--- a/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h
+++ b/chrome/browser/chromeos/login/security_token_pin_dialog_host_ash_impl.h
@@ -35,6 +35,10 @@
   void CloseSecurityTokenPinDialog() override;
 
  private:
+  bool is_request_running() const {
+    return !pin_dialog_closed_callback_.is_null();
+  }
+
   // Called when the PIN entered by the user is received from the Ash Login/Lock
   // Screen UI.
   void OnUserInputReceived(const std::string& user_input);
@@ -45,7 +49,12 @@
   // started requests.
   void Reset();
 
+  // The callback to run when the user submits a non-empty input to the security
+  // token PIN dialog.
+  // Is non-empty iff the dialog is active and the input wasn't sent yet.
   SecurityTokenPinEnteredCallback pin_entered_callback_;
+  // The callback to run when the security token PIN dialog gets closed.
+  // Is non-empty iff the dialog is active.
   SecurityTokenPinDialogClosedCallback pin_dialog_closed_callback_;
 
   base::WeakPtrFactory<SecurityTokenPinDialogHostAshImpl> weak_ptr_factory_{
diff --git a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc
index eae4e077..3ecacd5 100644
--- a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc
+++ b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc
@@ -72,22 +72,22 @@
 
 // Returns true and sets |level| to a PolicyLevel if the policy has been set
 // at that level. Returns false if the policy has been set at the level of
-// DevicePolicyOptions::UNSET.
+// PolicyOptions::UNSET.
 bool GetPolicyLevel(bool has_policy_options,
-                    const em::DevicePolicyOptions& policy_option_proto,
+                    const em::PolicyOptions& policy_option_proto,
                     PolicyLevel* level) {
   if (!has_policy_options) {
     *level = POLICY_LEVEL_MANDATORY;
     return true;
   }
   switch (policy_option_proto.mode()) {
-    case em::DevicePolicyOptions::MANDATORY:
+    case em::PolicyOptions::MANDATORY:
       *level = POLICY_LEVEL_MANDATORY;
       return true;
-    case em::DevicePolicyOptions::RECOMMENDED:
+    case em::PolicyOptions::RECOMMENDED:
       *level = POLICY_LEVEL_RECOMMENDED;
       return true;
-    case em::DevicePolicyOptions::UNSET:
+    case em::PolicyOptions::UNSET:
       return false;
   }
 }
@@ -844,6 +844,20 @@
           nullptr);
     }
 
+    if (container.has_login_screen_spoken_feedback_enabled()) {
+      PolicyLevel level;
+      if (GetPolicyLevel(
+              container.has_login_screen_spoken_feedback_enabled_options(),
+              container.login_screen_spoken_feedback_enabled_options(),
+              &level)) {
+        policies->Set(key::kDeviceLoginScreenSpokenFeedbackEnabled, level,
+                      POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
+                      std::make_unique<base::Value>(
+                          container.login_screen_spoken_feedback_enabled()),
+                      nullptr);
+      }
+    }
+
     if (container.has_login_screen_default_high_contrast_enabled()) {
       policies->Set(key::kDeviceLoginScreenDefaultHighContrastEnabled,
                     POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
@@ -853,6 +867,19 @@
                     nullptr);
     }
 
+    if (container.has_login_screen_high_contrast_enabled()) {
+      PolicyLevel level;
+      if (GetPolicyLevel(
+              container.has_login_screen_high_contrast_enabled_options(),
+              container.login_screen_high_contrast_enabled_options(), &level)) {
+        policies->Set(key::kDeviceLoginScreenHighContrastEnabled, level,
+                      POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
+                      std::make_unique<base::Value>(
+                          container.login_screen_high_contrast_enabled()),
+                      nullptr);
+      }
+    }
+
     if (container.has_login_screen_default_screen_magnifier_type()) {
       policies->Set(key::kDeviceLoginScreenDefaultScreenMagnifierType,
                     POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
diff --git a/chrome/browser/chromeos/policy/login_profile_policy_provider.cc b/chrome/browser/chromeos/policy/login_profile_policy_provider.cc
index 2e7bb4d..8445959 100644
--- a/chrome/browser/chromeos/policy/login_profile_policy_provider.cc
+++ b/chrome/browser/chromeos/policy/login_profile_policy_provider.cc
@@ -40,6 +40,8 @@
     {key::kDeviceLoginScreenAutoSelectCertificateForUrls,
      key::kAutoSelectCertificateForUrls},
     {key::kDeviceLoginScreenLargeCursorEnabled, key::kLargeCursorEnabled},
+    {key::kDeviceLoginScreenSpokenFeedbackEnabled, key::kSpokenFeedbackEnabled},
+    {key::kDeviceLoginScreenHighContrastEnabled, key::kHighContrastEnabled},
 };
 
 const DevicePolicyToUserPolicyMapEntry kRecommendedDevicePoliciesMap[] = {
diff --git a/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc b/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc
index 2966f6a..a72c7cc 100644
--- a/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc
+++ b/chrome/browser/chromeos/policy/login_screen_accessibility_policy_browsertest.cc
@@ -89,10 +89,9 @@
 
   void RefreshDevicePolicyAndWaitForPrefChange(const char* pref_name);
 
-  // Returns the pref value only if it exists in the pref service and has the
-  // same policy being applied as mandatory when |is_managed| is true or as
-  // recommended when |is_managed| is false, otherwise returns an empty value.
-  base::Value GetPrefValue(const char* pref_name, bool is_managed) const;
+  bool IsPrefManaged(const char* pref_name) const;
+
+  base::Value GetPrefValue(const char* pref_name) const;
 
   Profile* login_profile_ = nullptr;
 
@@ -132,14 +131,18 @@
   command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests);
 }
 
-base::Value LoginScreenAccessibilityPolicyBrowsertest::GetPrefValue(
-    const char* pref_name,
-    bool is_managed) const {
+bool LoginScreenAccessibilityPolicyBrowsertest::IsPrefManaged(
+    const char* pref_name) const {
   const PrefService::Preference* pref =
       login_profile_->GetPrefs()->FindPreference(pref_name);
-  const bool is_recommended = pref && pref->IsRecommended() && !is_managed,
-             is_mandatory = pref && pref->IsManaged() && is_managed;
-  if (is_recommended || is_mandatory)
+  return pref && pref->IsManaged();
+}
+
+base::Value LoginScreenAccessibilityPolicyBrowsertest::GetPrefValue(
+    const char* pref_name) const {
+  const PrefService::Preference* pref =
+      login_profile_->GetPrefs()->FindPreference(pref_name);
+  if (pref)
     return pref->GetValue()->Clone();
   else
     return base::Value();
@@ -168,9 +171,9 @@
 
   // Verify that the pref which controls the large cursor in the login profile
   // is managed by the policy.
+  EXPECT_TRUE(IsPrefManaged(ash::prefs::kAccessibilityLargeCursorEnabled));
   EXPECT_EQ(base::Value(false),
-            GetPrefValue(ash::prefs::kAccessibilityLargeCursorEnabled,
-                         /*is_managed=*/true));
+            GetPrefValue(ash::prefs::kAccessibilityLargeCursorEnabled));
 
   // Verify that the large cursor cannot be enabled manually anymore.
   accessibility_manager->EnableLargeCursor(true);
@@ -197,7 +200,7 @@
       true);
   proto.mutable_accessibility_settings()
       ->mutable_login_screen_large_cursor_enabled_options()
-      ->set_mode(em::DevicePolicyOptions::RECOMMENDED);
+      ->set_mode(em::PolicyOptions::RECOMMENDED);
   proto.mutable_accessibility_settings()
       ->set_login_screen_default_large_cursor_enabled(false);
   RefreshDevicePolicyAndWaitForPrefChange(
@@ -205,9 +208,9 @@
 
   // Verify that the pref which controls the large cursor in the login profile
   // is managed by the policy and is enabled.
+  EXPECT_FALSE(IsPrefManaged(ash::prefs::kAccessibilityLargeCursorEnabled));
   EXPECT_EQ(base::Value(true),
-            GetPrefValue(ash::prefs::kAccessibilityLargeCursorEnabled,
-                         /*is_managed=*/false));
+            GetPrefValue(ash::prefs::kAccessibilityLargeCursorEnabled));
 
   // Disable the large cursor through DeviceLoginScreenLargeCursorEnabled device
   // policy, and enable it through DeviceLoginScreenDefaultLargeCursorEnabled;
@@ -216,7 +219,7 @@
       false);
   proto.mutable_accessibility_settings()
       ->mutable_login_screen_large_cursor_enabled_options()
-      ->set_mode(em::DevicePolicyOptions::RECOMMENDED);
+      ->set_mode(em::PolicyOptions::RECOMMENDED);
   proto.mutable_accessibility_settings()
       ->set_login_screen_default_large_cursor_enabled(true);
   RefreshDevicePolicyAndWaitForPrefChange(
@@ -224,9 +227,181 @@
 
   // Verify that the pref which controls the large cursor in the login profile
   // is managed by the policy and is disabled.
+  EXPECT_FALSE(IsPrefManaged(ash::prefs::kAccessibilityLargeCursorEnabled));
   EXPECT_EQ(base::Value(false),
-            GetPrefValue(ash::prefs::kAccessibilityLargeCursorEnabled,
-                         /*is_managed=*/false));
+            GetPrefValue(ash::prefs::kAccessibilityLargeCursorEnabled));
+}
+
+IN_PROC_BROWSER_TEST_F(LoginScreenAccessibilityPolicyBrowsertest,
+                       DeviceLoginScreenSpokenFeedbackEnabled) {
+  // Verifies that the state of the spoken feedback accessibility feature on the
+  // login screen can be controlled through device policy.
+  chromeos::AccessibilityManager* accessibility_manager =
+      chromeos::AccessibilityManager::Get();
+  ASSERT_TRUE(accessibility_manager);
+  EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
+
+  // Manually enable the spoken feedback.
+  accessibility_manager->EnableSpokenFeedback(true);
+  EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
+
+  // Disable the spoken feedback through device policy and wait for the change
+  // to take effect.
+  em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_spoken_feedback_enabled(false);
+  RefreshDevicePolicyAndWaitForPrefChange(
+      ash::prefs::kAccessibilitySpokenFeedbackEnabled);
+
+  // Verify that the pref which controls the spoken feedback in the login
+  // profile is managed by the policy.
+  EXPECT_TRUE(IsPrefManaged(ash::prefs::kAccessibilitySpokenFeedbackEnabled));
+  EXPECT_EQ(base::Value(false),
+            GetPrefValue(ash::prefs::kAccessibilitySpokenFeedbackEnabled));
+
+  // Verify that the spoken feedback cannot be enabled manually anymore.
+  accessibility_manager->EnableSpokenFeedback(true);
+  EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
+}
+
+IN_PROC_BROWSER_TEST_F(LoginScreenAccessibilityPolicyBrowsertest,
+                       SpokenFeedbackEnabledOverridesDefaultPolicy) {
+  // Verifies that the state of the spoken feedback accessibility feature on the
+  // login screen will be controlled only through
+  // DeviceLoginScreenSpokenFeedbackEnabled device policy if both of
+  // DeviceLoginScreenSpokenFeedbackEnabled and
+  // DeviceLoginScreenDefaultSpokenFeedbackEnabled have been set.
+  chromeos::AccessibilityManager* accessibility_manager =
+      chromeos::AccessibilityManager::Get();
+  ASSERT_TRUE(accessibility_manager);
+  EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
+
+  // Enable the spoken feedback through DeviceLoginScreenSpokenFeedbackEnabled
+  // device policy, and disable it through
+  // DeviceLoginScreenDefaultSpokenFeedbackEnabled; then wait for the change to
+  // take effect.
+  em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_spoken_feedback_enabled(true);
+  proto.mutable_accessibility_settings()
+      ->mutable_login_screen_spoken_feedback_enabled_options()
+      ->set_mode(em::PolicyOptions::RECOMMENDED);
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_default_spoken_feedback_enabled(false);
+  RefreshDevicePolicyAndWaitForPrefChange(
+      ash::prefs::kAccessibilitySpokenFeedbackEnabled);
+
+  // Verify that the pref which controls the spoken feedback in the login
+  // profile is managed by the policy and is enabled.
+  EXPECT_FALSE(IsPrefManaged(ash::prefs::kAccessibilitySpokenFeedbackEnabled));
+  EXPECT_EQ(base::Value(true),
+            GetPrefValue(ash::prefs::kAccessibilitySpokenFeedbackEnabled));
+
+  // Disable the spoken feedback through DeviceLoginScreenSpokenFeedbackEnabled
+  // device policy, and enable it through
+  // DeviceLoginScreenDefaultSpokenFeedbackEnabled; then wait for the change to
+  // take effect.
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_spoken_feedback_enabled(false);
+  proto.mutable_accessibility_settings()
+      ->mutable_login_screen_spoken_feedback_enabled_options()
+      ->set_mode(em::PolicyOptions::RECOMMENDED);
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_default_spoken_feedback_enabled(true);
+  RefreshDevicePolicyAndWaitForPrefChange(
+      ash::prefs::kAccessibilitySpokenFeedbackEnabled);
+
+  // Verify that the pref which controls the spoken feedback in the login
+  // profile is managed by the policy and is disabled.
+  EXPECT_FALSE(IsPrefManaged(ash::prefs::kAccessibilitySpokenFeedbackEnabled));
+  EXPECT_EQ(base::Value(false),
+            GetPrefValue(ash::prefs::kAccessibilitySpokenFeedbackEnabled));
+}
+
+IN_PROC_BROWSER_TEST_F(LoginScreenAccessibilityPolicyBrowsertest,
+                       DeviceLoginScreenHighContrastEnabled) {
+  // Verifies that the state of the high contrast accessibility feature on the
+  // login screen can be controlled through device policy.
+  chromeos::AccessibilityManager* accessibility_manager =
+      chromeos::AccessibilityManager::Get();
+  ASSERT_TRUE(accessibility_manager);
+  EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
+
+  // Manually enable the high contrast.
+  accessibility_manager->EnableHighContrast(true);
+  EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
+
+  // Disable the high contrast through device policy and wait for the change
+  // to take effect.
+  em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_high_contrast_enabled(false);
+  RefreshDevicePolicyAndWaitForPrefChange(
+      ash::prefs::kAccessibilityHighContrastEnabled);
+
+  // Verify that the pref which controls the high contrast in the login
+  // profile is managed by the policy.
+  EXPECT_TRUE(IsPrefManaged(ash::prefs::kAccessibilityHighContrastEnabled));
+  EXPECT_EQ(base::Value(false),
+            GetPrefValue(ash::prefs::kAccessibilityHighContrastEnabled));
+
+  // Verify that the high contrast cannot be enabled manually anymore.
+  accessibility_manager->EnableHighContrast(true);
+  EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
+}
+
+IN_PROC_BROWSER_TEST_F(LoginScreenAccessibilityPolicyBrowsertest,
+                       HighContrastEnabledOverridesDefaultPolicy) {
+  // Verifies that the state of the high contrast accessibility feature on the
+  // login screen will be controlled only through
+  // DeviceLoginScreenHighContrastEnabled device policy if both of
+  // DeviceLoginScreenHighContrastEnabled and
+  // DeviceLoginScreenDefaultHighContrastEnabled have been set.
+  chromeos::AccessibilityManager* accessibility_manager =
+      chromeos::AccessibilityManager::Get();
+  ASSERT_TRUE(accessibility_manager);
+  EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
+
+  // Enable the high contrast through DeviceLoginScreenHighContrastEnabled
+  // device policy, and disable it through
+  // DeviceLoginScreenDefaultHighContrastEnabled; then wait for the change to
+  // take effect.
+  em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_high_contrast_enabled(true);
+  proto.mutable_accessibility_settings()
+      ->mutable_login_screen_high_contrast_enabled_options()
+      ->set_mode(em::PolicyOptions::RECOMMENDED);
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_default_high_contrast_enabled(false);
+  RefreshDevicePolicyAndWaitForPrefChange(
+      ash::prefs::kAccessibilityHighContrastEnabled);
+
+  // Verify that the pref which controls the high contrast in the login
+  // profile is managed by the policy and is enabled.
+  EXPECT_FALSE(IsPrefManaged(ash::prefs::kAccessibilityHighContrastEnabled));
+  EXPECT_EQ(base::Value(true),
+            GetPrefValue(ash::prefs::kAccessibilityHighContrastEnabled));
+
+  // Disable the high contrast through DeviceLoginScreenHighContrastEnabled
+  // device policy, and enable it through
+  // DeviceLoginScreenDefaultHighContrastEnabled; then wait for the change to
+  // take effect.
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_high_contrast_enabled(false);
+  proto.mutable_accessibility_settings()
+      ->mutable_login_screen_high_contrast_enabled_options()
+      ->set_mode(em::PolicyOptions::RECOMMENDED);
+  proto.mutable_accessibility_settings()
+      ->set_login_screen_default_high_contrast_enabled(true);
+  RefreshDevicePolicyAndWaitForPrefChange(
+      ash::prefs::kAccessibilityHighContrastEnabled);
+
+  // Verify that the pref which controls the high contrast in the login
+  // profile is managed by the policy and is disabled.
+  EXPECT_FALSE(IsPrefManaged(ash::prefs::kAccessibilityHighContrastEnabled));
+  EXPECT_EQ(base::Value(false),
+            GetPrefValue(ash::prefs::kAccessibilityHighContrastEnabled));
 }
 
 }  // namespace policy
diff --git a/chrome/browser/chromeos/release_notes/release_notes_storage.cc b/chrome/browser/chromeos/release_notes/release_notes_storage.cc
index 4cae3ba..dad47d7 100644
--- a/chrome/browser/chromeos/release_notes/release_notes_storage.cc
+++ b/chrome/browser/chromeos/release_notes/release_notes_storage.cc
@@ -54,6 +54,10 @@
     return false;
   }
 
+  // Only shows notification in stable channel.
+  if (!chrome::GetChannelName().empty())
+    return false;
+
   std::string user_email = profile_->GetProfileUserName();
   if (base::EndsWith(user_email, "@google.com",
                      base::CompareCase::INSENSITIVE_ASCII) ||
diff --git a/chrome/browser/chromeos/system_token_cert_db_initializer.cc b/chrome/browser/chromeos/system_token_cert_db_initializer.cc
index 6ea2e78..2252348c 100644
--- a/chrome/browser/chromeos/system_token_cert_db_initializer.cc
+++ b/chrome/browser/chromeos/system_token_cert_db_initializer.cc
@@ -15,7 +15,6 @@
 #include "build/branding_buildflags.h"
 #include "build/buildflag.h"
 #include "chrome/browser/chromeos/login/startup_utils.h"
-#include "chromeos/dbus/cryptohome/cryptohome_client.h"
 #include "chromeos/dbus/dbus_method_call_status.h"
 #include "chromeos/network/network_cert_loader.h"
 #include "chromeos/tpm/tpm_token_loader.h"
@@ -86,7 +85,21 @@
 
 SystemTokenCertDBInitializer::~SystemTokenCertDBInitializer() = default;
 
-void SystemTokenCertDBInitializer::ShutDown() {}
+void SystemTokenCertDBInitializer::ShutDown() {
+  // Note that the observer could potentially not be added yet, but
+  // RemoveObserver() is a no-op in that case.
+  CryptohomeClient::Get()->RemoveObserver(this);
+}
+
+void SystemTokenCertDBInitializer::TpmInitStatusUpdated(
+    bool ready,
+    bool owned,
+    bool was_owned_this_boot) {
+  if (ready) {
+    // The TPM "ready" means that it's available && owned && not being owned.
+    MaybeStartInitializingDatabase();
+  }
+}
 
 void SystemTokenCertDBInitializer::OnCryptohomeAvailable(bool available) {
   if (!available) {
@@ -96,6 +109,7 @@
   }
 
   VLOG(1) << "SystemTokenCertDBInitializer: Cryptohome available.";
+  CryptohomeClient::Get()->AddObserver(this);
   CryptohomeClient::Get()->TpmIsReady(
       base::BindOnce(&SystemTokenCertDBInitializer::OnGotTpmIsReady,
                      weak_ptr_factory_.GetWeakPtr()));
@@ -118,6 +132,13 @@
 
     return;
   }
+  MaybeStartInitializingDatabase();
+}
+
+void SystemTokenCertDBInitializer::MaybeStartInitializingDatabase() {
+  if (started_initializing_)
+    return;
+  started_initializing_ = true;
   VLOG(1)
       << "SystemTokenCertDBInitializer: TPM is ready, loading system token.";
   TPMTokenLoader::Get()->EnsureStarted();
diff --git a/chrome/browser/chromeos/system_token_cert_db_initializer.h b/chrome/browser/chromeos/system_token_cert_db_initializer.h
index e25ee581..5167724 100644
--- a/chrome/browser/chromeos/system_token_cert_db_initializer.h
+++ b/chrome/browser/chromeos/system_token_cert_db_initializer.h
@@ -10,6 +10,7 @@
 #include "base/macros.h"
 #include "base/memory/weak_ptr.h"
 #include "base/optional.h"
+#include "chromeos/dbus/cryptohome/cryptohome_client.h"
 #include "crypto/scoped_nss_types.h"
 
 namespace net {
@@ -26,27 +27,39 @@
 // ShutDown() has been called, but must be outlived by this object.
 //
 // All of the methods must be called on the UI thread.
-class SystemTokenCertDBInitializer final {
+class SystemTokenCertDBInitializer final : public CryptohomeClient::Observer {
  public:
   SystemTokenCertDBInitializer();
-  ~SystemTokenCertDBInitializer();
+  ~SystemTokenCertDBInitializer() override;
 
   // Stops making new requests to D-Bus services.
   void ShutDown();
 
+  // CryptohomeClient::Observer:
+  void TpmInitStatusUpdated(bool ready,
+                            bool owned,
+                            bool was_owned_this_boot) override;
+
  private:
   // Called once the cryptohome service is available.
   void OnCryptohomeAvailable(bool available);
 
   // This is a callback for the cryptohome TpmIsReady query. Note that this is
   // not a listener which would be called once TPM becomes ready if it was not
-  // ready on startup (e.g. after device enrollment), see crbug.com/725500.
+  // ready on startup - that event is observed by TpmInitStatusUpdated().
   void OnGotTpmIsReady(base::Optional<bool> tpm_is_ready);
 
+  // Starts loading the system slot and initializing the corresponding NSS cert
+  // database, unless it was already started before.
+  void MaybeStartInitializingDatabase();
+
   // Initializes the global system token NSSCertDatabase with |system_slot|.
   // Also starts NetworkCertLoader with the system token database.
   void InitializeDatabase(crypto::ScopedPK11Slot system_slot);
 
+  // Whether the database initialization was started.
+  bool started_initializing_ = false;
+
   // Global NSSCertDatabase which sees the system token.
   std::unique_ptr<net::NSSCertDatabase> system_token_cert_database_;
 
diff --git a/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc b/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc
index febd21f..3d664ad3 100644
--- a/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc
+++ b/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc
@@ -121,8 +121,9 @@
                          ManagementApiNonPersistentApiTest,
                          ::testing::Values(ContextType::kEventPage));
 
-INSTANTIATE_TEST_SUITE_P(ServiceWorker,
-                         ManagementApiNonPersistentApiTest,
-                         ::testing::Values(ContextType::kServiceWorker));
+// Flaky: crbug.com/1003597
+// INSTANTIATE_TEST_SUITE_P(ServiceWorker,
+//                          ManagementApiNonPersistentApiTest,
+//                          ::testing::Values(ContextType::kServiceWorker));
 
 }  // namespace extensions
diff --git a/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chrome/browser/extensions/api/settings_private/prefs_util.cc
index 37478e1..89f6c0f 100644
--- a/chrome/browser/extensions/api/settings_private/prefs_util.cc
+++ b/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -56,6 +56,7 @@
 #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.h"
 #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.h"
 #include "chromeos/constants/chromeos_features.h"
+#include "chromeos/constants/chromeos_pref_names.h"
 #include "chromeos/services/assistant/public/cpp/assistant_prefs.h"
 #include "chromeos/settings/cros_settings_names.h"
 #include "components/arc/arc_prefs.h"
@@ -344,6 +345,8 @@
       settings_api::PrefType::PREF_TYPE_BOOLEAN;
   (*s_whitelist)[chromeos::kAccountsPrefUsers] =
       settings_api::PrefType::PREF_TYPE_LIST;
+  (*s_whitelist)[chromeos::prefs::kSecondaryGoogleAccountSigninAllowed] =
+      settings_api::PrefType::PREF_TYPE_BOOLEAN;
   // kEnableAutoScreenLock is read-only.
   (*s_whitelist)[ash::prefs::kEnableAutoScreenLock] =
       settings_api::PrefType::PREF_TYPE_BOOLEAN;
@@ -753,8 +756,13 @@
 #endif
 
   if (pref && pref->IsManaged()) {
-    pref_object->controlled_by =
-        settings_api::ControlledBy::CONTROLLED_BY_USER_POLICY;
+    if (profile_->IsChild()) {
+      pref_object->controlled_by =
+          settings_api::ControlledBy::CONTROLLED_BY_CHILD_RESTRICTION;
+    } else {
+      pref_object->controlled_by =
+          settings_api::ControlledBy::CONTROLLED_BY_USER_POLICY;
+    }
     pref_object->enforcement = settings_api::Enforcement::ENFORCEMENT_ENFORCED;
     return pref_object;
   }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json
index 96d637f..ab9c91f 100644
--- a/chrome/browser/flag-metadata.json
+++ b/chrome/browser/flag-metadata.json
@@ -78,6 +78,11 @@
     "expiry_milestone": 83
   },
   {
+    "name": "allow-sync-xhr-in-page-dismissal",
+    "owners": [ "kdillon@chromium.org" ],
+    "expiry_milestone": 82
+  },
+  {
     "name": "android-files-in-files-app",
     "owners": [ "fukino" ],
     "expiry_milestone": 76
@@ -1228,11 +1233,6 @@
     "expiry_milestone": 80
   },
   {
-    "name": "enable-forbid-sync-xhr-in-page-dismissal",
-    "owners": [ "kdillon@chromium.org" ],
-    "expiry_milestone": 82
-  },
-  {
     "name": "enable-force-dark",
     "owners": [ "gilmanmh@google.com" ],
     "expiry_milestone": 80
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc
index 4025398e..6d7c1cf 100644
--- a/chrome/browser/flag_descriptions.cc
+++ b/chrome/browser/flag_descriptions.cc
@@ -46,6 +46,12 @@
     "that do not have CanSignHttpExchangesDraft extension. Warning: Enabling "
     "this may pose a security risk.";
 
+const char kAllowSyncXHRInPageDismissalName[] =
+    "Allows synchronous XHR requests in page dismissal";
+const char kAllowSyncXHRInPageDismissalDescription[] =
+    "Allows synchronous XHR requests during page dismissal when the page is "
+    "being navigated away or closed by the user.";
+
 const char kEnableSignedExchangeSubresourcePrefetchName[] =
     "Enable Signed Exchange subresource prefetching";
 const char kEnableSignedExchangeSubresourcePrefetchDescription[] =
@@ -1087,12 +1093,6 @@
     "Filling of passwords when an account is explicitly selected by the user "
     "rather than autofilling credentials on page load on HTTP origins.";
 
-const char kForbidSyncXHRInPageDismissalName[] =
-    "Forbid synchronous XHR requests in page dismissal";
-const char kForbidSyncXHRInPageDismissalDescription[] =
-    "Disallow synchronous XHR requests during page dismissal when the page is "
-    "being navigated away or closed by the user.";
-
 const char kForceTextDirectionName[] = "Force text direction";
 const char kForceTextDirectionDescription[] =
     "Explicitly force the per-character directionality of UI text to "
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h
index 47f99fa5..d307a28 100644
--- a/chrome/browser/flag_descriptions.h
+++ b/chrome/browser/flag_descriptions.h
@@ -65,6 +65,9 @@
 extern const char kAllowSignedHTTPExchangeCertsWithoutExtensionName[];
 extern const char kAllowSignedHTTPExchangeCertsWithoutExtensionDescription[];
 
+extern const char kAllowSyncXHRInPageDismissalName[];
+extern const char kAllowSyncXHRInPageDismissalDescription[];
+
 extern const char kEnableSignedExchangeSubresourcePrefetchName[];
 extern const char kEnableSignedExchangeSubresourcePrefetchDescription[];
 
@@ -652,9 +655,6 @@
 extern const char kFocusMode[];
 extern const char kFocusModeDescription[];
 
-extern const char kForbidSyncXHRInPageDismissalName[];
-extern const char kForbidSyncXHRInPageDismissalDescription[];
-
 extern const char kForceTextDirectionName[];
 extern const char kForceTextDirectionDescription[];
 extern const char kForceDirectionLtr[];
diff --git a/chrome/browser/media/cast_mirroring_service_host.cc b/chrome/browser/media/cast_mirroring_service_host.cc
index 894ce29..298b0f2 100644
--- a/chrome/browser/media/cast_mirroring_service_host.cc
+++ b/chrome/browser/media/cast_mirroring_service_host.cc
@@ -169,7 +169,6 @@
 CastMirroringServiceHost::CastMirroringServiceHost(
     content::DesktopMediaID source_media_id)
     : source_media_id_(source_media_id),
-      resource_provider_binding_(this),
       gpu_client_(nullptr, base::OnTaskRunnerDeleter(nullptr)) {
   // Observe the target WebContents for Tab mirroring.
   if (source_media_id_.type == content::DesktopMediaID::TYPE_WEB_CONTENTS)
@@ -180,7 +179,7 @@
 
 void CastMirroringServiceHost::Start(
     mojom::SessionParametersPtr session_params,
-    mojom::SessionObserverPtr observer,
+    mojo::PendingRemote<mojom::SessionObserver> observer,
     mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel,
     mojo::PendingReceiver<mojom::CastMessageChannel> inbound_channel) {
   // Start() should not be called in the middle of a mirroring session.
@@ -198,8 +197,8 @@
           .WithDisplayName("Mirroring Service")
           .WithSandboxType(service_manager::SANDBOX_TYPE_UTILITY)
           .Pass());
-  mojom::ResourceProviderPtr provider;
-  resource_provider_binding_.Bind(mojo::MakeRequest(&provider));
+  mojo::PendingRemote<mojom::ResourceProvider> provider;
+  resource_provider_receiver.Bind(provider.InitWithNewPipeAndPassReceiver());
   mirroring_service_->Start(
       std::move(session_params), GetCaptureResolutionConstraint(),
       std::move(observer), std::move(provider), std::move(outbound_channel),
diff --git a/chrome/browser/media/cast_mirroring_service_host.h b/chrome/browser/media/cast_mirroring_service_host.h
index b40297e3..b5726c63 100644
--- a/chrome/browser/media/cast_mirroring_service_host.h
+++ b/chrome/browser/media/cast_mirroring_service_host.h
@@ -21,6 +21,7 @@
 #include "mojo/public/cpp/bindings/binding.h"
 #include "mojo/public/cpp/bindings/pending_receiver.h"
 #include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 #include "mojo/public/cpp/bindings/remote.h"
 #include "ui/gfx/geometry/size.h"
 
@@ -73,7 +74,7 @@
 
   // mojom::MirroringServiceHost implementation.
   void Start(mojom::SessionParametersPtr session_params,
-             mojom::SessionObserverPtr observer,
+             mojo::PendingRemote<mojom::SessionObserver> observer,
              mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel,
              mojo::PendingReceiver<mojom::CastMessageChannel> inbound_channel)
       override;
@@ -124,8 +125,8 @@
   // Describes the media source for this mirroring session.
   content::DesktopMediaID source_media_id_;
 
-  // The binding to this mojom::ResourceProvider implementation.
-  mojo::Binding<mojom::ResourceProvider> resource_provider_binding_;
+  // The receiver to this mojom::ResourceProvider implementation.
+  mojo::Receiver<mojom::ResourceProvider> resource_provider_receiver{this};
 
   // Connection to the remote mojom::MirroringService implementation.
   mojo::Remote<mojom::MirroringService> mirroring_service_;
diff --git a/chrome/browser/media/cast_mirroring_service_host_browsertest.cc b/chrome/browser/media/cast_mirroring_service_host_browsertest.cc
index c7471cd95f..96683b08 100644
--- a/chrome/browser/media/cast_mirroring_service_host_browsertest.cc
+++ b/chrome/browser/media/cast_mirroring_service_host_browsertest.cc
@@ -24,7 +24,6 @@
 #include "media/capture/video_capture_types.h"
 #include "media/mojo/mojom/audio_data_pipe.mojom.h"
 #include "media/mojo/mojom/audio_input_stream.mojom.h"
-#include "mojo/public/cpp/bindings/binding.h"
 #include "mojo/public/cpp/bindings/pending_remote.h"
 #include "mojo/public/cpp/bindings/receiver.h"
 #include "mojo/public/cpp/bindings/remote.h"
@@ -130,8 +129,8 @@
       public mojom::CastMessageChannel,
       public mojom::AudioStreamCreatorClient {
  public:
-  CastMirroringServiceHostBrowserTest() : observer_binding_(this) {}
-  ~CastMirroringServiceHostBrowserTest() override {}
+  CastMirroringServiceHostBrowserTest() = default;
+  ~CastMirroringServiceHostBrowserTest() override = default;
 
  protected:
   // Starts a tab mirroring session.
@@ -141,8 +140,8 @@
     ASSERT_TRUE(web_contents);
     host_ = std::make_unique<CastMirroringServiceHost>(
         BuildMediaIdForTabMirroring(web_contents));
-    mojom::SessionObserverPtr observer;
-    observer_binding_.Bind(mojo::MakeRequest(&observer));
+    mojo::PendingRemote<mojom::SessionObserver> observer;
+    observer_receiver_.Bind(observer.InitWithNewPipeAndPassReceiver());
     mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel;
     outbound_channel_receiver_.Bind(
         outbound_channel.InitWithNewPipeAndPassReceiver());
@@ -230,7 +229,7 @@
     OnAudioStreamCreated();
   }
 
-  mojo::Binding<mojom::SessionObserver> observer_binding_;
+  mojo::Receiver<mojom::SessionObserver> observer_receiver_{this};
   mojo::Receiver<mojom::CastMessageChannel> outbound_channel_receiver_{this};
   mojo::Receiver<mojom::AudioStreamCreatorClient> audio_client_receiver_{this};
   mojo::Remote<mojom::CastMessageChannel> inbound_channel_;
diff --git a/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc b/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc
index 7b503944..06306d5 100644
--- a/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc
+++ b/chrome/browser/media/router/providers/cast/mirroring_activity_record.cc
@@ -36,7 +36,6 @@
 using media_router::mojom::MediaRouteProvider;
 using media_router::mojom::MediaRouter;
 using mirroring::mojom::SessionError;
-using mirroring::mojom::SessionObserverPtr;
 using mirroring::mojom::SessionParameters;
 using mirroring::mojom::SessionType;
 
@@ -71,9 +70,9 @@
   media_router->GetMirroringServiceHostForTab(
       target_tab_id, host_.BindNewPipeAndPassReceiver());
 
-  // Create Mojo bindings for the interfaces this object implements.
-  SessionObserverPtr observer_ptr;
-  observer_binding_.Bind(mojo::MakeRequest(&observer_ptr));
+  // Bind Mojo receivers for the interfaces this object implements.
+  mojo::PendingRemote<mirroring::mojom::SessionObserver> observer_remote;
+  observer_receiver_.Bind(observer_remote.InitWithNewPipeAndPassReceiver());
   mojo::PendingRemote<mirroring::mojom::CastMessageChannel> channel_remote;
   channel_receiver_.Bind(channel_remote.InitWithNewPipeAndPassReceiver());
 
@@ -94,7 +93,7 @@
       base::Unretained(host_.get()),
       SessionParameters::New(session_type, cast_data.ip_endpoint.address(),
                              cast_data.model_name),
-      std::move(observer_ptr), std::move(channel_remote),
+      std::move(observer_remote), std::move(channel_remote),
       channel_to_service_.BindNewPipeAndPassReceiver());
 }
 
diff --git a/chrome/browser/media/router/providers/cast/mirroring_activity_record.h b/chrome/browser/media/router/providers/cast/mirroring_activity_record.h
index 138f8737..45b3232 100644
--- a/chrome/browser/media/router/providers/cast/mirroring_activity_record.h
+++ b/chrome/browser/media/router/providers/cast/mirroring_activity_record.h
@@ -17,7 +17,6 @@
 #include "components/mirroring/mojom/cast_message_channel.mojom.h"
 #include "components/mirroring/mojom/mirroring_service_host.mojom.h"
 #include "components/mirroring/mojom/session_observer.mojom.h"
-#include "mojo/public/cpp/bindings/binding.h"
 #include "mojo/public/cpp/bindings/receiver.h"
 #include "mojo/public/cpp/bindings/remote.h"
 
@@ -97,7 +96,7 @@
   // Sends Cast messages from the mirroring receiver to the mirroring service.
   mojo::Remote<mirroring::mojom::CastMessageChannel> channel_to_service_;
 
-  mojo::Binding<mirroring::mojom::SessionObserver> observer_binding_{this};
+  mojo::Receiver<mirroring::mojom::SessionObserver> observer_receiver_{this};
 
   // To handle Cast messages from the mirroring service to the mirroring
   // receiver.
diff --git a/chrome/browser/navigation_predictor/navigation_predictor.cc b/chrome/browser/navigation_predictor/navigation_predictor.cc
index 0a76116..d2e3f0a 100644
--- a/chrome/browser/navigation_predictor/navigation_predictor.cc
+++ b/chrome/browser/navigation_predictor/navigation_predictor.cc
@@ -14,7 +14,6 @@
 #include "base/optional.h"
 #include "base/rand_util.h"
 #include "base/system/sys_info.h"
-#include "chrome/browser/engagement/site_engagement_service.h"
 #include "chrome/browser/predictors/loading_predictor.h"
 #include "chrome/browser/predictors/loading_predictor_factory.h"
 #include "chrome/browser/prerender/prerender_handle.h"
@@ -146,14 +145,6 @@
           blink::features::kNavigationPredictor,
           "is_url_incremented_scale",
           100)),
-      source_engagement_score_scale_(base::GetFieldTrialParamByFeatureAsInt(
-          blink::features::kNavigationPredictor,
-          "source_engagement_score_scale",
-          0)),
-      target_engagement_score_scale_(base::GetFieldTrialParamByFeatureAsInt(
-          blink::features::kNavigationPredictor,
-          "target_engagement_score_scale",
-          0)),
       area_rank_scale_(base::GetFieldTrialParamByFeatureAsInt(
           blink::features::kNavigationPredictor,
           "area_rank_scale",
@@ -201,7 +192,6 @@
       sum_link_scales_(
           ratio_area_scale_ + is_in_iframe_scale_ + is_same_host_scale_ +
           contains_image_scale_ + is_url_incremented_scale_ +
-          source_engagement_score_scale_ + target_engagement_score_scale_ +
           area_rank_scale_ + ratio_distance_root_top_scale_),
       sum_page_scales_(link_total_scale_ + iframe_link_total_scale_ +
                        increment_link_total_scale_ +
@@ -536,13 +526,6 @@
   builder.Record(ukm_recorder_);
 }
 
-SiteEngagementService* NavigationPredictor::GetEngagementService() const {
-  Profile* profile = Profile::FromBrowserContext(browser_context_);
-  SiteEngagementService* service = SiteEngagementService::Get(profile);
-  DCHECK(service);
-  return service;
-}
-
 TemplateURLService* NavigationPredictor::GetTemplateURLService() const {
   return TemplateURLServiceFactory::GetForProfile(
       Profile::FromBrowserContext(browser_context_));
@@ -571,27 +554,6 @@
   }
 
   RecordTimingOnClick();
-
-  SiteEngagementService* engagement_service = GetEngagementService();
-
-  UMA_HISTOGRAM_COUNTS_100(
-      "AnchorElementMetrics.Clicked.DocumentEngagementScore",
-      static_cast<int>(engagement_service->GetScore(metrics->source_url)));
-
-  double target_score = engagement_service->GetScore(metrics->target_url);
-  UMA_HISTOGRAM_COUNTS_100("AnchorElementMetrics.Clicked.HrefEngagementScore2",
-                           static_cast<int>(target_score));
-  if (target_score > 0) {
-    UMA_HISTOGRAM_COUNTS_100(
-        "AnchorElementMetrics.Clicked.HrefEngagementScorePositive",
-        static_cast<int>(target_score));
-  }
-  if (!metrics->is_same_host) {
-    UMA_HISTOGRAM_COUNTS_100(
-        "AnchorElementMetrics.Clicked.HrefEngagementScoreExternal",
-        static_cast<int>(target_score));
-  }
-
   clicked_count_++;
 
   RecordActionAccuracyOnClick(metrics->target_url);
@@ -821,17 +783,6 @@
   median_link_location_ = link_locations[link_locations.size() / 2] * 100;
   double page_metrics_score = GetPageMetricsScore();
 
-  // Retrieve site engagement score of the document. |metrics| is guaranteed to
-  // be non-empty. All |metrics| have the same source_url.
-  SiteEngagementService* engagement_service = GetEngagementService();
-  double document_engagement_score =
-      engagement_service->GetScore(metrics[0]->source_url);
-  DCHECK(document_engagement_score >= 0 &&
-         document_engagement_score <= engagement_service->GetMaxPoints());
-  UMA_HISTOGRAM_COUNTS_100(
-      "AnchorElementMetrics.Visible.DocumentEngagementScore",
-      static_cast<int>(document_engagement_score));
-
   // Sort metric by area in descending order to get area rank, which is a
   // derived feature to calculate navigation score.
   std::sort(metrics.begin(), metrics.end(), [](const auto& a, const auto& b) {
@@ -854,28 +805,13 @@
     const auto& metric = metrics[i];
     RecordMetricsOnLoad(*metric);
 
-    const double target_engagement_score =
-        engagement_service->GetScore(metric->target_url);
-    DCHECK(target_engagement_score >= 0 &&
-           target_engagement_score <= engagement_service->GetMaxPoints());
-    UMA_HISTOGRAM_COUNTS_100(
-        "AnchorElementMetrics.Visible.HrefEngagementScore2",
-        static_cast<int>(target_engagement_score));
-    if (!metric->is_same_host) {
-      UMA_HISTOGRAM_COUNTS_100(
-          "AnchorElementMetrics.Visible.HrefEngagementScoreExternal",
-          static_cast<int>(target_engagement_score));
-    }
-
     // Anchor elements with the same area are assigned with the same rank.
     size_t area_rank = i;
     if (i > 0 && metric->ratio_area == metrics[i - 1]->ratio_area)
       area_rank = navigation_scores[navigation_scores.size() - 1]->area_rank;
 
     double score =
-        CalculateAnchorNavigationScore(*metric, document_engagement_score,
-                                       target_engagement_score, area_rank) +
-        page_metrics_score;
+        CalculateAnchorNavigationScore(*metric, area_rank) + page_metrics_score;
     total_score += score;
 
     navigation_scores.push_back(std::make_unique<NavigationScore>(
@@ -918,18 +854,12 @@
 
 double NavigationPredictor::CalculateAnchorNavigationScore(
     const blink::mojom::AnchorElementMetrics& metrics,
-    double document_engagement_score,
-    double target_engagement_score,
     int area_rank) const {
   DCHECK(!browser_context_->IsOffTheRecord());
 
   if (sum_link_scales_ == 0)
     return 0.0;
 
-  double max_engagement_points = GetEngagementService()->GetMaxPoints();
-  document_engagement_score /= max_engagement_points;
-  target_engagement_score /= max_engagement_points;
-
   double area_rank_score =
       (double)((number_of_anchors_ - area_rank)) / number_of_anchors_;
 
@@ -948,12 +878,6 @@
   DCHECK_LE(0, metrics.is_url_incremented_by_one);
   DCHECK_GE(1, metrics.is_url_incremented_by_one);
 
-  DCHECK_LE(0, document_engagement_score);
-  DCHECK_GE(1, document_engagement_score);
-
-  DCHECK_LE(0, target_engagement_score);
-  DCHECK_GE(1, target_engagement_score);
-
   DCHECK_LE(0, area_rank_score);
   DCHECK_GE(1, area_rank_score);
 
@@ -975,8 +899,6 @@
       (metrics.is_in_iframe ? is_in_iframe_scale_ : 0.0) +
       (metrics.contains_image ? contains_image_scale_ : 0.0) + host_score +
       (metrics.is_url_incremented_by_one ? is_url_incremented_scale_ : 0.0) +
-      (source_engagement_score_scale_ * document_engagement_score) +
-      (target_engagement_score_scale_ * target_engagement_score) +
       (area_rank_scale_ * area_rank_score) +
       (ratio_distance_root_top_scale_ *
        GetLinearBucketForLinkLocation(
diff --git a/chrome/browser/navigation_predictor/navigation_predictor.h b/chrome/browser/navigation_predictor/navigation_predictor.h
index 393c0ec..9df45587 100644
--- a/chrome/browser/navigation_predictor/navigation_predictor.h
+++ b/chrome/browser/navigation_predictor/navigation_predictor.h
@@ -33,7 +33,6 @@
 class PrerenderManager;
 }
 
-class SiteEngagementService;
 class TemplateURLService;
 
 // This class gathers metrics of anchor elements from both renderer process
@@ -125,10 +124,6 @@
   bool IsValidMetricFromRenderer(
       const blink::mojom::AnchorElementMetrics& metric) const;
 
-  // Returns site engagement service, which can be used to get site engagement
-  // score. Return value is guaranteed to be non-null.
-  SiteEngagementService* GetEngagementService() const;
-
   // Returns template URL service. Guaranteed to be non-null.
   TemplateURLService* GetTemplateURLService() const;
 
@@ -136,8 +131,8 @@
   void MergeMetricsSameTargetUrl(
       std::vector<blink::mojom::AnchorElementMetricsPtr>* metrics) const;
 
-  // Computes and stores document level metrics, including |number_of_anchors_|,
-  // |document_engagement_score_|, etc.
+  // Computes and stores document level metrics, including |number_of_anchors_|
+  // etc.
   void ComputeDocumentMetricsOnLoad(
       const std::vector<blink::mojom::AnchorElementMetricsPtr>& metrics);
 
@@ -145,8 +140,6 @@
   // returns navigation score. Virtual for testing purposes.
   virtual double CalculateAnchorNavigationScore(
       const blink::mojom::AnchorElementMetrics& metrics,
-      double document_engagement_score,
-      double target_engagement_score,
       int area_rank) const;
 
   // If |sum_page_scales_| is non-zero, return the page-wide score to add to
@@ -244,8 +237,6 @@
   const int is_same_host_scale_;
   const int contains_image_scale_;
   const int is_url_incremented_scale_;
-  const int source_engagement_score_scale_;
-  const int target_engagement_score_scale_;
   const int area_rank_scale_;
   const int ratio_distance_root_top_scale_;
 
diff --git a/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc b/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc
index 6e3e04ac..b17881b 100644
--- a/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc
+++ b/chrome/browser/navigation_predictor/navigation_predictor_browsertest.cc
@@ -258,8 +258,6 @@
   base::RunLoop().RunUntilIdle();
 
   histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
-  histogram_tester.ExpectTotalCount(
       "AnchorElementMetrics.Clicked.DurationLoadToFirstClick", 1);
   histogram_tester.ExpectTotalCount(
       "AnchorElementMetrics.Clicked.NavigationScore", 1);
@@ -295,9 +293,6 @@
       "NavigationPredictor.OnNonDSE.ActionTaken",
       NavigationPredictor::Action::kPrefetch, 1);
 
-  histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
-
   histogram_tester.ExpectUniqueSample(
       "NavigationPredictor.OnNonDSE.AccuracyActionTaken",
       NavigationPredictor::ActionAccuracy::
@@ -341,9 +336,6 @@
       "NavigationPredictor.OnNonDSE.ActionTaken",
       NavigationPredictor::Action::kPrefetch, 1);
 
-  histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
-
   histogram_tester.ExpectUniqueSample(
       "NavigationPredictor.OnNonDSE.AccuracyActionTaken",
       NavigationPredictor::ActionAccuracy::
@@ -641,9 +633,6 @@
       "NavigationPredictor.OnNonDSE.ActionTaken",
       NavigationPredictor::Action::kPrefetch, 1);
 
-  histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
-
   histogram_tester.ExpectUniqueSample(
       "NavigationPredictor.OnNonDSE.AccuracyActionTaken",
       NavigationPredictor::ActionAccuracy::kPrefetchActionClickToSameURL, 1);
@@ -664,10 +653,8 @@
   EXPECT_TRUE(content::ExecuteScript(
       incognito->tab_strip_model()->GetActiveWebContents(),
       "document.getElementById('google').click();"));
-  base::RunLoop().RunUntilIdle();
-
   histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 0);
+      "AnchorElementMetrics.Visible.HighestNavigationScore", 0);
 }
 
 // Simulate click at the anchor element.
diff --git a/chrome/browser/navigation_predictor/navigation_predictor_unittest.cc b/chrome/browser/navigation_predictor/navigation_predictor_unittest.cc
index 4963137..d88460e 100644
--- a/chrome/browser/navigation_predictor/navigation_predictor_unittest.cc
+++ b/chrome/browser/navigation_predictor/navigation_predictor_unittest.cc
@@ -59,8 +59,6 @@
  private:
   double CalculateAnchorNavigationScore(
       const blink::mojom::AnchorElementMetrics& metrics,
-      double document_engagement_score,
-      double target_engagement_score,
       int area_rank) const override {
     area_rank_map_.emplace(std::make_pair(metrics.target_url, area_rank));
     return 100 * metrics.ratio_area;
@@ -97,8 +95,6 @@
   // any weight is the ratio distance to the top of the document.
   double CalculateAnchorNavigationScore(
       const blink::mojom::AnchorElementMetrics& metrics,
-      double document_engagement_score,
-      double target_engagement_score,
       int area_rank) const override {
     return metrics.ratio_distance_root_top;
   }
@@ -199,8 +195,6 @@
   predictor_service()->ReportAnchorElementMetricsOnClick(std::move(metrics));
   base::RunLoop().RunUntilIdle();
 
-  histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
   histogram_tester.ExpectUniqueSample(
       "NavigationPredictor.OnNonDSE.AccuracyActionTaken",
       NavigationPredictor::ActionAccuracy::kNoActionTakenClickHappened, 1);
@@ -234,7 +228,7 @@
   base::RunLoop().RunUntilIdle();
 
   histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 0);
+      "AnchorElementMetrics.Visible.HighestNavigationScore", 0);
 }
 
 // Test that if source/target url is not http or https, no navigation score will
@@ -459,8 +453,6 @@
       std::move(metrics_clicked));
   base::RunLoop().RunUntilIdle();
 
-  histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
   histogram_tester.ExpectUniqueSample(
       "NavigationPredictor.OnNonDSE.AccuracyActionTaken",
       NavigationPredictor::ActionAccuracy::kPrefetchActionClickToSameOrigin, 1);
@@ -864,8 +856,6 @@
       std::move(metrics_clicked));
   base::RunLoop().RunUntilIdle();
 
-  histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
   histogram_tester.ExpectUniqueSample(
       "NavigationPredictor.OnNonDSE.AccuracyActionTaken",
       NavigationPredictor::ActionAccuracy::kPreconnectActionClickToSameOrigin,
@@ -956,8 +946,6 @@
       std::move(metrics_clicked));
   base::RunLoop().RunUntilIdle();
 
-  histogram_tester.ExpectTotalCount(
-      "AnchorElementMetrics.Clicked.HrefEngagementScore2", 1);
   histogram_tester.ExpectUniqueSample(
       "NavigationPredictor.OnNonDSE.AccuracyActionTaken",
       NavigationPredictor::ActionAccuracy::kPreconnectActionClickToSameOrigin,
diff --git a/chrome/browser/net/cookie_policy_browsertest.cc b/chrome/browser/net/cookie_policy_browsertest.cc
index 5d6f5b9..58a92d8 100644
--- a/chrome/browser/net/cookie_policy_browsertest.cc
+++ b/chrome/browser/net/cookie_policy_browsertest.cc
@@ -18,6 +18,7 @@
 #include "components/content_settings/core/browser/cookie_settings.h"
 #include "components/content_settings/core/common/features.h"
 #include "components/content_settings/core/common/pref_names.h"
+#include "components/network_session_configurator/common/network_switches.h"
 #include "components/prefs/pref_service.h"
 #include "content/public/common/content_paths.h"
 #include "content/public/test/browser_test_utils.h"
@@ -29,23 +30,31 @@
 
 namespace {
 
-// "ServiceWorker", "CacheStorage" are not available because the test server
-// runs on http.
+// "ServiceWorker" is not handled correctly by content settings with secondary
+// pattern yet.
 const std::vector<std::string> kStorageTypes{
-    "Cookie",         "LocalStorage", "FileSystem",
-    "SessionStorage", "IndexedDb",    "WebSql",
+    "Cookie",    "LocalStorage", "FileSystem",   "SessionStorage",
+    "IndexedDb", "WebSql",       "CacheStorage",
 };
 
 class CookiePolicyBrowserTest : public InProcessBrowserTest {
  protected:
-  CookiePolicyBrowserTest() {}
+  CookiePolicyBrowserTest()
+      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {}
 
   void SetUpOnMainThread() override {
     host_resolver()->AddRule("*", "127.0.0.1");
     base::FilePath path;
     base::PathService::Get(content::DIR_TEST_DATA, &path);
-    embedded_test_server()->ServeFilesFromDirectory(path);
-    ASSERT_TRUE(embedded_test_server()->Start());
+    https_server_.ServeFilesFromDirectory(path);
+    https_server_.AddDefaultHandlers(GetChromeTestDataDir());
+    ASSERT_TRUE(https_server_.Start());
+  }
+
+  void SetUpCommandLine(base::CommandLine* command_line) override {
+    // HTTPS server only serves a valid cert for localhost, so this is needed
+    // to load pages from other hosts without an error.
+    command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
   }
 
   void SetBlockThirdPartyCookies(bool value) {
@@ -54,12 +63,12 @@
   }
 
   void NavigateToPageWithFrame(const std::string& host) {
-    GURL main_url(embedded_test_server()->GetURL(host, "/iframe.html"));
+    GURL main_url(https_server_.GetURL(host, "/iframe.html"));
     ui_test_utils::NavigateToURL(browser(), main_url);
   }
 
   void NavigateFrameTo(const std::string& host, const std::string& path) {
-    GURL page = embedded_test_server()->GetURL(host, path);
+    GURL page = https_server_.GetURL(host, path);
     content::WebContents* web_contents =
         browser()->tab_strip_model()->GetActiveWebContents();
     EXPECT_TRUE(NavigateIframeToURL(web_contents, "test", page));
@@ -75,7 +84,7 @@
   }
 
   void NavigateNestedFrameTo(const std::string& host, const std::string& path) {
-    GURL url(embedded_test_server()->GetURL(host, path));
+    GURL url(https_server_.GetURL(host, path));
     content::WebContents* web_contents =
         browser()->tab_strip_model()->GetActiveWebContents();
     content::TestNavigationObserver load_observer(web_contents);
@@ -97,9 +106,8 @@
 
   void ExpectCookiesOnHost(const std::string& host,
                            const std::string& expected) {
-    EXPECT_EQ(expected,
-              content::GetCookies(browser()->profile(),
-                                  embedded_test_server()->GetURL(host, "/")));
+    EXPECT_EQ(expected, content::GetCookies(browser()->profile(),
+                                            https_server_.GetURL(host, "/")));
   }
 
   void SetStorageForFrame(content::RenderFrameHost* frame) {
@@ -115,8 +123,7 @@
     for (const auto& data_type : kStorageTypes) {
       bool data;
       EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
-          frame, "try { has" + data_type + "(); } catch(e) { failure_(); }",
-          &data));
+          frame, "has" + data_type + "();", &data));
       EXPECT_EQ(expected, data) << data_type;
     }
   }
@@ -131,6 +138,9 @@
     return ChildFrameAt(GetFrame(), 0);
   }
 
+ protected:
+  net::test_server::EmbeddedTestServer https_server_;
+
  private:
   DISALLOW_COPY_AND_ASSIGN(CookiePolicyBrowserTest);
 };
@@ -153,7 +163,7 @@
 IN_PROC_BROWSER_TEST_F(CookiePolicyBrowserTest, AllowFirstPartyCookies) {
   SetBlockThirdPartyCookies(false);
 
-  GURL url(embedded_test_server()->GetURL("/set-cookie?cookie1"));
+  GURL url(https_server_.GetURL("/set-cookie?cookie1"));
 
   std::string cookie = content::GetCookies(browser()->profile(), url);
   ASSERT_EQ("", cookie);
@@ -170,8 +180,8 @@
                        AllowFirstPartyCookiesRedirect) {
   SetBlockThirdPartyCookies(true);
 
-  GURL url(embedded_test_server()->GetURL("/server-redirect?"));
-  GURL redirected_url(embedded_test_server()->GetURL("/set-cookie?cookie2"));
+  GURL url(https_server_.GetURL("/server-redirect?"));
+  GURL redirected_url(https_server_.GetURL("/set-cookie?cookie2"));
 
   // Change the host name from 127.0.0.1 to www.example.com so it triggers
   // third-party cookie blocking if the first party for cookies URL is not
@@ -252,8 +262,7 @@
   SetBlockThirdPartyCookies(false);
 
   // Set a cookie on `b.com`.
-  content::SetCookie(browser()->profile(),
-                     embedded_test_server()->GetURL("b.com", "/"),
+  content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
                      "thirdparty");
   ExpectCookiesOnHost("b.com", "thirdparty");
 
@@ -284,8 +293,7 @@
   SetBlockThirdPartyCookies(true);
 
   // Set a cookie on `b.com`.
-  content::SetCookie(browser()->profile(),
-                     embedded_test_server()->GetURL("b.com", "/"),
+  content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
                      "thirdparty");
   ExpectCookiesOnHost("b.com", "thirdparty");
 
@@ -316,15 +324,14 @@
   SetBlockThirdPartyCookies(true);
 
   // Set a cookie on `b.com`.
-  content::SetCookie(browser()->profile(),
-                     embedded_test_server()->GetURL("b.com", "/"),
+  content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
                      "thirdparty");
   ExpectCookiesOnHost("b.com", "thirdparty");
 
   // Allow all requests to b.com to have cookies.
   auto cookie_settings =
       CookieSettingsFactory::GetForProfile(browser()->profile());
-  GURL url = embedded_test_server()->GetURL("b.com", "/");
+  GURL url = https_server_.GetURL("b.com", "/");
   cookie_settings->SetCookieSetting(url, ContentSetting::CONTENT_SETTING_ALLOW);
 
   NavigateToPageWithFrame("a.com");
@@ -354,15 +361,14 @@
   SetBlockThirdPartyCookies(true);
 
   // Set a cookie on `b.com`.
-  content::SetCookie(browser()->profile(),
-                     embedded_test_server()->GetURL("b.com", "/"),
+  content::SetCookie(browser()->profile(), https_server_.GetURL("b.com", "/"),
                      "thirdparty");
   ExpectCookiesOnHost("b.com", "thirdparty");
 
   // Allow all requests on the top frame domain a.com to have cookies.
   auto cookie_settings =
       CookieSettingsFactory::GetForProfile(browser()->profile());
-  GURL url = embedded_test_server()->GetURL("a.com", "/");
+  GURL url = https_server_.GetURL("a.com", "/");
   cookie_settings->SetThirdPartyCookieSetting(
       url, ContentSetting::CONTENT_SETTING_ALLOW);
 
@@ -405,8 +411,8 @@
   // Allow all requests to b.com to access storage.
   auto cookie_settings =
       CookieSettingsFactory::GetForProfile(browser()->profile());
-  GURL a_url = embedded_test_server()->GetURL("a.com", "/");
-  GURL b_url = embedded_test_server()->GetURL("b.com", "/");
+  GURL a_url = https_server_.GetURL("a.com", "/");
+  GURL b_url = https_server_.GetURL("b.com", "/");
   cookie_settings->SetCookieSetting(b_url,
                                     ContentSetting::CONTENT_SETTING_ALLOW);
 
@@ -450,8 +456,8 @@
   // Allow all requests to b.com to access storage.
   auto cookie_settings =
       CookieSettingsFactory::GetForProfile(browser()->profile());
-  GURL a_url = embedded_test_server()->GetURL("a.com", "/");
-  GURL c_url = embedded_test_server()->GetURL("c.com", "/");
+  GURL a_url = https_server_.GetURL("a.com", "/");
+  GURL c_url = https_server_.GetURL("c.com", "/");
   cookie_settings->SetCookieSetting(c_url,
                                     ContentSetting::CONTENT_SETTING_ALLOW);
 
@@ -498,7 +504,7 @@
   // Allow all requests to b.com to access storage.
   auto cookie_settings =
       CookieSettingsFactory::GetForProfile(browser()->profile());
-  GURL a_url = embedded_test_server()->GetURL("a.com", "/");
+  GURL a_url = https_server_.GetURL("a.com", "/");
   cookie_settings->SetCookieSetting(a_url,
                                     ContentSetting::CONTENT_SETTING_ALLOW);
 
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
index dc2aad2..61b735c 100644
--- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc
+++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -644,9 +644,15 @@
   { key::kDeviceLoginScreenDefaultSpokenFeedbackEnabled,
     nullptr,
     base::Value::Type::BOOLEAN },
+  { key::kDeviceLoginScreenSpokenFeedbackEnabled,
+    nullptr,
+    base::Value::Type::BOOLEAN },
   { key::kDeviceLoginScreenDefaultHighContrastEnabled,
     nullptr,
     base::Value::Type::BOOLEAN },
+  { key::kDeviceLoginScreenHighContrastEnabled,
+    nullptr,
+    base::Value::Type::BOOLEAN },
   { key::kDeviceLoginScreenDefaultVirtualKeyboardEnabled,
     nullptr,
     base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/policy/policy_browsertest.cc b/chrome/browser/policy/policy_browsertest.cc
index d45a3a3..595c53d 100644
--- a/chrome/browser/policy/policy_browsertest.cc
+++ b/chrome/browser/policy/policy_browsertest.cc
@@ -200,18 +200,9 @@
 #include "net/base/url_util.h"
 #include "net/cert/x509_util.h"
 #include "net/dns/mock_host_resolver.h"
-#include "net/http/http_stream_factory.h"
-#include "net/http/transport_security_state.h"
-#include "net/http/transport_security_state_test_util.h"
 #include "net/test/embedded_test_server/embedded_test_server.h"
 #include "net/test/embedded_test_server/http_request.h"
 #include "net/test/embedded_test_server/http_response.h"
-#include "net/test/url_request/url_request_failed_job.h"
-#include "net/test/url_request/url_request_mock_http_job.h"
-#include "net/url_request/test_url_request_interceptor.h"
-#include "net/url_request/url_request.h"
-#include "net/url_request/url_request_filter.h"
-#include "net/url_request/url_request_interceptor.h"
 #include "services/device/public/cpp/test/fake_usb_device_info.h"
 #include "services/network/public/cpp/features.h"
 #include "services/network/public/cpp/network_switches.h"
@@ -279,7 +270,6 @@
 #endif
 
 using content::BrowserThread;
-using net::URLRequestMockHTTPJob;
 using safe_browsing::ReusedPasswordAccountType;
 using testing::_;
 using testing::AtLeast;
@@ -323,80 +313,6 @@
   return nullptr;
 }
 
-// Filters requests to the hosts in |urls| and redirects them to the test data
-// dir through URLRequestMockHTTPJobs.
-void RedirectHostsToTestData(const char* const urls[], size_t size) {
-  // Map the given hosts to the test data dir.
-  net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
-  base::FilePath base_path;
-  GetTestDataDirectory(&base_path);
-  for (size_t i = 0; i < size; ++i) {
-    const GURL url(urls[i]);
-    EXPECT_TRUE(url.is_valid());
-    filter->AddUrlInterceptor(
-        url, URLRequestMockHTTPJob::CreateInterceptor(base_path));
-  }
-}
-
-// Fails requests using ERR_CONNECTION_RESET.
-class FailedJobInterceptor : public net::URLRequestInterceptor {
- public:
-  FailedJobInterceptor() {}
-  ~FailedJobInterceptor() override {}
-
-  // URLRequestInterceptor implementation:
-  net::URLRequestJob* MaybeInterceptRequest(
-      net::URLRequest* request,
-      net::NetworkDelegate* network_delegate) const override {
-    return new net::URLRequestFailedJob(request, network_delegate,
-                                        net::ERR_CONNECTION_RESET);
-  }
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(FailedJobInterceptor);
-};
-
-// While |MakeRequestFail| is in scope URLRequests to |host| will fail.
-class MakeRequestFail {
- public:
-  // Sets up the filter on IO thread such that requests to |host| fail.
-  explicit MakeRequestFail(const std::string& host) : host_(host) {
-    base::RunLoop run_loop;
-    base::PostTaskAndReply(FROM_HERE, {BrowserThread::IO},
-                           base::BindOnce(MakeRequestFailOnIO, host_),
-                           run_loop.QuitClosure());
-    run_loop.Run();
-  }
-  ~MakeRequestFail() {
-    base::RunLoop run_loop;
-    base::PostTaskAndReply(FROM_HERE, {BrowserThread::IO},
-                           base::BindOnce(UndoMakeRequestFailOnIO, host_),
-                           run_loop.QuitClosure());
-    run_loop.Run();
-  }
-
- private:
-  // Filters requests to the |host| such that they fail. Run on IO thread.
-  static void MakeRequestFailOnIO(const std::string& host) {
-    net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
-    filter->AddHostnameInterceptor("http", host,
-                                   std::unique_ptr<net::URLRequestInterceptor>(
-                                       new FailedJobInterceptor()));
-    filter->AddHostnameInterceptor("https", host,
-                                   std::unique_ptr<net::URLRequestInterceptor>(
-                                       new FailedJobInterceptor()));
-  }
-
-  // Remove filters for requests to the |host|. Run on IO thread.
-  static void UndoMakeRequestFailOnIO(const std::string& host) {
-    net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
-    filter->RemoveHostnameHandler("http", host);
-    filter->RemoveHostnameHandler("https", host);
-  }
-
-  const std::string host_;
-};
-
 // Verifies that the given url |spec| can be opened. This assumes that |spec|
 // points at empty.html in the test data dir.
 void CheckCanOpenURL(Browser* browser, const std::string& spec) {
@@ -993,8 +909,6 @@
 }
 
 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
-  MakeRequestFail make_request_fail("search.example");
-
   // Verifies that a default search is made using the provider configured via
   // policy. Also checks that default search can be completely disabled.
   const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
@@ -2976,12 +2890,6 @@
                            command_line->argv().begin()));
   }
 
-  void SetUpOnMainThread() override {
-    base::PostTask(FROM_HERE, {BrowserThread::IO},
-                   base::BindOnce(RedirectHostsToTestData, kRestoredURLs,
-                                  base::size(kRestoredURLs)));
-  }
-
   void ListOfURLs() {
     // Verifies that policy can set the startup pages to a list of URLs.
     base::ListValue urls;
@@ -5831,21 +5739,16 @@
               std::make_unique<base::ListValue>(bypass_list));
     provider_.UpdateChromePolicy(policies);
   }
-
- private:
-  net::ScopedTransportSecurityStateSource hsts_source_;
 };
 
 IN_PROC_BROWSER_TEST_F(HSTSPolicyTest, HSTSPolicyBypassList) {
-  if (content::IsOutOfProcessNetworkService()) {
-    network::mojom::NetworkServiceTestPtr network_service_test;
-    content::GetSystemConnector()->BindInterface(
-        content::mojom::kNetworkServiceName, &network_service_test);
-    mojo::ScopedAllowSyncCallForTesting allow_sync_call;
-    // The port number 1234 here doesn't matter - it just needs to be a non-zero
-    // value so that we use the unittest_default preload list.
-    network_service_test->SetTransportSecurityStateSource(1234);
-  }
+  network::mojom::NetworkServiceTestPtr network_service_test;
+  content::GetSystemConnector()->BindInterface(
+      content::mojom::kNetworkServiceName, &network_service_test);
+  mojo::ScopedAllowSyncCallForTesting allow_sync_call;
+  // The port number 1234 here doesn't matter - it just needs to be a non-zero
+  // value so that we use the unittest_default preload list.
+  network_service_test->SetTransportSecurityStateSource(1234);
 
   ASSERT_TRUE(embedded_test_server()->Start());
   GURL url("http://example/");
diff --git a/chrome/browser/resources/chromeos/login/demo_setup.css b/chrome/browser/resources/chromeos/login/demo_setup.css
index 9e424ef..709f672 100644
--- a/chrome/browser/resources/chromeos/login/demo_setup.css
+++ b/chrome/browser/resources/chromeos/login/demo_setup.css
@@ -2,10 +2,6 @@
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file. */
 
-[slot='bottom-buttons'] {
-  padding: 0 6px;
-}
-
 /* Spinner shown on progress dialog. */
 paper-spinner-lite {
   height: 164px;
diff --git a/chrome/browser/resources/chromeos/login/encryption_migration.css b/chrome/browser/resources/chromeos/login/encryption_migration.css
index 27cea4c..a98fd65 100644
--- a/chrome/browser/resources/chromeos/login/encryption_migration.css
+++ b/chrome/browser/resources/chromeos/login/encryption_migration.css
@@ -23,10 +23,6 @@
   width: 100%;
 }
 
-[slot='bottom-buttons'] {
-  padding-inline-end: 16px;
-}
-
 oobe-text-button {
   color: rgb(90, 90, 90);
 }
diff --git a/chrome/browser/resources/chromeos/login/enterprise_enrollment.html b/chrome/browser/resources/chromeos/login/enterprise_enrollment.html
index e36297e0..7fed93e5 100644
--- a/chrome/browser/resources/chromeos/login/enterprise_enrollment.html
+++ b/chrome/browser/resources/chromeos/login/enterprise_enrollment.html
@@ -50,8 +50,7 @@
                      name="oauth-enroll-auth-view">
             </webview>
           </div>
-          <div slot="bottom-buttons"
-               class="flex layout horizontal center self-start">
+          <div slot="bottom-buttons" class="layout horizontal start-justified">
             <oobe-back-button id="oobe-signin-back-button"
                 disabled="[[authenticatorDialogDisplayed_]]"
                 on-click="onBackButtonClicked_"></oobe-back-button>
diff --git a/chrome/browser/resources/chromeos/login/fingerprint_setup.css b/chrome/browser/resources/chromeos/login/fingerprint_setup.css
index 40e1aa17..1b60afa 100644
--- a/chrome/browser/resources/chromeos/login/fingerprint_setup.css
+++ b/chrome/browser/resources/chromeos/login/fingerprint_setup.css
@@ -7,10 +7,6 @@
   font-weight: 400; /* roboto-regular */
 }
 
-[slot='bottom-buttons'] {
-  padding: 0 34px;
-}
-
 [slot='footer'] {
   padding: 50px 0 0;
 }
diff --git a/chrome/browser/resources/chromeos/login/marketing_opt_in.css b/chrome/browser/resources/chromeos/login/marketing_opt_in.css
index 671912d3..35a03312 100644
--- a/chrome/browser/resources/chromeos/login/marketing_opt_in.css
+++ b/chrome/browser/resources/chromeos/login/marketing_opt_in.css
@@ -24,8 +24,3 @@
   --iron-icon-fill-color: var(--google-blue-600);
   padding-inline-end: 16px;
 }
-
-.bottom-buttons {
-  padding: 0 24px;
-}
-
diff --git a/chrome/browser/resources/chromeos/login/oobe_dialog.css b/chrome/browser/resources/chromeos/login/oobe_dialog.css
index 11ce8fed..8722be4 100644
--- a/chrome/browser/resources/chromeos/login/oobe_dialog.css
+++ b/chrome/browser/resources/chromeos/login/oobe_dialog.css
@@ -56,6 +56,7 @@
 }
 
 #footer-container {
+  overflow-y: auto;
   padding: 0 64px;
 }
 
@@ -64,15 +65,11 @@
 }
 
 #oobe-bottom {
-  height: 80px;
-  padding: 0 calc(64px - 4px); /* real width - button margin */
+  height: 32px;
+  padding: 24px calc(24px - 4px); /* real padding - button margin */
   z-index: 1;
 }
 
-:host(:not([full-screen-dialog])) #oobe-bottom {
-  padding: 0 calc(32px - 4px); /* real width - button margin */
-}
-
 :host #oobe-bottom[no-buttons-padding] {
   padding: unset;
 }
diff --git a/chrome/browser/resources/chromeos/login/oobe_dialog.html b/chrome/browser/resources/chromeos/login/oobe_dialog.html
index c7cdfbf..03868ceb 100644
--- a/chrome/browser/resources/chromeos/login/oobe_dialog.html
+++ b/chrome/browser/resources/chromeos/login/oobe_dialog.html
@@ -41,11 +41,12 @@
       <iron-icon icon-"icon2" ... slot="oobe-icon" class="oobe-icon-2x">
 
   |bottom-buttons| block is shown only if |has-buttons| attribute is set.
+  Please keep |bottom-buttons| block as simple as possible. Ideally just a div
+  with oobe buttons. No custom styles, etc.
 
   Attributes:
     no-header - hides header
     no-footer-padding - disables footer padding.
-    no-buttons-padding - disables buttons padding.
     has-buttons - shows bottom buttons menu
 
   I.e. [no-header no-footer-padding] will make the footer occupy all the dialog
@@ -78,7 +79,6 @@
     </div>
     <template is="dom-if" if="[[hasButtons]]">
       <div id="oobe-bottom" hideShadow$="[[hideShadow]]"
-        no-buttons-padding$="[[noButtonsPadding]]"
           class="layout horizontal center">
         <slot name="bottom-buttons"></slot>
       </div>
diff --git a/chrome/browser/resources/chromeos/login/oobe_reset_confirmation_overlay.css b/chrome/browser/resources/chromeos/login/oobe_reset_confirmation_overlay.css
index 0534b7a..dae595e 100644
--- a/chrome/browser/resources/chromeos/login/oobe_reset_confirmation_overlay.css
+++ b/chrome/browser/resources/chromeos/login/oobe_reset_confirmation_overlay.css
@@ -2,10 +2,6 @@
  * Use of this source code is governed by a BSD-style license that can be
  * found in the LICENSE file. */
 
-[slot='bottom-buttons'] {
-  width: 100%;
-}
-
 .reset-popup {
   background: white;
   border-radius: 2px;
diff --git a/chrome/browser/resources/chromeos/login/screen_error_message.css b/chrome/browser/resources/chromeos/login/screen_error_message.css
index d4615c1..1e1b4f2 100644
--- a/chrome/browser/resources/chromeos/login/screen_error_message.css
+++ b/chrome/browser/resources/chromeos/login/screen_error_message.css
@@ -62,8 +62,8 @@
   text-decoration: none;
 }
 
-#error-message-md-footer {
-  overflow: scroll;
+.scrollable {
+  overflow: auto;
 }
 
 #offline-network-control {
diff --git a/chrome/browser/resources/chromeos/login/screen_error_message.html b/chrome/browser/resources/chromeos/login/screen_error_message.html
index bcac232..5405142 100644
--- a/chrome/browser/resources/chromeos/login/screen_error_message.html
+++ b/chrome/browser/resources/chromeos/login/screen_error_message.html
@@ -39,7 +39,7 @@
       </div>
     </h1>
     <div id="error-message-md-footer" slot="footer"
-        class="flex layout vertical">
+        class="flex layout vertical scrollable">
       <div id="error-body-id" class="error-body" aria-live="assertive">
         <div id="kiosk-online-message-body"
             class="error-message-paragraph
@@ -132,7 +132,8 @@
                    show-with-ui-state-signin
                    show-with-ui-state-supervised
                    show-with-ui-state-kiosk-mode
-                   show-with-ui-state-auto-enrollment-error">
+                   show-with-ui-state-auto-enrollment-error
+                   scrollable">
           <network-select-login id="offline-network-control"
               class="layout vertical flex" configure-connected>
           </network-select-login>
diff --git a/chrome/browser/resources/chromeos/login/screen_gaia_signin.css b/chrome/browser/resources/chromeos/login/screen_gaia_signin.css
index 1838d5d..47d8c1c 100644
--- a/chrome/browser/resources/chromeos/login/screen_gaia_signin.css
+++ b/chrome/browser/resources/chromeos/login/screen_gaia_signin.css
@@ -122,18 +122,6 @@
   padding-top: 44px;
 }
 
-#signin-frame-dialog #buttons-container {
-  padding: 0 calc(32px - 4px); /* real width - button margin */
-}
-
-#signin-frame-dialog[full-screen-dialog] #buttons-container {
-  padding: 0 calc(64px - 4px); /* real width - button margin */
-}
-
-#gaia-screen-navigation-buttons {
-  height: 100%;
-}
-
 #gaia-screen-buttons-overlay {
   background: rgba(0, 0, 0, 0.6);
 }
diff --git a/chrome/browser/resources/chromeos/login/screen_gaia_signin.html b/chrome/browser/resources/chromeos/login/screen_gaia_signin.html
index 4c31867..bd43c0bc 100644
--- a/chrome/browser/resources/chromeos/login/screen_gaia_signin.html
+++ b/chrome/browser/resources/chromeos/login/screen_gaia_signin.html
@@ -9,7 +9,7 @@
 
   <template>
     <oobe-dialog id="signin-frame-dialog" class="gaia-dialog" role="dialog"
-        has-buttons no-header no-footer-padding no-buttons-padding
+        has-buttons no-header no-footer-padding
         hidden="[[!isSigninFrameDialogVisible_(screenMode_,
                                                pinDialogParameters_)]]">
       <div slot="footer" class="flex layout vertical">
@@ -19,7 +19,7 @@
         </div>
       </div>
       <div id="gaia-screen-navigation-buttons"
-          slot="bottom-buttons" class="relative flex layout horizontal center">
+          slot="bottom-buttons" class="relative flex layout horizontal">
         <div id="buttons-container" class="flex layout horizontal center">
           <oobe-back-button id="signin-back-button"
               disabled="[[!navigationEnabled_]]"></oobe-back-button>
diff --git a/chrome/browser/resources/chromeos/login/sync_consent.css b/chrome/browser/resources/chromeos/login/sync_consent.css
index 83898a7..67eb09cd 100644
--- a/chrome/browser/resources/chromeos/login/sync_consent.css
+++ b/chrome/browser/resources/chromeos/login/sync_consent.css
@@ -38,10 +38,6 @@
   --cr-checkbox-label-padding-start: 12px;
 }
 
-#syncConsentOverviewDialog [slot='bottom-buttons'] {
-  padding: 0 6px; /* = 8px - 2px button border */
-}
-
 /* --------------- Sync Make Chrome ... --------------- */
 
 #syncConsentNewDialog [slot='oobe-icon'] {
@@ -61,10 +57,6 @@
   padding-inline-end: 16px;
 }
 
-#syncConsentNewDialog [slot='bottom-buttons'] {
-  padding: 0 24px;
-}
-
 /* ------------------ Sync options ------------- */
 
 #syncConsentMakeChromeSyncOptionsDialog [slot='oobe-icon'] {
diff --git a/chrome/browser/resources/local_ntp/local_ntp.css b/chrome/browser/resources/local_ntp/local_ntp.css
index 7035dd50..acb7d41 100644
--- a/chrome/browser/resources/local_ntp/local_ntp.css
+++ b/chrome/browser/resources/local_ntp/local_ntp.css
@@ -731,13 +731,13 @@
 
 #promo {
   bottom: 16px;
-  display: none;
   left: 0;
   pointer-events: none;
   position: fixed;
   right: 0;
   text-align: center;
   transition: bottom 400ms;
+  visibility: hidden;
 }
 
 #promo.float-down {
@@ -776,18 +776,6 @@
   }
 }
 
-/**
- * Hide the promo if the window is too small:
- * max-width = promo.max-width (505px) + 2 * edit gear icon (16px + 28px + 8px)
- * max-height = ntp-contents.max-height (628px) + promo div height (16px + 22px)
- */
-@media only screen and (max-width: 609px),
-            screen and (max-height: 666px)  {
-  #promo > div {
-    display: none;
-  }
-}
-
 #promo > div > a {
   color: rgb(51, 103, 214) !important;
   text-decoration: none;
@@ -818,8 +806,7 @@
   }
 }
 
-#one-google.show-element,
-#promo.show-element {
+#one-google.show-element {
   display: block;
 }
 
diff --git a/chrome/browser/resources/local_ntp/local_ntp.html b/chrome/browser/resources/local_ntp/local_ntp.html
index b968eca..ac5bac8b 100644
--- a/chrome/browser/resources/local_ntp/local_ntp.html
+++ b/chrome/browser/resources/local_ntp/local_ntp.html
@@ -1,5 +1,5 @@
 <!doctype html>
-<html lang="$i18n{language}"><!-- TODO(dbeam): dir="$i18n{textdirection}"? -->
+<html lang="$i18n{language}" dir="$i18n{textdirection}">
 <!-- Copyright 2015 The Chromium Authors. All rights reserved.
      Use of this source code is governed by a BSD-style license that can be
      found in the LICENSE file. -->
diff --git a/chrome/browser/resources/local_ntp/local_ntp.js b/chrome/browser/resources/local_ntp/local_ntp.js
index c15db99..e9ffd1f7 100644
--- a/chrome/browser/resources/local_ntp/local_ntp.js
+++ b/chrome/browser/resources/local_ntp/local_ntp.js
@@ -90,7 +90,6 @@
   // Vertically centers the most visited section for a non-Google provided page.
   NON_GOOGLE_PAGE: 'non-google-page',
   NON_WHITE_BG: 'non-white-bg',
-  RTL: 'rtl',                  // Right-to-left language text.
   SEARCH_ICON: 'search-icon',  // Magnifying glass/search icon.
   SELECTED: 'selected',  // A selected (via up/down arrow key) realbox match.
   SHOW_ELEMENT: 'show-element',
@@ -112,7 +111,7 @@
  * @type {string}
  * @const
  */
-const DARK_MODE_BACKGROUND_COLOR = 'rgba(50,54,57,1)';
+const DARK_MODE_BACKGROUND_COLOR = 'rgba(53,54,58,1)';
 
 /**
  * The period of time (ms) before transitions can be applied to a toast
@@ -227,7 +226,7 @@
  */
 const NTP_DESIGN = {
   backgroundColor: [255, 255, 255, 255],
-  darkBackgroundColor: [50, 54, 57, 255],
+  darkBackgroundColor: [53, 54, 58, 255],
   iconBackgroundColor: [241, 243, 244, 255],  /** GG100 */
   iconDarkBackgroundColor: [32, 33, 36, 255], /** GG900 */
   numTitleLines: 1,
@@ -303,6 +302,24 @@
 // Helper methods.
 
 /**
+ * @param {number} style
+ * @return {!Array<string>}
+ */
+function classificationStyleToClasses(style) {
+  const classes = [];
+  if (style & ACMatchClassificationStyle.DIM) {
+    classes.push('dim');
+  }
+  if (style & ACMatchClassificationStyle.MATCH) {
+    classes.push('match');
+  }
+  if (style & ACMatchClassificationStyle.URL) {
+    classes.push('url');
+  }
+  return classes;
+}
+
+/**
  * Converts an Array of color components into RGBA format "rgba(R,G,B,A)".
  * @param {Array<number>} color Array of rgba color components.
  * @return {string} CSS color in RGBA format.
@@ -630,7 +647,7 @@
         $(IDS.SUGGESTIONS).style.visibility = 'visible';
       }
       if ($(IDS.PROMO)) {
-        $(IDS.PROMO).classList.add(CLASSES.SHOW_ELEMENT);
+        showPromoIfNotOverlappingAndTrackResizes();
       }
       if (customLinksEnabled()) {
         $(customize.IDS.CUSTOM_LINKS_RESTORE_DEFAULT)
@@ -831,13 +848,6 @@
 
   if (searchboxApiHandle.rtl) {
     $(IDS.NOTIFICATION).dir = 'rtl';
-    // Grabbing the root HTML element. TODO(dbeam): could this just be <html ...
-    // dir="$i18n{textdirection}"> in the .html file instead? It could result in
-    // less flicker for RTL users (as HTML/CSS can render before JavaScript has
-    // the chance to run).
-    document.documentElement.setAttribute('dir', 'rtl');
-    // Add class for setting alignments based on language directionality.
-    document.documentElement.classList.add(CLASSES.RTL);
   }
 
   if (!iframesAndVoiceSearchDisabledForTesting) {
@@ -917,7 +927,7 @@
 
   // The the MV tiles are already loaded show the promo immediately.
   if (tilesAreLoaded) {
-    promoContainer.classList.add(CLASSES.SHOW_ELEMENT);
+    showPromoIfNotOverlappingAndTrackResizes();
   }
 }
 
@@ -959,6 +969,71 @@
       document.body.classList.contains(CLASSES.FAKEBOX_DRAG_FOCUS);
 }
 
+/** @return {boolean} */
+function isPromoOverlapping() {
+  const MARGIN = 10;
+
+  /**
+   * @param {string} id
+   * @return {DOMRect}
+   */
+  const rect = id => $(id).getBoundingClientRect();
+
+  const promoRect = $(IDS.PROMO).querySelector('div').getBoundingClientRect();
+
+  if (promoRect.top - MARGIN <= rect(IDS.USER_CONTENT).bottom) {
+    return true;
+  }
+
+  if (window.chrome.embeddedSearch.searchBox.rtl) {
+    const attributionRect = rect(IDS.ATTRIBUTION);
+    if (attributionRect.width > 0 &&
+        promoRect.left - MARGIN <= attributionRect.right) {
+      return true;
+    }
+
+    const editBgRect = rect(customize.IDS.EDIT_BG);
+    assert(editBgRect.width > 0);
+    if (promoRect.left - 2 * MARGIN <= editBgRect.right) {
+      return true;
+    }
+
+    const customAttributionsRect = rect(customize.IDS.ATTRIBUTIONS);
+    if (customAttributionsRect.width > 0 &&
+        promoRect.right + MARGIN >= customAttributionsRect.left) {
+      return true;
+    }
+  } else {
+    const customAttributionsRect = rect(customize.IDS.ATTRIBUTIONS);
+    if (customAttributionsRect.width > 0 &&
+        promoRect.left - MARGIN <= customAttributionsRect.right) {
+      return true;
+    }
+
+    const editBgRect = rect(customize.IDS.EDIT_BG);
+    assert(editBgRect.width > 0);
+    if (promoRect.right + 2 * MARGIN >= editBgRect.left) {
+      return true;
+    }
+
+    const attributionEl = $(IDS.ATTRIBUTION);
+    const attributionRect = attributionEl.getBoundingClientRect();
+    if (attributionRect.width > 0) {
+      const attributionOnLeft =
+          attributionEl.classList.contains(CLASSES.LEFT_ALIGN_ATTRIBUTION);
+      if (attributionOnLeft) {
+        if (promoRect.left - MARGIN <= attributionRect.right) {
+          return true;
+        }
+      } else if (promoRect.right + MARGIN >= attributionRect.left) {
+        return true;
+      }
+    }
+  }
+
+  return false;
+}
+
 /** Binds event listeners. */
 function listen() {
   document.addEventListener('DOMContentLoaded', init);
@@ -1260,6 +1335,9 @@
   renderTheme();
   renderOneGoogleBarTheme();
   sendThemeInfoToMostVisitedIframe();
+  if ($(IDS.PROMO)) {
+    showPromoIfNotOverlapping();
+  }
 }
 
 /**
@@ -1643,6 +1721,18 @@
   $(IDS.UNDO_LINK).focus();
 }
 
+function showPromoIfNotOverlapping() {
+  $(IDS.PROMO).style.visibility = isPromoOverlapping() ? 'hidden' : 'visible';
+}
+
+function showPromoIfNotOverlappingAndTrackResizes() {
+  showPromoIfNotOverlapping();
+  // The removal before addition is to ensure only 1 event listener is ever
+  // active at the same time.
+  window.removeEventListener('resize', showPromoIfNotOverlapping);
+  window.addEventListener('resize', showPromoIfNotOverlapping);
+}
+
 /**
  * @param {string} text
  * @param {!Array<string>} classes
@@ -1655,24 +1745,6 @@
   return span;
 }
 
-/**
- * @param {number} style
- * @return {!Array<string>}
- */
-function classificationStyleToClasses(style) {
-  const classes = [];
-  if (style & ACMatchClassificationStyle.DIM) {
-    classes.push('dim');
-  }
-  if (style & ACMatchClassificationStyle.MATCH) {
-    classes.push('match');
-  }
-  if (style & ACMatchClassificationStyle.URL) {
-    classes.push('url');
-  }
-  return classes;
-}
-
 /** @param {!RealboxOutputUpdate} update */
 function updateRealboxOutput(update) {
   assert(Object.keys(update).length > 0);
diff --git a/chrome/browser/resources/local_ntp/local_ntp_common.css b/chrome/browser/resources/local_ntp/local_ntp_common.css
index 102d85b..0f89aa12 100644
--- a/chrome/browser/resources/local_ntp/local_ntp_common.css
+++ b/chrome/browser/resources/local_ntp/local_ntp_common.css
@@ -5,7 +5,7 @@
 html {
   /* Material Design colors. Keep in sync with ui/gfx/color_palette.h. */
 
-  --dark-mode-bg-rgb: 50, 54, 57;
+  --dark-mode-bg-rgb: 53, 54, 58;
   --dark-mode-dialog-rgb: 41, 42, 45;
 
   /* Google Grey */
diff --git a/chrome/browser/resources/ntp4/incognito_and_guest_tab.css b/chrome/browser/resources/ntp4/incognito_and_guest_tab.css
index 1e2b3cc2..95c0609 100644
--- a/chrome/browser/resources/ntp4/incognito_and_guest_tab.css
+++ b/chrome/browser/resources/ntp4/incognito_and_guest_tab.css
@@ -11,7 +11,7 @@
 
 @media (prefers-color-scheme: dark) {
   html {
-    background: rgb(50, 54, 57);
+    background: rgb(53, 54, 58);
     color: rgb(232, 234, 237);  /* --google-grey-200 */
   }
 }
diff --git a/chrome/browser/resources/ntp4/incognito_tab.css b/chrome/browser/resources/ntp4/incognito_tab.css
index c2beff1..65d53a4 100644
--- a/chrome/browser/resources/ntp4/incognito_tab.css
+++ b/chrome/browser/resources/ntp4/incognito_tab.css
@@ -13,7 +13,7 @@
 .content {
   /* This is identical to the default background color. It's necessary to set it
      for the case when a theme with a background image is installed. */
-  background-color: rgb(50, 54, 57);
+  background-color: rgb(53, 54, 58);
   color: rgb(232, 234, 237);  /* --google-grey-200 */
   font-size: calc(100% - 2px);
   line-height: calc(100% + 6px);
diff --git a/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html b/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html
index 22f80da..284c9d57 100644
--- a/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html
+++ b/chrome/browser/resources/settings/chromeos/os_people_page/os_people_page.html
@@ -250,7 +250,8 @@
         <settings-subpage
             associated-control="[[$$('#account-manager-subpage-trigger')]]"
             page-title="$i18n{accountManagerPageTitle}">
-          <settings-account-manager></settings-account-manager>
+          <settings-account-manager prefs="[[prefs]]">
+          </settings-account-manager>
         </settings-subpage>
       </template>
       <template is="dom-if" if="[[pageVisibility.people.kerberosAccounts]]">
diff --git a/chrome/browser/resources/settings/people_page/account_manager.html b/chrome/browser/resources/settings/people_page/account_manager.html
index e9fdb9c..f5d9d8b 100644
--- a/chrome/browser/resources/settings/people_page/account_manager.html
+++ b/chrome/browser/resources/settings/people_page/account_manager.html
@@ -45,8 +45,17 @@
         margin-inline-start: 60px;
       }
 
-      #account-list-header {
-        padding-bottom: 8px;
+      .secondary-accounts-policy-indicator {
+        margin-inline-end: 12px;
+      }
+
+      .settings-box.user-message {
+        align-items: flex-end;
+      }
+
+      #account-list-header > h2 {
+        padding-bottom: 12px;
+        padding-top: 12px;
       }
 
       cr-policy-indicator {
@@ -55,7 +64,8 @@
       }
 
       #add-account-button {
-        margin-top: var(--add-account-margin-top);
+        margin-bottom: 12px;
+        margin-top: 12px;
       }
 
       #add-account-icon {
@@ -105,14 +115,21 @@
       </span>
     </div>
 
+    <div id="settings-box-user-message" class="settings-box first user-message"
+        hidden="[[isSecondaryGoogleAccountSigninAllowed_()]]">
+      <cr-policy-pref-indicator class="secondary-accounts-policy-indicator"
+          pref=
+          "[[prefs.account_manager.secondary_google_account_signin_allowed]]">
+      </cr-policy-pref-indicator>
+      <div id="user-message-text" class="secondary">
+        [[getSecondaryAccountsDisabledUserMessage_()]]
+      </div>
+    </div>
+
     <div class="settings-box first">
       <div id="account-list-header" class="flex">
         <h2>$i18n{accountListHeader}</h2>
       </div>
-      <cr-policy-indicator
-          hidden="[[isSecondaryGoogleAccountSigninAllowed_()]]"
-          indicator-type="userPolicy">
-      </cr-policy-indicator>
       <cr-button disabled="[[!isSecondaryGoogleAccountSigninAllowed_()]]"
           id="add-account-button" on-tap="addAccount_">
         <div id="add-account-icon"></div>
diff --git a/chrome/browser/resources/settings/people_page/account_manager.js b/chrome/browser/resources/settings/people_page/account_manager.js
index 8613c12..e5cecdc 100644
--- a/chrome/browser/resources/settings/people_page/account_manager.js
+++ b/chrome/browser/resources/settings/people_page/account_manager.js
@@ -70,6 +70,17 @@
   },
 
   /**
+   * @return {string} 'Secondary Accounts disabled' message depending on
+   *    account type
+   * @private
+   */
+  getSecondaryAccountsDisabledUserMessage_: function() {
+    return loadTimeData.getBoolean('isChild')
+      ? this.i18n('accountManagerSecondaryAccountsDisabledChildText')
+      : this.i18n('accountManagerSecondaryAccountsDisabledText');
+  },
+
+  /**
    * @param {string} iconUrl
    * @return {string} A CSS image-set for multiple scale factors.
    * @private
diff --git a/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.cc b/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.cc
index 73c59f55..4ae8e5177 100644
--- a/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.cc
+++ b/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.cc
@@ -302,8 +302,16 @@
     return;
   }
 
-  delegate->FillAllResultsWith(true);
-  delegate->RunCallback();
+  if (!wait_for_verdict || !work_being_done) {
+    // The UI will not be shown but the policy is set to not wait for the
+    // verdict, or no scans need to be performed.  Inform the caller that they
+    // may proceed.
+    //
+    // Supporting "wait for verdict" while not showing a UI makes writing tests
+    // for callers of this code easier.
+    delegate->FillAllResultsWith(true);
+    delegate->RunCallback();
+  }
 
   // Upload service callback will delete the delegate.
   if (work_being_done)
@@ -345,7 +353,8 @@
   text_request_complete_ = true;
   bool text_complies = (result == BinaryUploadService::Result::SUCCESS &&
                         response.dlp_scan_verdict().triggered_rules().empty());
-  result_.text_results.resize(data_.text.size(), text_complies);
+  std::fill(result_.text_results.begin(), result_.text_results.end(),
+            text_complies);
   MaybeCompleteScanRequest();
 }
 
@@ -479,7 +488,6 @@
   if (!dialog_)
     return false;
 
-  RunCallback();
   dialog_->CancelTabModalDialog();
   return true;
 }
@@ -488,6 +496,8 @@
   if (!text_request_complete_ || file_result_count_ < data_.paths.size())
     return;
 
+  RunCallback();
+
   if (!CloseTabModalDialog()) {
     // No UI was shown.  Delete |this| to cleanup.
     delete this;
diff --git a/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate_unittest.cc b/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate_unittest.cc
index 29046a5..9b6982f1 100644
--- a/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate_unittest.cc
+++ b/chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate_unittest.cc
@@ -4,12 +4,15 @@
 
 #include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.h"
 
+#include <set>
 #include <vector>
 
+#include "base/bind.h"
 #include "base/memory/scoped_refptr.h"
 #include "base/run_loop.h"
 #include "base/strings/utf_string_conversions.h"
 #include "base/test/scoped_feature_list.h"
+#include "chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.h"
 #include "chrome/test/base/testing_browser_process.h"
 #include "chrome/test/base/testing_profile.h"
 #include "chrome/test/base/testing_profile_manager.h"
@@ -27,83 +30,6 @@
 const char kDmToken[] = "dm_token";
 const char kTestUrl[] = "http://example.com";
 
-// A derivative of DeepScanningDialogDelegate that overrides calls to the
-// real binary upload service and re-implements them locally.
-class FakeDeepScanningDialogDelegate : public DeepScanningDialogDelegate {
- public:
-  static std::unique_ptr<DeepScanningDialogDelegate> Create(
-      base::RepeatingClosure delete_closure,
-      content::WebContents* web_contents,
-      Data data,
-      CompletionCallback callback) {
-    auto ret = std::make_unique<FakeDeepScanningDialogDelegate>(
-        delete_closure, web_contents, std::move(data), std::move(callback));
-    return ret;
-  }
-
-  FakeDeepScanningDialogDelegate(base::RepeatingClosure delete_closure,
-                                 content::WebContents* web_contents,
-                                 Data data,
-                                 CompletionCallback callback)
-      : DeepScanningDialogDelegate(web_contents,
-                                   std::move(data),
-                                   std::move(callback)),
-        delete_closure_(delete_closure) {}
-
-  ~FakeDeepScanningDialogDelegate() override {
-    if (!delete_closure_.is_null())
-      delete_closure_.Run();
-  }
-
- private:
-  void Response(base::FilePath path,
-                std::unique_ptr<BinaryUploadService::Request> request) {
-    DeepScanningClientResponse response;
-    response.mutable_dlp_scan_verdict();
-    response.mutable_malware_scan_verdict();
-
-    if (path.empty()) {
-      StringRequestCallback(BinaryUploadService::Result::SUCCESS, response);
-    } else {
-      FileRequestCallback(path, BinaryUploadService::Result::SUCCESS, response);
-    }
-  }
-
-  void UploadTextForDeepScanning(
-      std::unique_ptr<BinaryUploadService::Request> request) override {
-    EXPECT_EQ(
-        DlpDeepScanningClientRequest::WEB_CONTENT_UPLOAD,
-        request->deep_scanning_request().dlp_scan_request().content_source());
-    EXPECT_EQ(kDmToken, request->deep_scanning_request().dm_token());
-
-    // Simulate a response.
-    base::ThreadTaskRunnerHandle::Get()->PostTask(
-        FROM_HERE, base::BindOnce(&FakeDeepScanningDialogDelegate::Response,
-                                  base::Unretained(this), base::FilePath(),
-                                  std::move(request)));
-  }
-
-  void UploadFileForDeepScanning(
-      const base::FilePath& path,
-      std::unique_ptr<BinaryUploadService::Request> request) override {
-    DCHECK(!path.empty());
-    EXPECT_EQ(
-        DlpDeepScanningClientRequest::WEB_CONTENT_UPLOAD,
-        request->deep_scanning_request().dlp_scan_request().content_source());
-    EXPECT_EQ(kDmToken, request->deep_scanning_request().dm_token());
-
-    // Simulate a response.
-    base::ThreadTaskRunnerHandle::Get()->PostTask(
-        FROM_HERE,
-        base::BindOnce(&FakeDeepScanningDialogDelegate::Response,
-                       base::Unretained(this), path, std::move(request)));
-  }
-
-  bool CloseTabModalDialog() override { return false; }
-
-  base::RepeatingClosure delete_closure_;
-};
-
 class BaseTest : public testing::Test {
  public:
   BaseTest() : profile_manager_(TestingBrowserProcess::GetGlobal()) {
@@ -126,6 +52,11 @@
         prefs::kCheckContentCompliance, state);
   }
 
+  void SetWaitPolicy(DelayDeliveryUntilVerdictValues state) {
+    TestingBrowserProcess::GetGlobal()->local_state()->SetInteger(
+        prefs::kDelayDeliveryUntilVerdict, state);
+  }
+
   void SetMalwarePolicy(SendFilesForMalwareCheckValues state) {
     profile_->GetPrefs()->SetInteger(
         prefs::kSafeBrowsingSendFilesForMalwareCheck, state);
@@ -322,6 +253,10 @@
     return web_contents_.get();
   }
 
+  void PathFailsDeepScan(base::FilePath path) {
+    failures_.insert(std::move(path));
+  }
+
  private:
   void SetUp() override {
     BaseTest::SetUp();
@@ -332,11 +267,22 @@
     SetMalwarePolicy(SEND_UPLOADS);
 
     DeepScanningDialogDelegate::SetFactoryForTesting(base::BindRepeating(
-        &FakeDeepScanningDialogDelegate::Create, run_loop_.QuitClosure()));
+        &FakeDeepScanningDialogDelegate::Create, run_loop_.QuitClosure(),
+        base::Bind(&DeepScanningDialogDelegateAuditOnlyTest::StatusCallback,
+                   base::Unretained(this)),
+        kDmToken));
+  }
+
+  bool StatusCallback(const base::FilePath& path) {
+    // The path succeeds if it is not in the |failures_| maps.
+    return failures_.find(path) == failures_.end();
   }
 
   base::RunLoop run_loop_;
   std::unique_ptr<content::WebContents> web_contents_;
+
+  // Paths in this map will be consider to have failed deep scan checks.
+  std::set<base::FilePath> failures_;
 };
 
 TEST_F(DeepScanningDialogDelegateAuditOnlyTest, Empty) {
@@ -346,16 +292,21 @@
 
   // Keep |data| empty by not setting any text or paths.
 
+  bool called = false;
   DeepScanningDialogDelegate::ShowForWebContents(
       contents(), std::move(data),
-      base::BindOnce([](const DeepScanningDialogDelegate::Data& data,
-                        const DeepScanningDialogDelegate::Result& result) {
-        EXPECT_EQ(0u, data.text.size());
-        EXPECT_EQ(0u, data.paths.size());
-        EXPECT_EQ(0u, result.text_results.size());
-        EXPECT_EQ(0u, result.paths_results.size());
-      }));
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(0u, data.text.size());
+            EXPECT_EQ(0u, data.paths.size());
+            EXPECT_EQ(0u, result.text_results.size());
+            EXPECT_EQ(0u, result.paths_results.size());
+            *called = true;
+          },
+          &called));
   RunUntilDone();
+  EXPECT_TRUE(called);
 }
 
 TEST_F(DeepScanningDialogDelegateAuditOnlyTest, StringData) {
@@ -365,17 +316,22 @@
 
   data.text.emplace_back(base::UTF8ToUTF16("foo"));
 
+  bool called = false;
   DeepScanningDialogDelegate::ShowForWebContents(
       contents(), std::move(data),
-      base::BindOnce([](const DeepScanningDialogDelegate::Data& data,
-                        const DeepScanningDialogDelegate::Result& result) {
-        EXPECT_EQ(1u, data.text.size());
-        EXPECT_EQ(0u, data.paths.size());
-        ASSERT_EQ(1u, result.text_results.size());
-        EXPECT_EQ(0u, result.paths_results.size());
-        EXPECT_TRUE(result.text_results[0]);
-      }));
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(1u, data.text.size());
+            EXPECT_EQ(0u, data.paths.size());
+            ASSERT_EQ(1u, result.text_results.size());
+            EXPECT_EQ(0u, result.paths_results.size());
+            EXPECT_TRUE(result.text_results[0]);
+            *called = true;
+          },
+          &called));
   RunUntilDone();
+  EXPECT_TRUE(called);
 }
 
 TEST_F(DeepScanningDialogDelegateAuditOnlyTest, StringData2) {
@@ -386,18 +342,23 @@
   data.text.emplace_back(base::UTF8ToUTF16("foo"));
   data.text.emplace_back(base::UTF8ToUTF16("bar"));
 
+  bool called = false;
   DeepScanningDialogDelegate::ShowForWebContents(
       contents(), std::move(data),
-      base::BindOnce([](const DeepScanningDialogDelegate::Data& data,
-                        const DeepScanningDialogDelegate::Result& result) {
-        EXPECT_EQ(2u, data.text.size());
-        EXPECT_EQ(0u, data.paths.size());
-        ASSERT_EQ(2u, result.text_results.size());
-        EXPECT_EQ(0u, result.paths_results.size());
-        EXPECT_TRUE(result.text_results[0]);
-        EXPECT_TRUE(result.text_results[1]);
-      }));
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(2u, data.text.size());
+            EXPECT_EQ(0u, data.paths.size());
+            ASSERT_EQ(2u, result.text_results.size());
+            EXPECT_EQ(0u, result.paths_results.size());
+            EXPECT_TRUE(result.text_results[0]);
+            EXPECT_TRUE(result.text_results[1]);
+            *called = true;
+          },
+          &called));
   RunUntilDone();
+  EXPECT_TRUE(called);
 }
 
 TEST_F(DeepScanningDialogDelegateAuditOnlyTest, FileData) {
@@ -407,17 +368,22 @@
 
   data.paths.emplace_back(FILE_PATH_LITERAL("/tmp/foo"));
 
+  bool called = false;
   DeepScanningDialogDelegate::ShowForWebContents(
       contents(), std::move(data),
-      base::BindOnce([](const DeepScanningDialogDelegate::Data& data,
-                        const DeepScanningDialogDelegate::Result& result) {
-        EXPECT_EQ(0u, data.text.size());
-        EXPECT_EQ(1u, data.paths.size());
-        EXPECT_EQ(0u, result.text_results.size());
-        ASSERT_EQ(1u, result.paths_results.size());
-        EXPECT_TRUE(result.paths_results[0]);
-      }));
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(0u, data.text.size());
+            EXPECT_EQ(1u, data.paths.size());
+            EXPECT_EQ(0u, result.text_results.size());
+            ASSERT_EQ(1u, result.paths_results.size());
+            EXPECT_TRUE(result.paths_results[0]);
+            *called = true;
+          },
+          &called));
   RunUntilDone();
+  EXPECT_TRUE(called);
 }
 
 TEST_F(DeepScanningDialogDelegateAuditOnlyTest, FileData2) {
@@ -428,18 +394,23 @@
   data.paths.emplace_back(FILE_PATH_LITERAL("/tmp/foo"));
   data.paths.emplace_back(FILE_PATH_LITERAL("/tmp/bar"));
 
+  bool called = false;
   DeepScanningDialogDelegate::ShowForWebContents(
       contents(), std::move(data),
-      base::BindOnce([](const DeepScanningDialogDelegate::Data& data,
-                        const DeepScanningDialogDelegate::Result& result) {
-        EXPECT_EQ(0u, data.text.size());
-        EXPECT_EQ(2u, data.paths.size());
-        EXPECT_EQ(0u, result.text_results.size());
-        ASSERT_EQ(2u, result.paths_results.size());
-        EXPECT_TRUE(result.paths_results[0]);
-        EXPECT_TRUE(result.paths_results[1]);
-      }));
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(0u, data.text.size());
+            EXPECT_EQ(2u, data.paths.size());
+            EXPECT_EQ(0u, result.text_results.size());
+            ASSERT_EQ(2u, result.paths_results.size());
+            EXPECT_TRUE(result.paths_results[0]);
+            EXPECT_TRUE(result.paths_results[1]);
+            *called = true;
+          },
+          &called));
   RunUntilDone();
+  EXPECT_TRUE(called);
 }
 
 TEST_F(DeepScanningDialogDelegateAuditOnlyTest, StringFileData) {
@@ -451,19 +422,79 @@
   data.paths.emplace_back(FILE_PATH_LITERAL("/tmp/foo"));
   data.paths.emplace_back(FILE_PATH_LITERAL("/tmp/bar"));
 
+  bool called = false;
   DeepScanningDialogDelegate::ShowForWebContents(
       contents(), std::move(data),
-      base::BindOnce([](const DeepScanningDialogDelegate::Data& data,
-                        const DeepScanningDialogDelegate::Result& result) {
-        EXPECT_EQ(1u, data.text.size());
-        EXPECT_EQ(2u, data.paths.size());
-        ASSERT_EQ(1u, result.text_results.size());
-        ASSERT_EQ(2u, result.paths_results.size());
-        EXPECT_TRUE(result.text_results[0]);
-        EXPECT_TRUE(result.paths_results[0]);
-        EXPECT_TRUE(result.paths_results[1]);
-      }));
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(1u, data.text.size());
+            EXPECT_EQ(2u, data.paths.size());
+            ASSERT_EQ(1u, result.text_results.size());
+            ASSERT_EQ(2u, result.paths_results.size());
+            EXPECT_TRUE(result.text_results[0]);
+            EXPECT_TRUE(result.paths_results[0]);
+            EXPECT_TRUE(result.paths_results[1]);
+            *called = true;
+          },
+          &called));
   RunUntilDone();
+  EXPECT_TRUE(called);
+}
+
+TEST_F(DeepScanningDialogDelegateAuditOnlyTest, StringFileDataPartialSuccess) {
+  SetWaitPolicy(DELAY_UPLOADS);
+
+  GURL url(kTestUrl);
+  DeepScanningDialogDelegate::Data data;
+  ASSERT_TRUE(DeepScanningDialogDelegate::IsEnabled(profile(), url, &data));
+
+  data.text.emplace_back(base::UTF8ToUTF16("foo"));
+  data.paths.emplace_back(FILE_PATH_LITERAL("/tmp/foo"));
+
+  PathFailsDeepScan(data.paths[0]);
+
+  bool called = false;
+  DeepScanningDialogDelegate::ShowForWebContents(
+      contents(), std::move(data),
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(1u, data.text.size());
+            EXPECT_EQ(1u, data.paths.size());
+            ASSERT_EQ(1u, result.text_results.size());
+            ASSERT_EQ(1u, result.paths_results.size());
+            EXPECT_TRUE(result.text_results[0]);
+            EXPECT_FALSE(result.paths_results[0]);
+            *called = true;
+          },
+          &called));
+  RunUntilDone();
+  EXPECT_TRUE(called);
+}
+
+TEST_F(DeepScanningDialogDelegateAuditOnlyTest, EmptyWait) {
+  SetWaitPolicy(DELAY_UPLOADS);
+
+  GURL url(kTestUrl);
+  DeepScanningDialogDelegate::Data data;
+  ASSERT_TRUE(DeepScanningDialogDelegate::IsEnabled(profile(), url, &data));
+
+  bool called = false;
+  DeepScanningDialogDelegate::ShowForWebContents(
+      contents(), std::move(data),
+      base::BindOnce(
+          [](bool* called, const DeepScanningDialogDelegate::Data& data,
+             const DeepScanningDialogDelegate::Result& result) {
+            EXPECT_EQ(0u, data.text.size());
+            EXPECT_EQ(0u, data.paths.size());
+            ASSERT_EQ(0u, result.text_results.size());
+            ASSERT_EQ(0u, result.paths_results.size());
+            *called = true;
+          },
+          &called));
+  RunUntilDone();
+  EXPECT_TRUE(called);
 }
 
 }  // namespace
diff --git a/chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.cc b/chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.cc
new file mode 100644
index 0000000..83d0b85
--- /dev/null
+++ b/chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.cc
@@ -0,0 +1,100 @@
+// Copyright (c) 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.h"
+
+#include <base/callback.h>
+#include <base/logging.h>
+
+namespace safe_browsing {
+
+FakeDeepScanningDialogDelegate::FakeDeepScanningDialogDelegate(
+    base::RepeatingClosure delete_closure,
+    StatusCallback status_callback,
+    std::string dm_token,
+    content::WebContents* web_contents,
+    Data data,
+    CompletionCallback callback)
+    : DeepScanningDialogDelegate(web_contents,
+                                 std::move(data),
+                                 std::move(callback)),
+      delete_closure_(delete_closure),
+      status_callback_(status_callback),
+      dm_token_(std::move(dm_token)) {}
+
+FakeDeepScanningDialogDelegate::~FakeDeepScanningDialogDelegate() {
+  if (!delete_closure_.is_null())
+    delete_closure_.Run();
+}
+
+// static
+std::unique_ptr<DeepScanningDialogDelegate>
+FakeDeepScanningDialogDelegate::Create(base::RepeatingClosure delete_closure,
+                                       StatusCallback status_callback,
+                                       std::string dm_token,
+                                       content::WebContents* web_contents,
+                                       Data data,
+                                       CompletionCallback callback) {
+  auto ret = std::make_unique<FakeDeepScanningDialogDelegate>(
+      delete_closure, status_callback, std::move(dm_token), web_contents,
+      std::move(data), std::move(callback));
+  return ret;
+}
+
+void FakeDeepScanningDialogDelegate::Response(
+    base::FilePath path,
+    std::unique_ptr<BinaryUploadService::Request> request) {
+  DeepScanningClientResponse response;
+  bool status = status_callback_.is_null() ? false : status_callback_.Run(path);
+  if (!status) {
+    // If the scan should fail, mark both the DLP and malware as failed.
+    // for DLP, just add a rule to the triggered list., does not matter what
+    // the rule is.  For malware, just set the verdict to MALWARE.
+    response.mutable_dlp_scan_verdict()->mutable_triggered_rules()->Add();
+    response.mutable_malware_scan_verdict()->set_verdict(
+        MalwareDeepScanningVerdict::MALWARE);
+  }
+
+  if (path.empty()) {
+    StringRequestCallback(BinaryUploadService::Result::SUCCESS, response);
+  } else {
+    FileRequestCallback(path, BinaryUploadService::Result::SUCCESS, response);
+  }
+}
+
+void FakeDeepScanningDialogDelegate::UploadTextForDeepScanning(
+    std::unique_ptr<BinaryUploadService::Request> request) {
+  DCHECK_EQ(
+      DlpDeepScanningClientRequest::WEB_CONTENT_UPLOAD,
+      request->deep_scanning_request().dlp_scan_request().content_source());
+  DCHECK_EQ(dm_token_, request->deep_scanning_request().dm_token());
+
+  // Simulate a response.
+  base::ThreadTaskRunnerHandle::Get()->PostTask(
+      FROM_HERE, base::BindOnce(&FakeDeepScanningDialogDelegate::Response,
+                                base::Unretained(this), base::FilePath(),
+                                std::move(request)));
+}
+
+void FakeDeepScanningDialogDelegate::UploadFileForDeepScanning(
+    const base::FilePath& path,
+    std::unique_ptr<BinaryUploadService::Request> request) {
+  DCHECK(!path.empty());
+  DCHECK_EQ(
+      DlpDeepScanningClientRequest::WEB_CONTENT_UPLOAD,
+      request->deep_scanning_request().dlp_scan_request().content_source());
+  DCHECK_EQ(dm_token_, request->deep_scanning_request().dm_token());
+
+  // Simulate a response.
+  base::ThreadTaskRunnerHandle::Get()->PostTask(
+      FROM_HERE,
+      base::BindOnce(&FakeDeepScanningDialogDelegate::Response,
+                     base::Unretained(this), path, std::move(request)));
+}
+
+bool FakeDeepScanningDialogDelegate::CloseTabModalDialog() {
+  return false;
+}
+
+}  // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.h b/chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.h
new file mode 100644
index 0000000..4e0b2ad
--- /dev/null
+++ b/chrome/browser/safe_browsing/cloud_content_scanning/fake_deep_scanning_dialog_delegate.h
@@ -0,0 +1,71 @@
+// Copyright (c) 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CHROME_BROWSER_SAFE_BROWSING_CLOUD_CONTENT_SCANNING_FAKE_DEEP_SCANNING_DIALOG_DELEGATE_H_
+#define CHROME_BROWSER_SAFE_BROWSING_CLOUD_CONTENT_SCANNING_FAKE_DEEP_SCANNING_DIALOG_DELEGATE_H_
+
+#include <memory>
+
+#include "base/callback_forward.h"
+#include "base/files/file_path.h"
+#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.h"
+#include "chrome/browser/safe_browsing/download_protection/binary_upload_service.h"
+
+namespace content {
+class WebContents;
+}
+
+namespace safe_browsing {
+
+// A derivative of DeepScanningDialogDelegate that overrides calls to the
+// real binary upload service and re-implements them locally.
+class FakeDeepScanningDialogDelegate : public DeepScanningDialogDelegate {
+ public:
+  // Callback that determines the scan status of the file specified.  To
+  // simulate a file that passes a scan, return true, otherwise return false.
+  // If an empty path is given, this represents the non-file based text data.
+  using StatusCallback = base::RepeatingCallback<bool(const base::FilePath&)>;
+
+  FakeDeepScanningDialogDelegate(base::RepeatingClosure delete_closure,
+                                 StatusCallback status_callback,
+                                 std::string dm_token,
+                                 content::WebContents* web_contents,
+                                 Data data,
+                                 CompletionCallback callback);
+  ~FakeDeepScanningDialogDelegate() override;
+
+  // Use with DeepScanningDialogDelegate::SetFactoryForTesting() to create
+  // fake instances of this class.  Note that all but the last three arguments
+  // will need to be bound at base::Bind() time.
+  static std::unique_ptr<DeepScanningDialogDelegate> Create(
+      base::RepeatingClosure delete_closure,
+      StatusCallback status_callback,
+      std::string dm_token,
+      content::WebContents* web_contents,
+      Data data,
+      CompletionCallback callback);
+
+ private:
+  // Simulates a response from the binary upload service.  the |path| argument
+  // is used to call |status_callback_| to determine if the path should succeed
+  // or fail.
+  void Response(base::FilePath path,
+                std::unique_ptr<BinaryUploadService::Request> request);
+
+  // DeepScanningDialogDelegate overrides.
+  void UploadTextForDeepScanning(
+      std::unique_ptr<BinaryUploadService::Request> request) override;
+  void UploadFileForDeepScanning(
+      const base::FilePath& path,
+      std::unique_ptr<BinaryUploadService::Request> request) override;
+  bool CloseTabModalDialog() override;
+
+  base::RepeatingClosure delete_closure_;
+  StatusCallback status_callback_;
+  std::string dm_token_;
+};
+
+}  // namespace safe_browsing
+
+#endif  // CHROME_BROWSER_SAFE_BROWSING_CLOUD_CONTENT_SCANNING_FAKE_DEEP_SCANNING_DIALOG_DELEGATE_H_
diff --git a/chrome/browser/signin/chrome_signin_client.cc b/chrome/browser/signin/chrome_signin_client.cc
index d944446..106856e 100644
--- a/chrome/browser/signin/chrome_signin_client.cc
+++ b/chrome/browser/signin/chrome_signin_client.cc
@@ -133,10 +133,6 @@
       ->GetCookieManagerForBrowserProcess();
 }
 
-std::string ChromeSigninClient::GetProductVersion() {
-  return chrome::GetVersionString();
-}
-
 bool ChromeSigninClient::AreSigninCookiesAllowed() {
   return ProfileAllowsSigninCookies(profile_);
 }
diff --git a/chrome/browser/signin/chrome_signin_client.h b/chrome/browser/signin/chrome_signin_client.h
index 2f6d7c8..3a3165f 100644
--- a/chrome/browser/signin/chrome_signin_client.h
+++ b/chrome/browser/signin/chrome_signin_client.h
@@ -63,11 +63,6 @@
       gaia::GaiaSource source) override;
   bool IsNonEnterpriseUser(const std::string& username) override;
 
-  // Returns a string describing the chrome version environment. Version format:
-  // <Build Info> <OS> <Version number> (<Last change>)<channel or "-devel">
-  // If version information is unavailable, returns "invalid."
-  std::string GetProductVersion() override;
-
   // gaia::GaiaOAuthClient::Delegate implementation.
   void OnGetTokenInfoResponse(
       std::unique_ptr<base::DictionaryValue> token_info) override;
diff --git a/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc b/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc
index fd3da450..409a163 100644
--- a/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc
+++ b/chrome/browser/ssl/captive_portal_blocking_page_browsertest.cc
@@ -44,7 +44,6 @@
 #include "net/cert/x509_certificate.h"
 #include "net/test/cert_test_util.h"
 #include "net/test/test_data_directory.h"
-#include "net/test/url_request/url_request_failed_job.h"
 #include "testing/gtest/include/gtest/gtest.h"
 #include "url/gurl.h"
 
@@ -207,11 +206,6 @@
           is_wifi_connection_, wifi_ssid_));
 }
 
-void AddURLRequestFilterOnIOThread() {
-  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
-  net::URLRequestFailedJob::AddUrlHandler();
-}
-
 }  // namespace
 
 class CaptivePortalBlockingPageTest : public InProcessBrowserTest {
@@ -220,11 +214,6 @@
     CertReportHelper::SetFakeOfficialBuildForTesting();
   }
 
-  void SetUpOnMainThread() override {
-    base::PostTask(FROM_HERE, {content::BrowserThread::IO},
-                   base::BindOnce(&AddURLRequestFilterOnIOThread));
-  }
-
   void SetUpCommandLine(base::CommandLine* command_line) override {
     // Setting the sending threshold to 1.0 ensures reporting is enabled.
     variations::testing::VariationParamsManager::AppendVariationParams(
@@ -284,9 +273,11 @@
   // handled by the normal SSLErrorNavigationThrotttle since this test only
   // checks the behavior of the Blocking Page, not the integration with that
   // throttle.
-  ui_test_utils::NavigateToURL(
-      browser(),
-      net::URLRequestFailedJob::GetMockHttpsUrl(net::ERR_BLOCKED_BY_CLIENT));
+  //
+  // TODO(https://crbug.com/1003940): Clean this code up now that committed
+  // interstitials have shipped.
+  ui_test_utils::NavigateToURL(browser(),
+                               GURL("https://mock.failed.request/start=-20"));
   content::RenderFrameHost* frame;
   frame = contents->GetMainFrame();
   ASSERT_TRUE(WaitForRenderFrameReady(frame));
diff --git a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc
index 91afc174..77dc011 100644
--- a/chrome/browser/ssl/security_state_tab_helper_browsertest.cc
+++ b/chrome/browser/ssl/security_state_tab_helper_browsertest.cc
@@ -5,6 +5,7 @@
 #include "chrome/browser/ssl/security_state_tab_helper.h"
 
 #include "base/base64.h"
+#include "base/base_paths.h"
 #include "base/bind.h"
 #include "base/command_line.h"
 #include "base/feature_list.h"
@@ -12,6 +13,7 @@
 #include "base/macros.h"
 #include "base/metrics/field_trial.h"
 #include "base/metrics/field_trial_params.h"
+#include "base/path_service.h"
 #include "base/run_loop.h"
 #include "base/strings/string_split.h"
 #include "base/strings/utf_string_conversions.h"
@@ -74,6 +76,7 @@
 #include "content/public/test/test_navigation_observer.h"
 #include "content/public/test/url_loader_interceptor.h"
 #include "net/base/net_errors.h"
+#include "net/cert/cert_database.h"
 #include "net/cert/cert_status_flags.h"
 #include "net/cert/cert_verify_result.h"
 #include "net/cert/ct_policy_status.h"
@@ -89,9 +92,6 @@
 #include "net/test/embedded_test_server/http_response.h"
 #include "net/test/embedded_test_server/request_handler_util.h"
 #include "net/test/test_data_directory.h"
-#include "net/test/url_request/url_request_failed_job.h"
-#include "net/url_request/url_request_filter.h"
-#include "net/url_request/url_request_test_util.h"
 #include "services/service_manager/public/cpp/connector.h"
 #include "third_party/blink/public/common/features.h"
 #include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h"
@@ -1270,32 +1270,6 @@
                            browser(), cert.get());
 }
 
-// Fails requests with ERR_IO_PENDING. Can be used to simulate a navigation
-// that never stops loading.
-class PendingJobInterceptor : public net::URLRequestInterceptor {
- public:
-  PendingJobInterceptor() {}
-  ~PendingJobInterceptor() override {}
-
-  // URLRequestInterceptor implementation
-  net::URLRequestJob* MaybeInterceptRequest(
-      net::URLRequest* request,
-      net::NetworkDelegate* network_delegate) const override {
-    return new net::URLRequestFailedJob(request, network_delegate,
-                                        net::ERR_IO_PENDING);
-  }
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(PendingJobInterceptor);
-};
-
-void InstallLoadingInterceptor(const std::string& host) {
-  net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
-  filter->AddHostnameInterceptor(
-      "http", host,
-      std::unique_ptr<net::URLRequestInterceptor>(new PendingJobInterceptor()));
-}
-
 class SecurityStateLoadingTest : public SecurityStateTabHelperTest {
  public:
   SecurityStateLoadingTest() : SecurityStateTabHelperTest() {}
@@ -1304,11 +1278,6 @@
  protected:
   void SetUpOnMainThread() override {
     ASSERT_TRUE(embedded_test_server()->Start());
-
-    base::PostTask(
-        FROM_HERE, {content::BrowserThread::IO},
-        base::BindOnce(&InstallLoadingInterceptor,
-                       embedded_test_server()->GetURL("/title1.html").host()));
   }
 
  private:
diff --git a/chrome/browser/ssl/ssl_browsertest.cc b/chrome/browser/ssl/ssl_browsertest.cc
index 9307472d..4caaaff 100644
--- a/chrome/browser/ssl/ssl_browsertest.cc
+++ b/chrome/browser/ssl/ssl_browsertest.cc
@@ -125,7 +125,6 @@
 #include "content/public/browser/web_contents.h"
 #include "content/public/browser/web_contents_observer.h"
 #include "content/public/common/content_switches.h"
-#include "content/public/common/network_service_util.h"
 #include "content/public/common/page_state.h"
 #include "content/public/common/service_names.mojom.h"
 #include "content/public/common/url_constants.h"
@@ -143,6 +142,7 @@
 #include "net/base/io_buffer.h"
 #include "net/base/net_errors.h"
 #include "net/cert/asn1_util.h"
+#include "net/cert/cert_database.h"
 #include "net/cert/cert_status_flags.h"
 #include "net/cert/mock_cert_verifier.h"
 #include "net/cert/x509_certificate.h"
@@ -163,10 +163,6 @@
 #include "net/test/spawned_test_server/spawned_test_server.h"
 #include "net/test/test_certificate_data.h"
 #include "net/test/test_data_directory.h"
-#include "net/url_request/url_request_context.h"
-#include "net/url_request/url_request_filter.h"
-#include "net/url_request/url_request_job.h"
-#include "net/url_request/url_request_test_util.h"
 #include "services/network/public/cpp/features.h"
 #include "services/network/public/cpp/network_switches.h"
 #include "services/network/public/mojom/network_service.mojom.h"
@@ -276,32 +272,6 @@
   DISALLOW_COPY_AND_ASSIGN(SSLInterstitialTimerObserver);
 };
 
-class HungJob : public net::URLRequestJob {
- public:
-  HungJob(net::URLRequest* request, net::NetworkDelegate* network_delegate)
-      : net::URLRequestJob(request, network_delegate) {}
-
-  void Start() override {}
-};
-
-class FaviconFilter : public net::URLRequestInterceptor {
- public:
-  FaviconFilter() {}
-  ~FaviconFilter() override {}
-
-  // net::URLRequestInterceptor implementation
-  net::URLRequestJob* MaybeInterceptRequest(
-      net::URLRequest* request,
-      net::NetworkDelegate* network_delegate) const override {
-    if (request->url().path() == "/favicon.ico")
-      return new HungJob(request, network_delegate);
-    return nullptr;
-  }
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(FaviconFilter);
-};
-
 class ChromeContentBrowserClientForMixedContentTest
     : public ChromeContentBrowserClient {
  public:
@@ -523,20 +493,6 @@
     https_server_common_name_only_.SetSSLConfig(
         net::EmbeddedTestServer::CERT_COMMON_NAME_ONLY);
     https_server_common_name_only_.AddDefaultHandlers(GetChromeTestDataDir());
-
-    // Sometimes favicons load before tests check the authentication
-    // state, and sometimes they load after. This is problematic on
-    // tests that load pages with certificate errors, because the page
-    // will be marked as having displayed subresources with certificate
-    // errors only if the favicon loads before the test checks the
-    // authentication state. To avoid this non-determinism, add an
-    // interceptor to hang all favicon requests.
-    std::unique_ptr<net::URLRequestInterceptor> interceptor(new FaviconFilter);
-    net::URLRequestFilter::GetInstance()->AddHostnameInterceptor(
-        "https", "127.0.0.1", std::move(interceptor));
-    interceptor.reset(new FaviconFilter);
-    net::URLRequestFilter::GetInstance()->AddHostnameInterceptor(
-        "https", "localhost", std::move(interceptor));
   }
 
   void SetUp() override {
@@ -804,25 +760,6 @@
         ->FlushSSLConfigManagerForTesting();
   }
 
-  // Checks that the TransportSecurityState associated with the
-  // net::URLRequestContext of the |context_getter| will return
-  // |expected_status| for |host|, given the certificate |cert|,
-  // |is_issued_by_known_root|, associated |hashes|, and a CT policy result of
-  // |policy_compliance|.
-  void CheckCTStatus(
-      scoped_refptr<net::URLRequestContextGetter> context_getter,
-      const std::string& host,
-      scoped_refptr<net::X509Certificate> cert,
-      bool is_issued_by_known_root,
-      const net::HashValueVector& hashes,
-      net::ct::CTPolicyCompliance policy_compliance,
-      net::TransportSecurityState::CTRequirementsStatus expected_status) {
-    RunOnIOThreadBlocking(base::BindOnce(
-        &SSLUITestBase::CheckCTStatusOnIOThread, base::Unretained(this),
-        context_getter, host, cert, is_issued_by_known_root, hashes,
-        policy_compliance, expected_status));
-  }
-
   // Helper function for TestInterstitialLinksOpenInNewTab. Implemented as a
   // test fixture method because the whole test fixture class is friended by
   // SSLBlockingPage.
@@ -936,30 +873,6 @@
     run_loop.Run();
   }
 
-  void CheckCTStatusOnIOThread(
-      scoped_refptr<net::URLRequestContextGetter> context_getter,
-      std::string host,
-      scoped_refptr<net::X509Certificate> cert,
-      bool known_root,
-      net::HashValueVector hashes,
-      net::ct::CTPolicyCompliance compliance_level,
-      net::TransportSecurityState::CTRequirementsStatus expected_status) {
-    net::URLRequestContext* context = context_getter->GetURLRequestContext();
-    ASSERT_TRUE(context);
-
-    net::TransportSecurityState* tss = context->transport_security_state();
-    ASSERT_TRUE(tss);
-
-    net::HostPortPair host_port_pair(host, 443);
-
-    EXPECT_EQ(expected_status,
-              tss->CheckCTRequirements(
-                  host_port_pair, known_root, hashes, cert.get(), cert.get(),
-                  net::SignedCertificateTimestampAndStatusList(),
-                  net::TransportSecurityState::DISABLE_EXPECT_CT_REPORTS,
-                  compliance_level));
-  }
-
   net::EmbeddedTestServer https_server_;
   net::EmbeddedTestServer https_server_expired_;
   net::EmbeddedTestServer https_server_mismatched_;
@@ -4651,11 +4564,6 @@
       clock_interstitial_ssl_status, after_interstitial_ssl_status));
 }
 
-void CleanUpOnIOThread() {
-  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
-  net::URLRequestFilter::GetInstance()->ClearHandlers();
-}
-
 // A fixture for testing on-demand network time queries on SSL
 // certificate date errors. It can simulate a delayed network time
 // request, and it allows the user to configure the experimental
@@ -4975,53 +4883,6 @@
   TriggerTimeResponse();
 }
 
-namespace {
-
-// Fails with a CHECK for all requests over HTTP except for favicons. This is to
-// ensure that name mismatch redirect feature's suggest URL ping stops on
-// redirects and never hits an HTTP URL.
-class HttpNameMismatchPingInterceptor : public net::URLRequestInterceptor {
- public:
-  HttpNameMismatchPingInterceptor() {}
-  ~HttpNameMismatchPingInterceptor() override {}
-
-  net::URLRequestJob* MaybeInterceptRequest(
-      net::URLRequest* request,
-      net::NetworkDelegate* delegate) const override {
-    if (request->url().path() == "/favicon.ico") {
-      // When a page doesn't list a favicon, a favicon request is automatically
-      // made over HTTP. These are harmless and don't leak the original page's
-      // URL, so ignore them.
-      return nullptr;
-    }
-
-    EXPECT_TRUE(false)
-        << "Name mismatch pings must never be over HTTP. This request was for "
-        << request->url();
-    return nullptr;
-  }
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(HttpNameMismatchPingInterceptor);
-};
-
-void SetUpHttpNameMismatchPingInterceptorOnIOThread() {
-  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
-  // Add interceptors for HTTP versions of example.org and www.example.org.
-  // These are the hostnames used in the tests, and we never want them to be
-  // contacted over HTTP.
-  net::URLRequestFilter::GetInstance()->AddHostnameInterceptor(
-      "http", "example.org",
-      std::unique_ptr<HttpNameMismatchPingInterceptor>(
-          new HttpNameMismatchPingInterceptor()));
-  net::URLRequestFilter::GetInstance()->AddHostnameInterceptor(
-      "http", "www.example.org",
-      std::unique_ptr<HttpNameMismatchPingInterceptor>(
-          new HttpNameMismatchPingInterceptor()));
-}
-
-}  // namespace
-
 class CommonNameMismatchBrowserTest : public CertVerifierBrowserTest {
  public:
   CommonNameMismatchBrowserTest() : CertVerifierBrowserTest() {}
@@ -5036,14 +4897,9 @@
   void SetUpOnMainThread() override {
     CertVerifierBrowserTest::SetUpOnMainThread();
     host_resolver()->AddRule("*", "127.0.0.1");
-    base::PostTask(
-        FROM_HERE, {content::BrowserThread::IO},
-        base::BindOnce(&SetUpHttpNameMismatchPingInterceptorOnIOThread));
   }
 
   void TearDownOnMainThread() override {
-    base::PostTask(FROM_HERE, {content::BrowserThread::IO},
-                   base::BindOnce(&CleanUpOnIOThread));
     CertVerifierBrowserTest::TearDownOnMainThread();
   }
 
@@ -5912,9 +5768,6 @@
 
 // Checks that a newly-added certificate authority is usable immediately.
 IN_PROC_BROWSER_TEST_F(SSLUITestNoCert, NewCertificateAuthority) {
-  if (!content::IsOutOfProcessNetworkService())
-    return;
-
   ASSERT_TRUE(https_server_.Start());
 
   WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
@@ -7077,31 +6930,15 @@
   TestNoMITMSoftwareInterstitial();
 }
 
-void SetRequireCTDelegateOnIOThread(
-    scoped_refptr<net::URLRequestContextGetter> context_getter,
-    net::TransportSecurityState::RequireCTDelegate* delegate) {
-  net::TransportSecurityState* state =
-      context_getter->GetURLRequestContext()->transport_security_state();
-  state->SetRequireCTDelegate(delegate);
-}
-
 void SetShouldNotRequireCTForTesting() {
-  if (content::IsOutOfProcessNetworkService()) {
-    network::mojom::NetworkServiceTestPtr network_service_test;
-    content::GetSystemConnector()->BindInterface(
-        content::mojom::kNetworkServiceName, &network_service_test);
-    network::mojom::NetworkServiceTest::ShouldRequireCT required_ct =
-        network::mojom::NetworkServiceTest::ShouldRequireCT::DONT_REQUIRE;
+  network::mojom::NetworkServiceTestPtr network_service_test;
+  content::GetSystemConnector()->BindInterface(
+      content::mojom::kNetworkServiceName, &network_service_test);
+  network::mojom::NetworkServiceTest::ShouldRequireCT required_ct =
+      network::mojom::NetworkServiceTest::ShouldRequireCT::DONT_REQUIRE;
 
-    mojo::ScopedAllowSyncCallForTesting allow_sync_call;
-    network_service_test->SetShouldRequireCT(required_ct);
-    return;
-  }
-
-  base::PostTask(
-      FROM_HERE, {content::BrowserThread::IO},
-      base::BindOnce(&net::TransportSecurityState::SetShouldRequireCTForTesting,
-                     base::Owned(new bool(false))));
+  mojo::ScopedAllowSyncCallForTesting allow_sync_call;
+  network_service_test->SetShouldRequireCT(required_ct);
 }
 
 class TLSLegacyVersionSSLUITest : public CertVerifierBrowserTest {
@@ -7715,17 +7552,12 @@
   }
 
   void TearDownOnMainThread() override {
-    if (content::IsOutOfProcessNetworkService()) {
-      mojo::ScopedAllowSyncCallForTesting allow_sync_call;
+    mojo::ScopedAllowSyncCallForTesting allow_sync_call;
 
-      network::mojom::NetworkServiceTestPtr network_service_test;
-      content::GetSystemConnector()->BindInterface(
-          content::mojom::kNetworkServiceName, &network_service_test);
-      network_service_test->SetTransportSecurityStateSource(0);
-    } else {
-      RunOnIOThreadBlocking(base::BindOnce(
-          &SSLPKPBrowserTest::CleanUpOnIOThread, base::Unretained(this)));
-    }
+    network::mojom::NetworkServiceTestPtr network_service_test;
+    content::GetSystemConnector()->BindInterface(
+        content::mojom::kNetworkServiceName, &network_service_test);
+    network_service_test->SetTransportSecurityStateSource(0);
     CertVerifierBrowserTest::TearDownOnMainThread();
   }
 
@@ -7736,18 +7568,10 @@
             browser()->profile());
     partition->GetNetworkContext()->EnableStaticKeyPinningForTesting();
 
-    if (content::IsOutOfProcessNetworkService()) {
-      mojo::ScopedAllowSyncCallForTesting allow_sync_call;
-
-      network::mojom::NetworkServiceTestPtr network_service_test;
-      content::GetSystemConnector()->BindInterface(
-          content::mojom::kNetworkServiceName, &network_service_test);
-      network_service_test->SetTransportSecurityStateSource(reporting_port);
-    } else {
-      RunOnIOThreadBlocking(base::BindOnce(
-          &SSLPKPBrowserTest::SetTransportSecurityStateSourceOnIO,
-          base::Unretained(this), reporting_port));
-    }
+    network::mojom::NetworkServiceTestPtr network_service_test;
+    content::GetSystemConnector()->BindInterface(
+        content::mojom::kNetworkServiceName, &network_service_test);
+    network_service_test->SetTransportSecurityStateSource(reporting_port);
   }
 
  private:
@@ -7757,18 +7581,6 @@
                            std::move(task), run_loop.QuitClosure());
     run_loop.Run();
   }
-
-  void SetTransportSecurityStateSourceOnIO(int reporting_port) {
-    transport_security_state_source_ =
-        std::make_unique<net::ScopedTransportSecurityStateSource>(
-            reporting_port);
-  }
-
-  void CleanUpOnIOThread() { transport_security_state_source_.reset(); }
-
-  // Only used when NetworkService is disabled. Accessed on IO thread.
-  std::unique_ptr<net::ScopedTransportSecurityStateSource>
-      transport_security_state_source_;
 };
 
 // Test case where a PKP report is sent.
@@ -7851,12 +7663,6 @@
     host_resolver()->AddRule("*", "127.0.0.1");
   }
 
-  void TearDownOnMainThread() override {
-    base::PostTask(FROM_HERE, {content::BrowserThread::IO},
-                   base::BindOnce(&CleanUpOnIOThread));
-    CertVerifierBrowserTest::TearDownOnMainThread();
-  }
-
  private:
   base::test::ScopedFeatureList scoped_feature_list_;
 };
diff --git a/chrome/browser/themes/theme_properties.cc b/chrome/browser/themes/theme_properties.cc
index ce7780a..a0fbc6e5 100644
--- a/chrome/browser/themes/theme_properties.cc
+++ b/chrome/browser/themes/theme_properties.cc
@@ -141,21 +141,16 @@
   switch (id) {
     case ThemeProperties::COLOR_FRAME:
     case ThemeProperties::COLOR_BACKGROUND_TAB:
-      return color_utils::HSLShift(
-          GetLightModeColor(ThemeProperties::COLOR_FRAME),
-          ThemeProperties::GetDefaultTint(ThemeProperties::TINT_FRAME, true));
+      return gfx::kGoogleGrey900;
     case ThemeProperties::COLOR_FRAME_INACTIVE:
     case ThemeProperties::COLOR_BACKGROUND_TAB_INACTIVE:
-      return color_utils::HSLShift(
-          GetLightModeColor(ThemeProperties::COLOR_FRAME),
-          ThemeProperties::GetDefaultTint(ThemeProperties::TINT_FRAME_INACTIVE,
-                                          true));
+      return gfx::kGoogleGrey800;
     case ThemeProperties::COLOR_DOWNLOAD_SHELF:
     case ThemeProperties::COLOR_STATUS_BUBBLE:
     case ThemeProperties::COLOR_INFOBAR:
     case ThemeProperties::COLOR_TOOLBAR:
     case ThemeProperties::COLOR_NTP_BACKGROUND:
-      return SkColorSetRGB(0x32, 0x36, 0x39);
+      return SkColorSetRGB(0x35, 0x36, 0x3A);
     case ThemeProperties::COLOR_HOVER_CARD_NO_PREVIEW_FOREGROUND:
       return gfx::kGoogleGrey700;
     case ThemeProperties::COLOR_HOVER_CARD_NO_PREVIEW_BACKGROUND:
diff --git a/chrome/browser/touch_to_fill/android/internal/BUILD.gn b/chrome/browser/touch_to_fill/android/internal/BUILD.gn
index 0441544..9e244c2 100644
--- a/chrome/browser/touch_to_fill/android/internal/BUILD.gn
+++ b/chrome/browser/touch_to_fill/android/internal/BUILD.gn
@@ -16,5 +16,6 @@
   java_files = [
     "java/src/org/chromium/chrome/browser/touch_to_fill/TouchToFillBridge.java",
     "java/src/org/chromium/chrome/browser/touch_to_fill/TouchToFillCoordinator.java",
+    "java/src/org/chromium/chrome/browser/touch_to_fill/TouchToFillProperties.java",
   ]
 }
diff --git a/chrome/browser/touch_to_fill/android/internal/README.md b/chrome/browser/touch_to_fill/android/internal/README.md
index 1e5a53b9..683a367 100644
--- a/chrome/browser/touch_to_fill/android/internal/README.md
+++ b/chrome/browser/touch_to_fill/android/internal/README.md
@@ -41,3 +41,30 @@
 3. The view renders the changed credential list.
     1. The view may apply style, RTL settings and event handlers for click events.
 
+
+## Model
+
+The model holds state and event listeners connected to the view. An MCP
+automatically notifies listener about any change made to a property. To automate
+this Observer structure, the model is a `PropertyModel` as defined in
+`//src/ui/android/java/src/org/chromium/ui/modelutil/`. It is build by defining
+readable and writable properties and constructing a model with them. The
+properties (and a simple factory method for the model) are located in the static
+`TouchToFillProperties` class.
+
+The model contains writable and readable properties.The readable properties are
+guaranteed to never change for the lifetime of the Touch To Fill component:
+
+ * **VIEW_EVENT_LISTENER** which is the listener that reacts to view events. The
+   mediator implements this interface.
+ * **CREDENTIAL_LIST** which is the set of displayed credentials. The list
+   itself will be modified (credentials will be added and removed) but the
+   object remains the same which allows to permanently bind it to a list
+   adapter.
+
+The writable properties change over the course of the components lifetime:
+
+ * **VISIBLE** which will trigger the component to render the bottom sheet or
+   hide it, if it was visible.
+ * **FORMATTED_URL** which is displayed as subtitle for the bottom sheet.
+
diff --git a/chrome/browser/touch_to_fill/android/internal/java/src/org/chromium/chrome/browser/touch_to_fill/TouchToFillProperties.java b/chrome/browser/touch_to_fill/android/internal/java/src/org/chromium/chrome/browser/touch_to_fill/TouchToFillProperties.java
new file mode 100644
index 0000000..09c1630
--- /dev/null
+++ b/chrome/browser/touch_to_fill/android/internal/java/src/org/chromium/chrome/browser/touch_to_fill/TouchToFillProperties.java
@@ -0,0 +1,49 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.chrome.browser.touch_to_fill;
+
+import org.chromium.chrome.browser.touch_to_fill.data.Credential;
+import org.chromium.ui.modelutil.ListModel;
+import org.chromium.ui.modelutil.PropertyModel;
+
+/**
+ * Properties defined here reflect the visible state of the TouchToFill-components.
+ */
+class TouchToFillProperties {
+    static final PropertyModel.WritableBooleanPropertyKey VISIBLE =
+            new PropertyModel.WritableBooleanPropertyKey("visible");
+    static final PropertyModel.WritableObjectPropertyKey<String> FORMATTED_URL =
+            new PropertyModel.WritableObjectPropertyKey<>("formatted_url");
+    static final PropertyModel.ReadableObjectPropertyKey<ListModel<Credential>> CREDENTIAL_LIST =
+            new PropertyModel.ReadableObjectPropertyKey<>("credential_list");
+    static final PropertyModel.ReadableObjectPropertyKey<ViewEventListener> VIEW_EVENT_LISTENER =
+            new PropertyModel.ReadableObjectPropertyKey<>("view_event_listener");
+
+    static PropertyModel createDefaultModel(ViewEventListener listener) {
+        return new PropertyModel
+                .Builder(VISIBLE, FORMATTED_URL, CREDENTIAL_LIST, VIEW_EVENT_LISTENER)
+                .with(VISIBLE, false)
+                .with(CREDENTIAL_LIST, new ListModel<>())
+                .with(VIEW_EVENT_LISTENER, listener)
+                .build();
+    }
+
+    /**
+     * This interface is used by the view to communicate events back to the mediator. It abstracts
+     * from the view by stripping information like parents, id or context.
+     */
+    interface ViewEventListener {
+        /**
+         * Called if the user selected an item from the list.
+         * @param position The position that the user selected.
+         */
+        void onSelectItemAt(int position);
+
+        /** Called if the user dismissed the view. */
+        void onDismissed();
+    }
+
+    private TouchToFillProperties() {}
+}
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc b/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc
index cf52275..1ef2be7 100644
--- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc
+++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view.cc
@@ -62,6 +62,7 @@
 #include "components/metrics/metrics_service.h"
 #include "components/prefs/pref_service.h"
 #include "components/url_formatter/elide_url.h"
+#include "components/url_formatter/url_formatter.h"
 #include "extensions/browser/extension_registry.h"
 #include "extensions/common/extension.h"
 #include "extensions/common/extension_set.h"
@@ -87,6 +88,7 @@
 #include "ui/gfx/text_constants.h"
 #include "ui/gfx/text_elider.h"
 #include "ui/resources/grit/ui_resources.h"
+#include "ui/views/accessibility/view_accessibility.h"
 #include "ui/views/animation/flood_fill_ink_drop_ripple.h"
 #include "ui/views/animation/ink_drop_highlight.h"
 #include "ui/views/animation/ink_drop_impl.h"
@@ -1534,8 +1536,12 @@
   views::LabelButton* button = nullptr;
   if (node->is_url()) {
     button = new BookmarkButton(this, node->url(), node->GetTitle());
+    button->GetViewAccessibility().OverrideDescription(url_formatter::FormatUrl(
+        node->url(), url_formatter::kFormatUrlOmitDefaults,
+        net::UnescapeRule::SPACES, nullptr, nullptr, nullptr));
   } else {
     button = new BookmarkFolderButton(node->GetTitle(), this);
+    button->GetViewAccessibility().OverrideDescription("");
   }
   ConfigureButton(node, button);
   bookmark_buttons_.insert(bookmark_buttons_.cbegin() + index, button);
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.cc b/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.cc
index a97de83d..5a2027a 100644
--- a/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.cc
+++ b/chrome/browser/ui/views/bookmarks/bookmark_menu_delegate.cc
@@ -24,6 +24,7 @@
 #include "components/bookmarks/common/bookmark_pref_names.h"
 #include "components/bookmarks/managed/managed_bookmark_service.h"
 #include "components/prefs/pref_service.h"
+#include "components/url_formatter/url_formatter.h"
 #include "content/public/browser/page_navigator.h"
 #include "ui/base/accelerators/menu_label_accelerator_util.h"
 #include "ui/base/dragdrop/os_exchange_data.h"
@@ -31,6 +32,7 @@
 #include "ui/base/theme_provider.h"
 #include "ui/base/window_open_disposition.h"
 #include "ui/resources/grit/ui_resources.h"
+#include "ui/views/accessibility/view_accessibility.h"
 #include "ui/views/controls/button/menu_button.h"
 #include "ui/views/controls/menu/menu_item_view.h"
 #include "ui/views/controls/menu/submenu_view.h"
@@ -551,10 +553,15 @@
           rb->GetImageSkiaNamed(IDR_DEFAULT_FAVICON) : image.ToImageSkia();
       child_menu_item = menu->AppendMenuItemWithIcon(
           id, MaybeEscapeLabel(node->GetTitle()), *icon);
+      child_menu_item->GetViewAccessibility().OverrideDescription(
+          url_formatter::FormatUrl(
+              node->url(), url_formatter::kFormatUrlOmitDefaults,
+              net::UnescapeRule::SPACES, nullptr, nullptr, nullptr));
     } else {
       DCHECK(node->is_folder());
       child_menu_item = menu->AppendSubMenuWithIcon(
           id, MaybeEscapeLabel(node->GetTitle()), folder_icon);
+      child_menu_item->GetViewAccessibility().OverrideDescription("");
     }
     AddMenuToMaps(child_menu_item, node);
   }
diff --git a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc
index 3c26617..96ec863 100644
--- a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc
+++ b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.cc
@@ -29,47 +29,16 @@
 
 namespace {
 
-// The left-hand margin used for rows.
-static constexpr int kMarginLeft = 4;
-
-// TODO(dschuyler): Perhaps this should be based on the font size
-// instead of hardcoded to 2 dp (e.g. by adding a space in an
-// appropriate font to the beginning of the description, then reducing
-// the additional padding here to zero).
-static constexpr int kAnswerIconToTextPadding = 2;
-
 // The edge length of the layout image area.
 static constexpr int kImageBoxSize = 40;
 
-// The diameter of the new answer layout images.
-static constexpr int kNewAnswerImageSize = 24;
+// The diameter of the answer layout images.
+static constexpr int kAnswerImageSize = 24;
 
 // The edge length of the entity suggestions images.
 static constexpr int kEntityImageSize = 32;
 static constexpr int kEntityImageCornerRadius = 4;
 
-// The margin height of a one-line suggestion row.
-static constexpr int kOneLineRowMarginHeight = 8;
-
-// The margin height of a two-line suggestion row.
-static constexpr int kTwoLineRowMarginHeight = 4;
-
-// Returns the padding width between elements.
-int HorizontalPadding() {
-  return GetLayoutConstant(LOCATION_BAR_ELEMENT_PADDING) +
-         GetLayoutInsets(LOCATION_BAR_ICON_INTERIOR_PADDING).width() / 2;
-}
-
-// Returns the margins that should appear around the result.
-// |is_two_line| indicates whether the vertical margin is for a type of
-// suggestion that uses two lines (e.g. answers).
-gfx::Insets GetMarginInsets(int text_height, bool is_two_line) {
-  int vertical_margin =
-      is_two_line ? kTwoLineRowMarginHeight : kOneLineRowMarginHeight;
-  return gfx::Insets(vertical_margin, kMarginLeft, vertical_margin,
-                     OmniboxMatchCellView::kMarginRight);
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // PlaceholderImageSource:
 
@@ -211,8 +180,6 @@
   // Decide layout style once before Layout, while match data is available.
   if (is_rich_suggestion_ || match.ShouldShowTabMatchButton() || match.pedal) {
     layout_style_ = LayoutStyle::TWO_LINE_SUGGESTION;
-  } else if (!!match.answer) {
-    layout_style_ = LayoutStyle::OLD_ANSWER;
   } else {
     layout_style_ = LayoutStyle::ONE_LINE_SUGGESTION;
   }
@@ -233,13 +200,11 @@
     const auto& icon = gfx::CreateVectorIcon(vector_icon, SK_ColorWHITE);
     answer_image_view_->SetImage(
         gfx::CanvasImageSource::MakeImageSkia<EncircledImageSource>(
-            kNewAnswerImageSize / 2, gfx::kGoogleBlue600, icon));
+            kAnswerImageSize / 2, gfx::kGoogleBlue600, icon));
   };
   if (match.type == AutocompleteMatchType::CALCULATOR) {
     apply_vector_icon(omnibox::kAnswerCalculatorIcon);
   } else if (!is_rich_suggestion_) {
-    // An old style answer entry may use the answer_image_view_. But
-    // it's set when the image arrives (later).
     answer_image_view_->SetImage(gfx::ImageSkia());
     answer_image_view_->SetSize(gfx::Size());
   } else {
@@ -274,7 +239,7 @@
       // Always set the image size so that downloaded images get the correct
       // size (such as Weather answers).
       answer_image_view_->SetImageSize(
-          gfx::Size(kNewAnswerImageSize, kNewAnswerImageSize));
+          gfx::Size(kAnswerImageSize, kAnswerImageSize));
     } else {
       SkColor color = result_view->GetColor(OmniboxPart::RESULTS_BACKGROUND);
       extensions::image_util::ParseHexColorString(match.image_dominant_color,
@@ -314,30 +279,25 @@
   return "OmniboxMatchCellView";
 }
 
-void OmniboxMatchCellView::Layout() {
-  // Update the margins. Avoid re-creating the border if the insets haven't
-  // changed, because SetBorder invalidates the layout.
-  gfx::Insets insets =
-      GetMarginInsets(content()->GetLineHeight(),
-                      layout_style_ != LayoutStyle::ONE_LINE_SUGGESTION);
-  if (insets != GetInsets())
-    SetBorder(views::CreateEmptyBorder(insets));
+gfx::Insets OmniboxMatchCellView::GetInsets() const {
+  const bool single_line = layout_style_ == LayoutStyle::ONE_LINE_SUGGESTION;
+  const int vertical_margin = single_line ? 8 : 4;
+  return gfx::Insets(vertical_margin, 4, vertical_margin,
+                     OmniboxMatchCellView::kMarginRight);
+}
 
-  // Layout children *after* updating the margins.
+void OmniboxMatchCellView::Layout() {
   views::View::Layout();
 
   const int icon_view_width = kImageBoxSize;
   const int text_indent = GetTextIndent();
   switch (layout_style_) {
-    case LayoutStyle::OLD_ANSWER:
-      LayoutOldStyleAnswer(icon_view_width, text_indent);
-      break;
     case LayoutStyle::ONE_LINE_SUGGESTION:
       LayoutOneLineSuggestion(icon_view_width,
                               text_indent + tail_suggest_common_prefix_width_);
       break;
     case LayoutStyle::TWO_LINE_SUGGESTION:
-      LayoutNewStyleTwoLineSuggestion();
+      LayoutTwoLineSuggestion();
       break;
   }
 }
@@ -349,19 +309,6 @@
 gfx::Size OmniboxMatchCellView::CalculatePreferredSize() const {
   int height = 0;
   switch (layout_style_) {
-    case LayoutStyle::OLD_ANSWER: {
-      int icon_width = icon_view_->width();
-      int answer_image_size =
-          answer_image_view_->GetImage().isNull()
-              ? 0
-              : answer_image_view_->height() + kAnswerIconToTextPadding;
-      int deduction =
-          icon_width + (HorizontalPadding() * 3) + answer_image_size;
-      int description_width = std::max(width() - deduction, 0);
-      height = content_view_->GetLineHeight() +
-               description_view_->GetHeightForWidth(description_width);
-      break;
-    }
     case LayoutStyle::ONE_LINE_SUGGESTION: {
       height = content_view_->GetLineHeight();
       break;
@@ -377,34 +324,7 @@
   return gfx::Size(0, height);
 }
 
-void OmniboxMatchCellView::LayoutOldStyleAnswer(int icon_view_width,
-                                                int text_indent) {
-  // TODO(dschuyler): Remove this layout once rich layouts are enabled by
-  // default.
-  gfx::Rect child_area = GetContentsBounds();
-  const int text_height = content_view_->GetLineHeight();
-  int x = child_area.x();
-  int y = child_area.y();
-  icon_view_->SetBounds(x, y, icon_view_width, text_height);
-  x += text_indent;
-  content_view_->SetBounds(x, y, width() - x, text_height);
-  y += text_height;
-  if (!answer_image_view_->GetImage().isNull()) {
-    constexpr int kImageEdgeLength = 24;
-    constexpr int kImagePadding = 2;
-    answer_image_view_->SetBounds(x, y + kImagePadding, kImageEdgeLength,
-                                  kImageEdgeLength);
-    answer_image_view_->SetImageSize(
-        gfx::Size(kImageEdgeLength, kImageEdgeLength));
-    x += answer_image_view_->width() + kAnswerIconToTextPadding;
-  }
-  int description_width = width() - x;
-  description_view_->SetBounds(
-      x, y, description_width,
-      description_view_->GetHeightForWidth(description_width));
-}
-
-void OmniboxMatchCellView::LayoutNewStyleTwoLineSuggestion() {
+void OmniboxMatchCellView::LayoutTwoLineSuggestion() {
   gfx::Rect child_area = GetContentsBounds();
   int x = child_area.x();
   int y = child_area.y();
diff --git a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h
index fe2c286..3333c73 100644
--- a/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h
+++ b/chrome/browser/ui/views/omnibox/omnibox_match_cell_view.h
@@ -40,19 +40,18 @@
 
   // views::View:
   const char* GetClassName() const override;
+  gfx::Insets GetInsets() const override;
   void Layout() override;
   bool CanProcessEventsWithinSubtree() const override;
   gfx::Size CalculatePreferredSize() const override;
 
  private:
   enum class LayoutStyle {
-    OLD_ANSWER,
     ONE_LINE_SUGGESTION,
     TWO_LINE_SUGGESTION,
   };
 
-  void LayoutOldStyleAnswer(int icon_view_width, int text_indent);
-  void LayoutNewStyleTwoLineSuggestion();
+  void LayoutTwoLineSuggestion();
   void LayoutOneLineSuggestion(int icon_view_width, int text_indent);
   void SetTailSuggestCommonPrefixWidth(const base::string16& common_prefix);
 
diff --git a/chrome/browser/ui/views/profiles/profile_menu_view.cc b/chrome/browser/ui/views/profiles/profile_menu_view.cc
index 77c75998..c5856b7 100644
--- a/chrome/browser/ui/views/profiles/profile_menu_view.cc
+++ b/chrome/browser/ui/views/profiles/profile_menu_view.cc
@@ -61,6 +61,7 @@
 
 // Helpers --------------------------------------------------------------------
 
+constexpr float kShortcutIconToImageRatio = 9.0 / 16.0;
 
 // Number of times the Dice sign-in promo illustration should be shown.
 constexpr int kDiceSigninPromoIllustrationShowCountMax = 10;
@@ -413,18 +414,19 @@
 
 void ProfileMenuView::BuildAutofillButtons() {
   AddShortcutFeatureButton(
-      kKeyIcon, l10n_util::GetStringUTF16(IDS_PROFILES_PASSWORDS_LINK),
+      ImageForMenu(kKeyIcon, kShortcutIconToImageRatio),
+      l10n_util::GetStringUTF16(IDS_PROFILES_PASSWORDS_LINK),
       base::BindRepeating(&ProfileMenuView::OnPasswordsButtonClicked,
                           base::Unretained(this)));
 
   AddShortcutFeatureButton(
-      kCreditCardIcon,
+      ImageForMenu(kCreditCardIcon, kShortcutIconToImageRatio),
       l10n_util::GetStringUTF16(IDS_PROFILES_CREDIT_CARDS_LINK),
       base::BindRepeating(&ProfileMenuView::OnCreditCardsButtonClicked,
                           base::Unretained(this)));
 
   AddShortcutFeatureButton(
-      vector_icons::kLocationOnIcon,
+      ImageForMenu(vector_icons::kLocationOnIcon, kShortcutIconToImageRatio),
       l10n_util::GetStringUTF16(IDS_PROFILES_ADDRESSES_LINK),
       base::BindRepeating(&ProfileMenuView::OnAddressesButtonClicked,
                           base::Unretained(this)));
@@ -512,7 +514,7 @@
 
 void ProfileMenuView::BuildProfileFeatureButtons() {
   AddProfileShortcutFeatureButton(
-      ImageForMenu(vector_icons::kSettingsIcon, /*icon_to_image_ratio=*/0.625),
+      ImageForMenu(vector_icons::kSettingsIcon, kShortcutIconToImageRatio),
       l10n_util::GetStringUTF16(IDS_PROFILES_MANAGE_USERS_BUTTON),
       base::BindRepeating(&ProfileMenuView::OnManageProfilesButtonClicked,
                           base::Unretained(this)));
diff --git a/chrome/browser/ui/views/profiles/profile_menu_view_base.cc b/chrome/browser/ui/views/profiles/profile_menu_view_base.cc
index 9ebc915..6a0a207 100644
--- a/chrome/browser/ui/views/profiles/profile_menu_view_base.cc
+++ b/chrome/browser/ui/views/profiles/profile_menu_view_base.cc
@@ -35,6 +35,7 @@
 #include "ui/views/controls/separator.h"
 #include "ui/views/controls/styled_label.h"
 #include "ui/views/layout/fill_layout.h"
+#include "ui/views/view_class_properties.h"
 
 #if !defined(OS_CHROMEOS)
 #include "chrome/browser/ui/views/profiles/profile_menu_view.h"
@@ -60,6 +61,16 @@
 // the menu items.
 constexpr int kMenuEdgeMargin = 16;
 
+SkColor GetDefaultIconColor() {
+  return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
+      ui::NativeTheme::kColorId_DefaultIconColor);
+}
+
+SkColor GetDefaultSeparatorColor() {
+  return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
+      ui::NativeTheme::kColorId_MenuSeparatorColor);
+}
+
 gfx::ImageSkia SizeImage(const gfx::ImageSkia& image, int size) {
   return gfx::ImageSkiaOperations::CreateResizedImage(
       image, skia::ImageOperations::RESIZE_BEST, gfx::Size(size, size));
@@ -81,9 +92,6 @@
 std::unique_ptr<views::View> CreateBorderedBoxView(
     std::unique_ptr<views::View> children_container) {
   constexpr int kBorderThickness = 1;
-  const SkColor kBorderColor =
-      ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
-          ui::NativeTheme::kColorId_MenuSeparatorColor);
 
   // Add rounded rectangular border around children.
   children_container->SetLayoutManager(std::make_unique<views::BoxLayout>(
@@ -91,7 +99,7 @@
   children_container->SetBorder(views::CreateRoundedRectBorder(
       kBorderThickness,
       views::LayoutProvider::Get()->GetCornerRadiusMetric(views::EMPHASIS_HIGH),
-      kBorderColor));
+      GetDefaultSeparatorColor()));
 
   // Create outer view with margin.
   // The outer view is needed because |BoxLayout| doesn't support outer
@@ -105,6 +113,33 @@
   return outer_view;
 }
 
+std::unique_ptr<views::Button> CreateCircularImageButton(
+    views::ButtonListener* listener,
+    const gfx::ImageSkia& image,
+    const base::string16& text,
+    bool show_border = false) {
+  constexpr int kImageSize = 28;
+  const int kBorderThickness = show_border ? 1 : 0;
+  const SkScalar kButtonRadius = (kImageSize + 2 * kBorderThickness) / 2.0;
+
+  auto button = std::make_unique<views::ImageButton>(listener);
+  button->SetImage(views::Button::STATE_NORMAL, SizeImage(image, kImageSize));
+  button->SetTooltipText(text);
+  button->SetInkDropMode(views::Button::InkDropMode::ON);
+  button->SetFocusForPlatform();
+  button->set_ink_drop_base_color(GetDefaultIconColor());
+  if (show_border) {
+    button->SetBorder(views::CreateRoundedRectBorder(
+        kBorderThickness, kButtonRadius, GetDefaultSeparatorColor()));
+  }
+  // Set circular highlight path.
+  auto path = std::make_unique<SkPath>();
+  path->addCircle(kButtonRadius, kButtonRadius, kButtonRadius);
+  button->SetProperty(views::kHighlightPathKey, path.release());
+
+  return button;
+}
+
 }  // namespace
 
 // MenuItems--------------------------------------------------------------------
@@ -265,21 +300,11 @@
 }
 
 void ProfileMenuViewBase::AddShortcutFeatureButton(
-    const gfx::VectorIcon& icon,
+    const gfx::ImageSkia& icon,
     const base::string16& text,
     base::RepeatingClosure action) {
   constexpr auto kMargins = gfx::Insets(8, 0);
   constexpr int kButtonSpacing = 6;
-  constexpr int kIconSize = 16;
-  constexpr int kIconPadding = 6;
-  const SkColor kIconColor =
-      ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
-          ui::NativeTheme::kColorId_DefaultIconColor);
-  const SkColor kBorderColor =
-      ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
-          ui::NativeTheme::kColorId_MenuSeparatorColor);
-  constexpr int kBorderThickness = 1;
-  constexpr int kButtonRadius = kIconSize / 2 + kIconPadding;
 
   // Initialize layout if this is the first time a button is added.
   if (!shortcut_features_container_->GetLayoutManager()) {
@@ -291,17 +316,8 @@
         views::BoxLayout::MainAxisAlignment::kCenter);
   }
 
-  // Add icon button with tooltip text(shown on hover).
-  views::Button* button =
-      shortcut_features_container_->AddChildView(std::make_unique<HoverButton>(
-          this, gfx::CreateVectorIcon(icon, kIconSize, kIconColor),
-          base::string16()));
-  button->SetTooltipText(text);
-  // Specify circular border with inside padding.
-  auto circular_border = views::CreateRoundedRectBorder(
-      kBorderThickness, kButtonRadius, kBorderColor);
-  button->SetBorder(views::CreatePaddedBorder(std::move(circular_border),
-                                              gfx::Insets(kIconPadding)));
+  views::Button* button = shortcut_features_container_->AddChildView(
+      CreateCircularImageButton(this, icon, text, /*show_border=*/true));
 
   RegisterClickAction(button, std::move(action));
 }
@@ -311,9 +327,6 @@
     const base::string16& text,
     base::RepeatingClosure action) {
   constexpr int kIconSize = 16;
-  const SkColor kIconColor =
-      ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
-          ui::NativeTheme::kColorId_DefaultIconColor);
 
   // Initialize layout if this is the first time a button is added.
   if (!account_features_container_->GetLayoutManager()) {
@@ -327,7 +340,8 @@
 
   views::Button* button =
       account_features_container_->AddChildView(std::make_unique<HoverButton>(
-          this, SizeImage(ColorImage(icon, kIconColor), kIconSize), text));
+          this, SizeImage(ColorImage(icon, GetDefaultIconColor()), kIconSize),
+          text));
 
   RegisterClickAction(button, std::move(action));
 }
@@ -371,8 +385,6 @@
     const gfx::ImageSkia& icon,
     const base::string16& text,
     base::RepeatingClosure action) {
-  constexpr int kIconSize = 28;
-
   // Initialize layout if this is the first time a button is added.
   if (!profile_shortcut_features_container_->GetLayoutManager()) {
     profile_shortcut_features_container_->SetLayoutManager(
@@ -382,10 +394,7 @@
   }
 
   views::Button* button = profile_shortcut_features_container_->AddChildView(
-      std::make_unique<HoverButton>(this, SizeImage(icon, kIconSize),
-                                    base::string16()));
-  button->SetTooltipText(text);
-  button->SetBorder(nullptr);
+      CreateCircularImageButton(this, icon, text));
 
   RegisterClickAction(button, std::move(action));
 }
@@ -411,14 +420,11 @@
 
 gfx::ImageSkia ProfileMenuViewBase::ImageForMenu(const gfx::VectorIcon& icon,
                                                  float icon_to_image_ratio) {
-  const SkColor kIconColor =
-      ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
-          ui::NativeTheme::kColorId_DefaultIconColor);
   const int padding =
       static_cast<int>(kMaxImageSize * (1.0 - icon_to_image_ratio) / 2.0);
 
-  auto sized_icon =
-      gfx::CreateVectorIcon(icon, kMaxImageSize - 2 * padding, kIconColor);
+  auto sized_icon = gfx::CreateVectorIcon(icon, kMaxImageSize - 2 * padding,
+                                          GetDefaultIconColor());
   return gfx::CanvasImageSource::CreatePadded(sized_icon, gfx::Insets(padding));
 }
 
@@ -822,10 +828,7 @@
 
 gfx::ImageSkia ProfileMenuViewBase::CreateVectorIcon(
     const gfx::VectorIcon& icon) {
-  return gfx::CreateVectorIcon(
-      icon, kIconSize,
-      ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor(
-          ui::NativeTheme::kColorId_DefaultIconColor));
+  return gfx::CreateVectorIcon(icon, kIconSize, GetDefaultIconColor());
 }
 
 int ProfileMenuViewBase::GetDefaultIconSize() {
diff --git a/chrome/browser/ui/views/profiles/profile_menu_view_base.h b/chrome/browser/ui/views/profiles/profile_menu_view_base.h
index 1418c7dd..f9dc49f1 100644
--- a/chrome/browser/ui/views/profiles/profile_menu_view_base.h
+++ b/chrome/browser/ui/views/profiles/profile_menu_view_base.h
@@ -101,7 +101,7 @@
   void SetSyncInfo(const base::string16& description,
                    const base::string16& link_text,
                    base::RepeatingClosure action);
-  void AddShortcutFeatureButton(const gfx::VectorIcon& icon,
+  void AddShortcutFeatureButton(const gfx::ImageSkia& icon,
                                 const base::string16& text,
                                 base::RepeatingClosure action);
   void AddAccountFeatureButton(const gfx::ImageSkia& icon,
diff --git a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc
index 34d5991a..93c68e6c 100644
--- a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc
+++ b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc
@@ -509,6 +509,12 @@
     ++hover_cards_seen_count_;
 }
 
+ax::mojom::Role TabHoverCardBubbleView::GetAccessibleWindowRole() {
+  // Override the role so that hover cards are not read when they appear because
+  // tabs handle accessibility text.
+  return ax::mojom::Role::kIgnored;
+}
+
 int TabHoverCardBubbleView::GetDialogButtons() const {
   return ui::DIALOG_BUTTON_NONE;
 }
diff --git a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h
index e43d4cf..f8e81dd 100644
--- a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h
+++ b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h
@@ -55,6 +55,7 @@
 
   // BubbleDialogDelegateView:
   void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override;
+  ax::mojom::Role GetAccessibleWindowRole() override;
   int GetDialogButtons() const override;
 
   void set_last_mouse_exit_timestamp(
diff --git a/chrome/browser/ui/views/tabs/tab_hover_interactive_uitest.cc b/chrome/browser/ui/views/tabs/tab_hover_interactive_uitest.cc
index f8e1c36..0912ee1 100644
--- a/chrome/browser/ui/views/tabs/tab_hover_interactive_uitest.cc
+++ b/chrome/browser/ui/views/tabs/tab_hover_interactive_uitest.cc
@@ -70,15 +70,9 @@
 
  private:
   std::vector<std::string> GetUMAHistogramNames() const override {
-    // Report each step in the Pipeline Reporter. Note that the UMA mean
-    // will only be printed if the following command line flag is provided:
-    // --perf-test-print-uma-means. Each measurement is in microseconds.
-    return {
-        "SingleThreadedCompositorLatency.BeginImplFrameToSendBeginMainFrame",
-        "SingleThreadedCompositorLatency.SendBeginMainFrameToCommit",
-        "SingleThreadedCompositorLatency.Commit",
-        "SingleThreadedCompositorLatency.EndCommitToActivation",
-        "SingleThreadedCompositorLatency.EndActivateToSubmitCompositorFrame"};
+    // This used to report the different stages from the pipline, but they have
+    // been removed for the UI compositor. Details in crbug.com/1005226
+    return {};
   }
 
   base::test::ScopedFeatureList scoped_feature_list_;
diff --git a/chrome/browser/ui/views/tabs/tab_spinner_interactive_uitest.cc b/chrome/browser/ui/views/tabs/tab_spinner_interactive_uitest.cc
index bd64362..4aaab49b 100644
--- a/chrome/browser/ui/views/tabs/tab_spinner_interactive_uitest.cc
+++ b/chrome/browser/ui/views/tabs/tab_spinner_interactive_uitest.cc
@@ -44,14 +44,9 @@
 
  private:
   std::vector<std::string> GetUMAHistogramNames() const override {
-    // Report each step in the Pipeline Reporter. Note that the UMA mean
-    // will only be printed if the following command line flag is provided:
-    // --perf-test-print-uma-means. Each measurement is in microseconds.
-    return {"SingleThreadedCompositorLatency.TotalLatency",
-            "SingleThreadedCompositorLatency.SendBeginMainFrameToCommit",
-            "SingleThreadedCompositorLatency.Commit",
-            "SingleThreadedCompositorLatency.Activation",
-            "SingleThreadedCompositorLatency.EndCommitToActivation"};
+    // This used to report the different stages from the pipline, but they have
+    // been removed for the UI compositor. Details in crbug.com/1005226
+    return {};
   }
 
   base::test::ScopedFeatureList scoped_feature_list_;
diff --git a/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.cc b/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.cc
index b6d37a7..fb566149 100644
--- a/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.cc
+++ b/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.cc
@@ -19,10 +19,5 @@
 AuthenticatorTransportSelectorSheetView::BuildStepSpecificContent() {
   return std::make_unique<HoverListView>(
       std::make_unique<TransportHoverListModel>(
-          model()->dialog_model()->available_transports(), this));
-}
-
-void AuthenticatorTransportSelectorSheetView::OnItemSelected(
-    AuthenticatorTransport transport) {
-  model()->OnTransportSelected(transport);
+          model()->dialog_model()->available_transports(), model()));
 }
diff --git a/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.h b/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.h
index 5662134b..bfa4d7c 100644
--- a/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.h
+++ b/chrome/browser/ui/views/webauthn/authenticator_transport_selector_sheet_view.h
@@ -18,8 +18,7 @@
 // user to pick the transport protocol over which they wish to use their
 // security key.
 class AuthenticatorTransportSelectorSheetView
-    : public AuthenticatorRequestSheetView,
-      public TransportHoverListModel::Delegate {
+    : public AuthenticatorRequestSheetView {
  public:
   explicit AuthenticatorTransportSelectorSheetView(
       std::unique_ptr<AuthenticatorTransportSelectorSheetModel> model);
@@ -34,9 +33,6 @@
   // AuthenticatorRequestSheetView:
   std::unique_ptr<views::View> BuildStepSpecificContent() override;
 
-  // TransportHoverListModel::Delegate:
-  void OnItemSelected(AuthenticatorTransport transport) override;
-
   DISALLOW_COPY_AND_ASSIGN(AuthenticatorTransportSelectorSheetView);
 };
 
diff --git a/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc b/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc
index 3cfbd46..d25d208 100644
--- a/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc
+++ b/chrome/browser/ui/webauthn/authenticator_dialog_browsertest.cc
@@ -40,6 +40,7 @@
         AuthenticatorTransport::kInternal,
         AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy};
     model->set_cable_transport_info(/*cable_extension_provided=*/true,
+                                    /*have_paired_phones=*/false,
                                     device::CableDiscoveryData::NewQRKey());
     model->StartFlow(std::move(transport_availability), base::nullopt, nullptr);
 
diff --git a/chrome/browser/ui/webauthn/sheet_models.cc b/chrome/browser/ui/webauthn/sheet_models.cc
index 35c6356..5ce75c6f 100644
--- a/chrome/browser/ui/webauthn/sheet_models.cc
+++ b/chrome/browser/ui/webauthn/sheet_models.cc
@@ -151,6 +151,10 @@
   dialog_model()->StartGuidedFlowForTransport(transport);
 }
 
+void AuthenticatorTransportSelectorSheetModel::StartPhonePairing() {
+  dialog_model()->StartPhonePairing();
+}
+
 // AuthenticatorInsertAndActivateUsbSheetModel ----------------------
 
 AuthenticatorInsertAndActivateUsbSheetModel::
@@ -1198,18 +1202,14 @@
 
 const gfx::VectorIcon& AuthenticatorQRSheetModel::GetStepIllustration(
     ImageColorScheme color_scheme) const {
-  return color_scheme == ImageColorScheme::kDark ? kWebauthnPermissionDarkIcon
-                                                 : kWebauthnPermissionIcon;
+  return color_scheme == ImageColorScheme::kDark ? kWebauthnPhoneDarkIcon
+                                                 : kWebauthnPhoneIcon;
 }
 
 base::string16 AuthenticatorQRSheetModel::GetStepTitle() const {
-  // TODO: this UI is not yet reachable, but will need a translated string
-  // once it is.
-  return base::UTF8ToUTF16("Title");
+  return l10n_util::GetStringUTF16(IDS_WEBAUTHN_CABLE_QR_TITLE);
 }
 
 base::string16 AuthenticatorQRSheetModel::GetStepDescription() const {
-  // TODO: this UI is not yet reachable, but will need a translated string
-  // once it is.
-  return base::UTF8ToUTF16("Description");
+  return l10n_util::GetStringUTF16(IDS_WEBAUTHN_CABLE_QR_DESCRIPTION);
 }
diff --git a/chrome/browser/ui/webauthn/sheet_models.h b/chrome/browser/ui/webauthn/sheet_models.h
index 4ce5b5f..2f83518c 100644
--- a/chrome/browser/ui/webauthn/sheet_models.h
+++ b/chrome/browser/ui/webauthn/sheet_models.h
@@ -10,6 +10,7 @@
 #include "base/macros.h"
 #include "base/strings/string16.h"
 #include "chrome/browser/ui/webauthn/authenticator_request_sheet_model.h"
+#include "chrome/browser/ui/webauthn/transport_hover_list_model.h"
 #include "chrome/browser/webauthn/authenticator_request_dialog_model.h"
 
 namespace gfx {
@@ -63,13 +64,14 @@
 // The sheet shown for selecting the transport over which the security key
 // should be accessed.
 class AuthenticatorTransportSelectorSheetModel
-    : public AuthenticatorSheetModelBase {
+    : public AuthenticatorSheetModelBase,
+      public TransportHoverListModel::Delegate {
  public:
   using AuthenticatorSheetModelBase::AuthenticatorSheetModelBase;
 
-  // Initiates the step-by-step flow with the the transport at the given |index|
-  // selected by the user.
-  void OnTransportSelected(AuthenticatorTransport transport);
+  // TransportHoverListModel::Delegate:
+  void OnTransportSelected(AuthenticatorTransport transport) override;
+  void StartPhonePairing() override;
 
  private:
   // AuthenticatorSheetModelBase:
diff --git a/chrome/browser/ui/webauthn/transport_hover_list_model.cc b/chrome/browser/ui/webauthn/transport_hover_list_model.cc
index 6007530b..873e96d 100644
--- a/chrome/browser/ui/webauthn/transport_hover_list_model.cc
+++ b/chrome/browser/ui/webauthn/transport_hover_list_model.cc
@@ -6,9 +6,23 @@
 
 #include <utility>
 
+#include "chrome/app/vector_icons/vector_icons.h"
 #include "chrome/browser/ui/webauthn/transport_utils.h"
+#include "chrome/grit/generated_resources.h"
+#include "device/fido/features.h"
+#include "ui/base/l10n/l10n_util.h"
 #include "ui/gfx/paint_vector_icon.h"
 
+namespace {
+// The tag ID space consists of the union of |AuthenticatorTransport| values
+// with the extra values defined below. These extra values must not overlap with
+// any values of |AuthenticatorTransport|.
+
+constexpr int kTagExtraBase = 1 << 16;
+// Command ID for triggering QR flow.
+constexpr int kPairPhoneTag = kTagExtraBase + 0;
+}  // namespace
+
 TransportHoverListModel::TransportHoverListModel(
     std::vector<AuthenticatorTransport> transport_list,
     Delegate* delegate)
@@ -33,10 +47,18 @@
   std::transform(
       transport_list_.begin(), transport_list_.end(), tag_list.begin(),
       [](const auto& transport) { return base::strict_cast<int>(transport); });
+
+  if (base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport)) {
+    tag_list.push_back(kPairPhoneTag);
+  }
   return tag_list;
 }
 
 base::string16 TransportHoverListModel::GetItemText(int item_tag) const {
+  if (item_tag == kPairPhoneTag) {
+    return l10n_util::GetStringUTF16(IDS_WEBAUTHN_TRANSPORT_POPUP_PAIR_PHONE);
+  }
+
   return GetTransportHumanReadableName(
       static_cast<AuthenticatorTransport>(item_tag),
       TransportSelectionContext::kTransportSelectionSheet);
@@ -48,16 +70,28 @@
 
 const gfx::VectorIcon* TransportHoverListModel::GetItemIcon(
     int item_tag) const {
+  if (item_tag == kPairPhoneTag) {
+    return &kSmartphoneIcon;
+  }
   return GetTransportVectorIcon(static_cast<AuthenticatorTransport>(item_tag));
 }
 
 void TransportHoverListModel::OnListItemSelected(int item_tag) {
-  if (delegate_)
-    delegate_->OnItemSelected(static_cast<AuthenticatorTransport>(item_tag));
+  if (!delegate_) {
+    return;
+  }
+
+  if (item_tag == kPairPhoneTag) {
+    delegate_->StartPhonePairing();
+    return;
+  }
+
+  delegate_->OnTransportSelected(static_cast<AuthenticatorTransport>(item_tag));
 }
 
 size_t TransportHoverListModel::GetPreferredItemCount() const {
-  return transport_list_.size();
+  return transport_list_.size() + static_cast<int>(base::FeatureList::IsEnabled(
+                                      device::kWebAuthPhoneSupport));
 }
 
 bool TransportHoverListModel::StyleForTwoLines() const {
diff --git a/chrome/browser/ui/webauthn/transport_hover_list_model.h b/chrome/browser/ui/webauthn/transport_hover_list_model.h
index 0ad10e9..2c1f88b 100644
--- a/chrome/browser/ui/webauthn/transport_hover_list_model.h
+++ b/chrome/browser/ui/webauthn/transport_hover_list_model.h
@@ -18,7 +18,10 @@
   // views that observe the model.
   class Delegate {
    public:
-    virtual void OnItemSelected(AuthenticatorTransport transport) = 0;
+    // Called when the given |transport| is selected by the user.
+    virtual void OnTransportSelected(AuthenticatorTransport transport) = 0;
+    // Called when the user selects the item to pair a new phone.
+    virtual void StartPhonePairing() = 0;
   };
 
   explicit TransportHoverListModel(
diff --git a/chrome/browser/ui/webui/app_management/app_management.mojom b/chrome/browser/ui/webui/app_management/app_management.mojom
index c62180b..512730e3 100644
--- a/chrome/browser/ui/webui/app_management/app_management.mojom
+++ b/chrome/browser/ui/webui/app_management/app_management.mojom
@@ -35,7 +35,8 @@
 };
 
 interface PageHandlerFactory {
-  CreatePageHandler(Page page, PageHandler& handler);
+  CreatePageHandler(pending_remote<Page> page,
+                    pending_receiver<PageHandler> handler);
 };
 
 // Browser interface.
diff --git a/chrome/browser/ui/webui/app_management/app_management_page_handler.cc b/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
index 13638978..4eece17 100644
--- a/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
+++ b/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
@@ -14,6 +14,7 @@
 #include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
 #include "chrome/browser/extensions/extension_service.h"
 #include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/app_management/app_management.mojom.h"
 #include "chrome/services/app_service/public/cpp/app_registry_cache.h"
 #include "chrome/services/app_service/public/mojom/types.mojom.h"
 #include "extensions/browser/extension_registry.h"
@@ -21,6 +22,10 @@
 #include "extensions/common/extension.h"
 #include "extensions/common/permissions/permission_message.h"
 #include "extensions/common/permissions/permissions_data.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
+#include "mojo/public/cpp/bindings/remote.h"
 
 #if defined(OS_CHROMEOS)
 #include "chrome/browser/chromeos/arc/arc_util.h"
@@ -82,10 +87,10 @@
 }  // namespace
 
 AppManagementPageHandler::AppManagementPageHandler(
-    app_management::mojom::PageHandlerRequest request,
-    app_management::mojom::PagePtr page,
+    mojo::PendingReceiver<app_management::mojom::PageHandler> receiver,
+    mojo::PendingRemote<app_management::mojom::Page> page,
     Profile* profile)
-    : binding_(this, std::move(request)),
+    : receiver_(this, std::move(receiver)),
       page_(std::move(page)),
       profile_(profile)
 #if defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/webui/app_management/app_management_page_handler.h b/chrome/browser/ui/webui/app_management/app_management_page_handler.h
index baeef29..10fa404 100644
--- a/chrome/browser/ui/webui/app_management/app_management_page_handler.h
+++ b/chrome/browser/ui/webui/app_management/app_management_page_handler.h
@@ -10,7 +10,10 @@
 #include "chrome/browser/ui/webui/app_management/app_management.mojom.h"
 #include "chrome/browser/ui/webui/app_management/app_management_shelf_delegate_chromeos.h"
 #include "chrome/services/app_service/public/cpp/app_registry_cache.h"
-#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
+#include "mojo/public/cpp/bindings/remote.h"
 
 #if defined(OS_CHROMEOS)
 #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
@@ -26,9 +29,10 @@
 #endif  // OS_CHROMEOS
 {
  public:
-  AppManagementPageHandler(app_management::mojom::PageHandlerRequest request,
-                           app_management::mojom::PagePtr page,
-                           Profile* profile);
+  AppManagementPageHandler(
+      mojo::PendingReceiver<app_management::mojom::PageHandler> receiver,
+      mojo::PendingRemote<app_management::mojom::Page> page,
+      Profile* profile);
   ~AppManagementPageHandler() override;
 
 #if defined(OS_CHROMEOS)
@@ -68,9 +72,9 @@
       const arc::mojom::ArcPackageInfo& package_info) override;
 #endif  // OS_CHROMEOS
 
-  mojo::Binding<app_management::mojom::PageHandler> binding_;
+  mojo::Receiver<app_management::mojom::PageHandler> receiver_;
 
-  app_management::mojom::PagePtr page_;
+  mojo::Remote<app_management::mojom::Page> page_;
 
   Profile* profile_;
 
diff --git a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc
index f648d2f7..be46394c 100644
--- a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc
+++ b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.cc
@@ -14,8 +14,8 @@
 namespace machine_learning {
 
 MachineLearningInternalsPageHandler::MachineLearningInternalsPageHandler(
-    mojom::PageHandlerRequest request)
-    : binding_(this, std::move(request)) {}
+    mojo::PendingReceiver<mojom::PageHandler> receiver)
+    : receiver_(this, std::move(receiver)) {}
 
 MachineLearningInternalsPageHandler::~MachineLearningInternalsPageHandler() =
     default;
diff --git a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h
index afa6d61..f0059447 100644
--- a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h
+++ b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.h
@@ -9,7 +9,8 @@
 #include "chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.mojom.h"
 #include "chromeos/services/machine_learning/public/mojom/machine_learning_service.mojom.h"
 #include "chromeos/services/machine_learning/public/mojom/model.mojom.h"
-#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 
 namespace chromeos {
 namespace machine_learning {
@@ -19,7 +20,7 @@
 class MachineLearningInternalsPageHandler : public mojom::PageHandler {
  public:
   explicit MachineLearningInternalsPageHandler(
-      mojom::PageHandlerRequest request);
+      mojo::PendingReceiver<mojom::PageHandler> receiver);
   ~MachineLearningInternalsPageHandler() override;
 
  private:
@@ -28,7 +29,7 @@
                  mojom::ModelRequest request,
                  LoadModelCallback callback) override;
 
-  mojo::Binding<mojom::PageHandler> binding_;
+  mojo::Receiver<mojom::PageHandler> receiver_;
 
   DISALLOW_COPY_AND_ASSIGN(MachineLearningInternalsPageHandler);
 };
diff --git a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc
index 09f00e14..18ff22f 100644
--- a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc
+++ b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.cc
@@ -4,6 +4,7 @@
 
 #include "chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.h"
 
+#include <memory>
 #include <utility>
 
 #include "chrome/browser/profiles/profile.h"
@@ -56,9 +57,9 @@
 MachineLearningInternalsUI::~MachineLearningInternalsUI() = default;
 
 void MachineLearningInternalsUI::BindMachineLearningInternalsPageHandler(
-    mojom::PageHandlerRequest request) {
-  page_handler_.reset(
-      new MachineLearningInternalsPageHandler(std::move(request)));
+    mojo::PendingReceiver<mojom::PageHandler> receiver) {
+  page_handler_ = std::make_unique<MachineLearningInternalsPageHandler>(
+      std::move(receiver));
 }
 
 }  // namespace machine_learning
diff --git a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.h b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.h
index 38517641..da44a73 100644
--- a/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.h
+++ b/chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_ui.h
@@ -9,6 +9,7 @@
 
 #include "base/macros.h"
 #include "chrome/browser/ui/webui/chromeos/machine_learning/machine_learning_internals_page_handler.mojom.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
 #include "ui/webui/mojo_web_ui_controller.h"
 
 namespace chromeos {
@@ -24,7 +25,7 @@
 
  private:
   void BindMachineLearningInternalsPageHandler(
-      mojom::PageHandlerRequest request);
+      mojo::PendingReceiver<mojom::PageHandler> receiver);
 
   std::unique_ptr<MachineLearningInternalsPageHandler> page_handler_;
 
diff --git a/chrome/browser/ui/webui/reset_password/reset_password_ui.cc b/chrome/browser/ui/webui/reset_password/reset_password_ui.cc
index b4b7b46..e6293d9e 100644
--- a/chrome/browser/ui/webui/reset_password/reset_password_ui.cc
+++ b/chrome/browser/ui/webui/reset_password/reset_password_ui.cc
@@ -4,10 +4,14 @@
 
 #include "chrome/browser/ui/webui/reset_password/reset_password_ui.h"
 
+#include <memory>
+#include <utility>
+
 #include "base/bind.h"
 #include "base/metrics/histogram_macros.h"
 #include "base/strings/utf_string_conversions.h"
 #include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/reset_password/reset_password.mojom.h"
 #include "chrome/common/url_constants.h"
 #include "chrome/grit/browser_resources.h"
 #include "components/safe_browsing/common/safe_browsing_prefs.h"
@@ -21,7 +25,7 @@
 #include "content/public/browser/navigation_entry.h"
 #include "content/public/browser/web_contents.h"
 #include "content/public/browser/web_ui_data_source.h"
-#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 #include "ui/base/l10n/l10n_util.h"
 
 using safe_browsing::LoginReputationClientResponse;
@@ -46,9 +50,8 @@
  public:
   ResetPasswordHandlerImpl(
       content::WebContents* web_contents,
-      mojo::InterfaceRequest<mojom::ResetPasswordHandler> request)
-      : web_contents_(web_contents),
-        binding_(this, std::move(request)) {
+      mojo::PendingReceiver<mojom::ResetPasswordHandler> receiver)
+      : web_contents_(web_contents), receiver_(this, std::move(receiver)) {
     DCHECK(web_contents);
   }
 
@@ -73,7 +76,7 @@
 
  private:
   content::WebContents* web_contents_;
-  mojo::Binding<mojom::ResetPasswordHandler> binding_;
+  mojo::Receiver<mojom::ResetPasswordHandler> receiver_;
 
   DISALLOW_COPY_AND_ASSIGN(ResetPasswordHandlerImpl);
 };
@@ -126,9 +129,9 @@
 ResetPasswordUI::~ResetPasswordUI() {}
 
 void ResetPasswordUI::BindResetPasswordHandler(
-    mojom::ResetPasswordHandlerRequest request) {
+    mojo::PendingReceiver<mojom::ResetPasswordHandler> receiver) {
   ui_handler_ = std::make_unique<ResetPasswordHandlerImpl>(
-      web_ui()->GetWebContents(), std::move(request));
+      web_ui()->GetWebContents(), std::move(receiver));
 }
 
 base::DictionaryValue ResetPasswordUI::PopulateStrings() const {
diff --git a/chrome/browser/ui/webui/reset_password/reset_password_ui.h b/chrome/browser/ui/webui/reset_password/reset_password_ui.h
index 8712c13..3bd3946 100644
--- a/chrome/browser/ui/webui/reset_password/reset_password_ui.h
+++ b/chrome/browser/ui/webui/reset_password/reset_password_ui.h
@@ -9,6 +9,7 @@
 #include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
 #include "chrome/browser/ui/webui/reset_password/reset_password.mojom.h"
 #include "components/password_manager/core/browser/password_manager_metrics_util.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
 #include "ui/webui/mojo_web_ui_controller.h"
 
 namespace base {
@@ -24,7 +25,8 @@
   ~ResetPasswordUI() override;
 
  private:
-  void BindResetPasswordHandler(mojom::ResetPasswordHandlerRequest request);
+  void BindResetPasswordHandler(
+      mojo::PendingReceiver<mojom::ResetPasswordHandler> receiver);
 
   base::DictionaryValue PopulateStrings() const;
 
diff --git a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc b/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc
index 8b3abcc..7a9cb17 100644
--- a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc
+++ b/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.cc
@@ -11,6 +11,7 @@
 #include "base/feature_list.h"
 #include "chrome/browser/apps/app_service/app_icon_source.h"
 #include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/webui/app_management/app_management.mojom.h"
 #include "chrome/browser/ui/webui/app_management/app_management_page_handler.h"
 #include "chrome/grit/browser_resources.h"
 #include "chrome/grit/chromium_strings.h"
@@ -19,37 +20,29 @@
 #include "content/public/browser/url_data_source.h"
 #include "content/public/browser/web_ui.h"
 #include "content/public/browser/web_ui_data_source.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 #include "ui/base/resource/resource_bundle.h"
 
 AppManagementPageHandlerFactory::AppManagementPageHandlerFactory(
     Profile* profile)
-    : page_factory_binding_(this), profile_(profile) {}
+    : profile_(profile) {}
 
 AppManagementPageHandlerFactory::~AppManagementPageHandlerFactory() = default;
 
 void AppManagementPageHandlerFactory::Bind(
-    app_management::mojom::PageHandlerFactoryRequest request) {
-  if (page_factory_binding_.is_bound()) {
-    page_factory_binding_.Unbind();
-  }
+    mojo::PendingReceiver<app_management::mojom::PageHandlerFactory> receiver) {
+  page_factory_receiver_.reset();
 
-  page_factory_binding_.Bind(std::move(request));
-}
-
-void AppManagementPageHandlerFactory::BindPageHandlerFactory(
-    app_management::mojom::PageHandlerFactoryRequest request) {
-  if (page_factory_binding_.is_bound()) {
-    page_factory_binding_.Unbind();
-  }
-
-  page_factory_binding_.Bind(std::move(request));
+  page_factory_receiver_.Bind(std::move(receiver));
 }
 
 void AppManagementPageHandlerFactory::CreatePageHandler(
-    app_management::mojom::PagePtr page,
-    app_management::mojom::PageHandlerRequest request) {
+    mojo::PendingRemote<app_management::mojom::Page> page,
+    mojo::PendingReceiver<app_management::mojom::PageHandler> receiver) {
   DCHECK(page);
 
   page_handler_ = std::make_unique<AppManagementPageHandler>(
-      std::move(request), std::move(page), profile_);
+      std::move(receiver), std::move(page), profile_);
 }
diff --git a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h b/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h
index 3779071f..ca3d617 100644
--- a/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h
+++ b/chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h
@@ -9,7 +9,9 @@
 
 #include "base/macros.h"
 #include "chrome/browser/ui/webui/app_management/app_management.mojom.h"
-#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 
 class Profile;
 
@@ -21,21 +23,20 @@
   explicit AppManagementPageHandlerFactory(Profile* profile);
   ~AppManagementPageHandlerFactory() override;
 
-  void Bind(app_management::mojom::PageHandlerFactoryRequest request);
+  void Bind(mojo::PendingReceiver<app_management::mojom::PageHandlerFactory>
+                receiver);
 
  private:
-  void BindPageHandlerFactory(
-      app_management::mojom::PageHandlerFactoryRequest request);
-
   // app_management::mojom::PageHandlerFactory:
   void CreatePageHandler(
-      app_management::mojom::PagePtr page,
-      app_management::mojom::PageHandlerRequest request) override;
+      mojo::PendingRemote<app_management::mojom::Page> page,
+      mojo::PendingReceiver<app_management::mojom::PageHandler> receiver)
+      override;
 
   std::unique_ptr<AppManagementPageHandler> page_handler_;
 
-  mojo::Binding<app_management::mojom::PageHandlerFactory>
-      page_factory_binding_;
+  mojo::Receiver<app_management::mojom::PageHandlerFactory>
+      page_factory_receiver_{this};
 
   Profile* profile_;
 
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc
index a8e024f..8740d7a 100644
--- a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc
+++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.cc
@@ -50,6 +50,7 @@
 #include "components/password_manager/core/common/password_manager_features.h"
 #include "components/unified_consent/feature.h"
 #include "content/public/browser/web_ui_data_source.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
 
 namespace chromeos {
 namespace settings {
@@ -190,13 +191,13 @@
 }
 
 void OSSettingsUI::BindAppManagementPageHandlerFactory(
-    app_management::mojom::PageHandlerFactoryRequest request) {
+    mojo::PendingReceiver<app_management::mojom::PageHandlerFactory> receiver) {
   if (!app_management_page_handler_factory_) {
     app_management_page_handler_factory_ =
         std::make_unique<AppManagementPageHandlerFactory>(
             Profile::FromWebUI(web_ui()));
   }
-  app_management_page_handler_factory_->Bind(std::move(request));
+  app_management_page_handler_factory_->Bind(std::move(receiver));
 }
 
 }  // namespace settings
diff --git a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
index 63131cf..f029a415c 100644
--- a/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
+++ b/chrome/browser/ui/webui/settings/chromeos/os_settings_ui.h
@@ -12,6 +12,7 @@
 #include "chrome/browser/ui/webui/settings/chromeos/app_management/app_management_page_handler_factory.h"
 #include "chrome/browser/ui/webui/webui_load_timer.h"
 #include "chromeos/services/network_config/public/mojom/cros_network_config.mojom-forward.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
 #include "ui/webui/mojo_web_ui_controller.h"
 
 namespace content {
@@ -33,7 +34,8 @@
   void BindCrosNetworkConfig(
       network_config::mojom::CrosNetworkConfigRequest request);
   void BindAppManagementPageHandlerFactory(
-      app_management::mojom::PageHandlerFactoryRequest request);
+      mojo::PendingReceiver<app_management::mojom::PageHandlerFactory>
+          receiver);
 
   WebuiLoadTimer webui_load_timer_;
 
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
index 5233515..c006d1ef 100644
--- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
+++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -1861,6 +1861,10 @@
     {"removeAccountLabel", IDS_SETTINGS_ACCOUNT_MANAGER_REMOVE_ACCOUNT_LABEL},
     {"accountManagerPrimaryAccountTooltip",
      IDS_SETTINGS_ACCOUNT_MANAGER_PRIMARY_ACCOUNT_TOOLTIP},
+    {"accountManagerSecondaryAccountsDisabledText",
+     IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_TEXT},
+    {"accountManagerSecondaryAccountsDisabledChildText",
+     IDS_SETTINGS_ACCOUNT_MANAGER_SECONDARY_ACCOUNTS_DISABLED_CHILD_TEXT},
     {"accountManagerSignedOutAccountName",
      IDS_SETTINGS_ACCOUNT_MANAGER_SIGNED_OUT_ACCOUNT_PLACEHOLDER},
     {"accountManagerUnmigratedAccountName",
diff --git a/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc b/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc
index be07aad..7f44dd8e 100644
--- a/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc
+++ b/chrome/browser/ui/webui/supervised_user_internals_message_handler.cc
@@ -193,8 +193,6 @@
   std::unique_ptr<base::ListValue> section_list(new base::ListValue);
 
   base::ListValue* section_general = AddSection(section_list.get(), "General");
-  AddSectionEntry(section_general, "Chrome version",
-                  chrome::GetVersionString());
   AddSectionEntry(section_general, "Child detection enabled",
                   ChildAccountService::IsChildAccountDetectionEnabled());
 
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.cc b/chrome/browser/webauthn/authenticator_request_dialog_model.cc
index efd9413..ad72ee0 100644
--- a/chrome/browser/webauthn/authenticator_request_dialog_model.cc
+++ b/chrome/browser/webauthn/authenticator_request_dialog_model.cc
@@ -31,7 +31,8 @@
     const device::FidoRequestHandlerBase::TransportAvailabilityInfo&
         transport_availability,
     base::Optional<device::FidoTransportProtocol> last_used_transport,
-    bool cable_extension_provided) {
+    bool cable_extension_provided,
+    bool have_paired_phones) {
   base::flat_set<AuthenticatorTransport> candidate_transports(
       transport_availability.available_transports);
 
@@ -64,7 +65,10 @@
           device::FidoRequestHandlerBase::RequestType::kGetAssertion &&
       last_used_transport &&
       base::Contains(candidate_transports, *last_used_transport) &&
-      *last_used_transport != device::FidoTransportProtocol::kInternal) {
+      *last_used_transport != device::FidoTransportProtocol::kInternal &&
+      (have_paired_phones ||
+       *last_used_transport !=
+           device::FidoTransportProtocol::kCloudAssistedBluetoothLowEnergy)) {
     return *last_used_transport;
   }
 
@@ -117,6 +121,10 @@
   transport_availability_ = std::move(transport_availability);
   last_used_transport_ = last_used_transport;
   for (const auto transport : transport_availability_.available_transports) {
+    if (transport == AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy &&
+        !cable_extension_provided_ && !have_paired_phones_) {
+      continue;
+    }
     available_transports_.emplace_back(transport);
   }
 
@@ -158,8 +166,9 @@
     return;
   }
 
-  auto most_likely_transport = SelectMostLikelyTransport(
-      transport_availability_, last_used_transport_, cable_extension_provided_);
+  auto most_likely_transport =
+      SelectMostLikelyTransport(transport_availability_, last_used_transport_,
+                                cable_extension_provided_, have_paired_phones_);
   if (most_likely_transport) {
     StartGuidedFlowForTransport(*most_likely_transport);
   } else if (!transport_availability_.available_transports.empty()) {
@@ -198,9 +207,7 @@
       break;
     }
     case AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy:
-      DCHECK(cable_extension_provided_ || qr_generator_key_.has_value());
-      EnsureBleAdapterIsPoweredBeforeContinuingWithStep(
-          cable_extension_provided_ ? Step::kCableActivate : Step::kQRCode);
+      EnsureBleAdapterIsPoweredBeforeContinuingWithStep(Step::kCableActivate);
       break;
     default:
       break;
@@ -229,6 +236,11 @@
   HideDialog();
 }
 
+void AuthenticatorRequestDialogModel::StartPhonePairing() {
+  DCHECK(qr_generator_key_);
+  EnsureBleAdapterIsPoweredBeforeContinuingWithStep(Step::kQRCode);
+}
+
 void AuthenticatorRequestDialogModel::
     EnsureBleAdapterIsPoweredBeforeContinuingWithStep(Step next_step) {
   DCHECK(current_step() == Step::kTransportSelection ||
@@ -647,7 +659,9 @@
 
 void AuthenticatorRequestDialogModel::set_cable_transport_info(
     bool cable_extension_provided,
+    bool have_paired_phones,
     base::Optional<device::QRGeneratorKey> qr_generator_key) {
   cable_extension_provided_ = cable_extension_provided;
+  have_paired_phones_ = have_paired_phones;
   qr_generator_key_ = std::move(qr_generator_key);
 }
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.h b/chrome/browser/webauthn/authenticator_request_dialog_model.h
index 1e35120f..96fb1a5f 100644
--- a/chrome/browser/webauthn/authenticator_request_dialog_model.h
+++ b/chrome/browser/webauthn/authenticator_request_dialog_model.h
@@ -209,6 +209,10 @@
   // UI instead.
   void HideDialogAndDispatchToNativeWindowsApi();
 
+  // StartPhonePairing triggers the display of a QR code for pairing a new
+  // phone.
+  void StartPhonePairing();
+
   // Ensures that the Bluetooth adapter is powered before proceeding to |step|.
   //  -- If the adapter is powered, advanced directly to |step|.
   //  -- If the adapter is not powered, but Chrome can turn it automatically,
@@ -427,6 +431,7 @@
 
   void set_cable_transport_info(
       bool cable_extension_provided,
+      bool has_paired_phones,
       base::Optional<device::QRGeneratorKey> qr_generator_key);
 
   const std::string& relying_party_id() const { return relying_party_id_; }
@@ -514,6 +519,9 @@
   // cable_extension_provided_ indicates whether the request included a caBLE
   // extension.
   bool cable_extension_provided_ = false;
+  // have_paired_phones_ indicates whether this profile knows of any paired
+  // phones.
+  bool have_paired_phones_ = false;
   base::Optional<device::QRGeneratorKey> qr_generator_key_;
 
   base::WeakPtrFactory<AuthenticatorRequestDialogModel> weak_factory_{this};
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc
index 2ba197e..eac0d0f 100644
--- a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc
+++ b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc
@@ -321,7 +321,7 @@
 
     if (base::Contains(test_case.transport_params,
                        TransportAvailabilityParam::kHasCableExtension)) {
-      model.set_cable_transport_info(true, base::nullopt);
+      model.set_cable_transport_info(true, false, base::nullopt);
     }
 
     model.StartFlow(std::move(transports_info), test_case.last_used_transport,
@@ -337,19 +337,38 @@
 }
 
 TEST_F(AuthenticatorRequestDialogModelTest, TransportList) {
-  TransportAvailabilityInfo transports_info;
-  transports_info.available_transports = kAllTransports;
+  for (const bool cable_extension_provided : {false, true}) {
+    for (const bool have_paired_phones : {false, true}) {
+      TransportAvailabilityInfo transports_info;
+      transports_info.available_transports = kAllTransports;
+      AuthenticatorRequestDialogModel model(/*relying_party_id=*/"example.com");
+      model.set_cable_transport_info(cable_extension_provided,
+                                     have_paired_phones,
+                                     /*qr_generator_key=*/base::nullopt);
+      model.StartFlow(std::move(transports_info), base::nullopt,
+                      &test_paired_device_list_);
 
-  AuthenticatorRequestDialogModel model(/*relying_party_id=*/"example.com");
-  model.StartFlow(std::move(transports_info), base::nullopt,
-                  &test_paired_device_list_);
-  EXPECT_THAT(model.available_transports(),
-              ::testing::UnorderedElementsAre(
-                  AuthenticatorTransport::kUsbHumanInterfaceDevice,
-                  AuthenticatorTransport::kNearFieldCommunication,
-                  AuthenticatorTransport::kBluetoothLowEnergy,
-                  AuthenticatorTransport::kInternal,
-                  AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy));
+      const bool should_include_cable =
+          cable_extension_provided || have_paired_phones;
+      if (should_include_cable) {
+        EXPECT_THAT(
+            model.available_transports(),
+            ::testing::UnorderedElementsAre(
+                AuthenticatorTransport::kUsbHumanInterfaceDevice,
+                AuthenticatorTransport::kNearFieldCommunication,
+                AuthenticatorTransport::kBluetoothLowEnergy,
+                AuthenticatorTransport::kInternal,
+                AuthenticatorTransport::kCloudAssistedBluetoothLowEnergy));
+      } else {
+        EXPECT_THAT(model.available_transports(),
+                    ::testing::UnorderedElementsAre(
+                        AuthenticatorTransport::kUsbHumanInterfaceDevice,
+                        AuthenticatorTransport::kNearFieldCommunication,
+                        AuthenticatorTransport::kBluetoothLowEnergy,
+                        AuthenticatorTransport::kInternal));
+      }
+    }
+  }
 }
 
 TEST_F(AuthenticatorRequestDialogModelTest, NoAvailableTransports) {
@@ -498,7 +517,7 @@
     BluetoothAdapterPowerOnCallbackReceiver power_receiver;
     AuthenticatorRequestDialogModel model(/*relying_party_id=*/"example.com");
     model.SetBluetoothAdapterPowerOnCallback(power_receiver.GetCallback());
-    model.set_cable_transport_info(true, base::nullopt);
+    model.set_cable_transport_info(true, false, base::nullopt);
     model.StartFlow(std::move(transports_info), base::nullopt,
                     &test_paired_device_list_);
     EXPECT_EQ(test_case.expected_final_step, model.current_step());
@@ -528,7 +547,7 @@
     AuthenticatorRequestDialogModel model(/*relying_party_id=*/"example.com");
     model.AddObserver(&mock_observer);
     model.SetBluetoothAdapterPowerOnCallback(power_receiver.GetCallback());
-    model.set_cable_transport_info(true, base::nullopt);
+    model.set_cable_transport_info(true, false, base::nullopt);
     model.StartFlow(std::move(transports_info), base::nullopt,
                     &test_paired_device_list_);
 
@@ -569,7 +588,7 @@
     BluetoothAdapterPowerOnCallbackReceiver power_receiver;
     AuthenticatorRequestDialogModel model(/*relying_party_id=*/"example.com");
     model.SetBluetoothAdapterPowerOnCallback(power_receiver.GetCallback());
-    model.set_cable_transport_info(true, base::nullopt);
+    model.set_cable_transport_info(true, false, base::nullopt);
     model.StartFlow(std::move(transports_info), base::nullopt,
                     &test_paired_device_list_);
 
diff --git a/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc b/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc
index 7d9452c..bf40df0 100644
--- a/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc
+++ b/chrome/browser/webauthn/chrome_authenticator_request_delegate.cc
@@ -290,8 +290,10 @@
 
 bool ChromeAuthenticatorRequestDelegate::SetCableTransportInfo(
     bool cable_extension_provided,
+    bool have_paired_phones,
     base::Optional<device::QRGeneratorKey> qr_generator_key) {
   weak_dialog_model_->set_cable_transport_info(cable_extension_provided,
+                                               have_paired_phones,
                                                std::move(qr_generator_key));
   return true;
 }
@@ -547,11 +549,12 @@
   std::move(cancel_callback_).Run();
 }
 
-void ChromeAuthenticatorRequestDelegate::AppendCablePairings(
-    std::vector<device::CableDiscoveryData>* pairings) {
+std::vector<device::CableDiscoveryData>
+ChromeAuthenticatorRequestDelegate::GetCablePairings() {
+  std::vector<device::CableDiscoveryData> ret;
   if (!base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport)) {
     NOTREACHED();
-    return;
+    return ret;
   }
 
   PrefService* prefs =
@@ -578,8 +581,10 @@
       continue;
     }
 
-    pairings->push_back(discovery);
+    ret.push_back(discovery);
   }
+
+  return ret;
 }
 
 void ChromeAuthenticatorRequestDelegate::AddFidoBleDeviceToPairedList(
diff --git a/chrome/browser/webauthn/chrome_authenticator_request_delegate.h b/chrome/browser/webauthn/chrome_authenticator_request_delegate.h
index 80c8ac648..fed6105 100644
--- a/chrome/browser/webauthn/chrome_authenticator_request_delegate.h
+++ b/chrome/browser/webauthn/chrome_authenticator_request_delegate.h
@@ -80,9 +80,9 @@
   bool ShouldPermitCableExtension(const url::Origin& origin) override;
   bool SetCableTransportInfo(
       bool cable_extension_provided,
+      bool has_paired_phones,
       base::Optional<device::QRGeneratorKey> qr_generator_key) override;
-  void AppendCablePairings(
-      std::vector<device::CableDiscoveryData>* pairings) override;
+  std::vector<device::CableDiscoveryData> GetCablePairings() override;
   void SelectAccount(
       std::vector<device::AuthenticatorGetAssertionResponse> responses,
       base::OnceCallback<void(device::AuthenticatorGetAssertionResponse)>
diff --git a/chrome/chrome_cleaner/test/resources/resource_ids b/chrome/chrome_cleaner/test/resources/resource_ids
index 0a146d4..a2d777e 100644
--- a/chrome/chrome_cleaner/test/resources/resource_ids
+++ b/chrome/chrome_cleaner/test/resources/resource_ids
@@ -17,7 +17,4 @@
   "chrome/chrome_cleaner/test/resources/test_resources.grd": {
     "includes": [9000],
   },
-  "chrome/chrome_cleaner/test/resources/test_strings.grd": {
-    "messages": [9500],
-  },
 }
diff --git a/chrome/common/chrome_paths.cc b/chrome/common/chrome_paths.cc
index a7542ef6..5407cea 100644
--- a/chrome/common/chrome_paths.cc
+++ b/chrome/common/chrome_paths.cc
@@ -424,17 +424,6 @@
         return false;
       cur = cur.Append(FILE_PATH_LITERAL("custom_wallpapers"));
       break;
-    case chrome::FILE_CHROMEOS_CROSTINI_ANSIBLE_SOFTWARE_CONFIG:
-      if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
-        return false;
-      cur = cur.Append(FILE_PATH_LITERAL("ansible_software_config.json"));
-      break;
-    case chrome::DIR_CHROMEOS_CROSTINI_ANSIBLE_PLAYBOOK_STAGING:
-      if (!base::PathService::Get(chrome::DIR_USER_DATA, &cur))
-        return false;
-      cur = cur.Append(FILE_PATH_LITERAL("ansible_playbook_staging"));
-      create_dir = true;
-      break;
 #endif
 #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
     case chrome::DIR_SUPERVISED_USER_INSTALLED_WHITELISTS:
diff --git a/chrome/common/chrome_paths.h b/chrome/common/chrome_paths.h
index e554d78..3258b62e 100644
--- a/chrome/common/chrome_paths.h
+++ b/chrome/common/chrome_paths.h
@@ -108,13 +108,6 @@
                                       // wallpaper thumbnails reside.
   DIR_CHROMEOS_CUSTOM_WALLPAPERS,     // Directory where custom wallpapers
                                       // reside.
-  // Managed Crostini deployments.
-  FILE_CHROMEOS_CROSTINI_ANSIBLE_SOFTWARE_CONFIG,  // A file with JSON
-                                                   // configuration for Ansible
-                                                   // package management.
-  DIR_CHROMEOS_CROSTINI_ANSIBLE_PLAYBOOK_STAGING,  // Directory where Ansible
-                                                   // playbooks pending
-                                                   // execution reside.
 #endif
   DIR_SUPERVISED_USER_INSTALLED_WHITELISTS,  // Directory where sanitized
                                              // supervised user whitelists are
diff --git a/chrome/renderer/searchbox/searchbox_extension.cc b/chrome/renderer/searchbox/searchbox_extension.cc
index 21aa5fe..81bce09 100644
--- a/chrome/renderer/searchbox/searchbox_extension.cc
+++ b/chrome/renderer/searchbox/searchbox_extension.cc
@@ -539,7 +539,6 @@
       v8::Isolate* isolate) final;
 
   // Handlers for JS properties.
-  static bool GetRightToLeft();
   static bool IsFocused();
   static bool IsKeyCaptureEnabled();
 
@@ -562,7 +561,7 @@
 gin::ObjectTemplateBuilder SearchBoxBindings::GetObjectTemplateBuilder(
     v8::Isolate* isolate) {
   return gin::Wrappable<SearchBoxBindings>::GetObjectTemplateBuilder(isolate)
-      .SetProperty("rtl", &SearchBoxBindings::GetRightToLeft)
+      .SetProperty("rtl", &base::i18n::IsRTL)
       .SetProperty("isFocused", &SearchBoxBindings::IsFocused)
       .SetProperty("isKeyCaptureEnabled",
                    &SearchBoxBindings::IsKeyCaptureEnabled)
@@ -575,10 +574,6 @@
                  &SearchBoxBindings::StopCapturingKeyStrokes);
 }
 
-bool SearchBoxBindings::GetRightToLeft() {
-  return base::i18n::IsRTL();
-}
-
 // static
 bool SearchBoxBindings::IsFocused() {
   const SearchBox* search_box = GetSearchBoxForCurrentContext();
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn
index a2daf85..41d87b0 100644
--- a/chrome/test/BUILD.gn
+++ b/chrome/test/BUILD.gn
@@ -57,6 +57,7 @@
   data = [
     "$root_out_dir/pyproto/components/policy/proto/device_management_backend_pb2.py",
     "$root_out_dir/pyproto/components/policy/proto/cloud_policy_pb2.py",
+    "$root_out_dir/pyproto/components/policy/proto/policy_common_definitions_pb2.py",
   ]
 
   if (!is_android) {
diff --git a/chrome/test/data/local_ntp/local_ntp_browsertest.js b/chrome/test/data/local_ntp/local_ntp_browsertest.js
index 63a6249..41de080 100644
--- a/chrome/test/data/local_ntp/local_ntp_browsertest.js
+++ b/chrome/test/data/local_ntp/local_ntp_browsertest.js
@@ -271,7 +271,7 @@
   let promo = document.createElement('div');
   promo.id = IDS.PROMO;
   promo.innerHTML = 'test';
-  promo.classList.add('show-element');
+  promo.style.visibility = 'visible';
   $('ntp-contents').appendChild(promo);
 }
 
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json
index 12f6da1..a58a8f51 100644
--- a/chrome/test/data/policy/policy_test_cases.json
+++ b/chrome/test/data/policy/policy_test_cases.json
@@ -4027,9 +4027,15 @@
   "DeviceLoginScreenDefaultSpokenFeedbackEnabled" : {
   },
 
+  "DeviceLoginScreenSpokenFeedbackEnabled" : {
+  },
+
   "DeviceLoginScreenDefaultHighContrastEnabled" : {
   },
 
+  "DeviceLoginScreenHighContrastEnabled" : {
+  },
+
   "DeviceLoginScreenDefaultScreenMagnifierType" : {
   },
 
diff --git a/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js b/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js
index 63368ca..18a0095 100644
--- a/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js
+++ b/chrome/test/data/webui/settings/chromeos/people_page_account_manager_test.js
@@ -153,7 +153,7 @@
 
     test('AddAccount', function() {
       assertFalse(accountManager.$$('#add-account-button').disabled);
-      assertTrue(accountManager.$$('cr-policy-indicator').hidden);
+      assertTrue(accountManager.$$('#settings-box-user-message').hidden);
       accountManager.$$('#add-account-button').click();
       assertEquals(1, browserProxy.getCallCount('addAccount'));
     });
@@ -269,7 +269,8 @@
     let accountList = null;
 
     suiteSetup(function() {
-      loadTimeData.overrideValues({secondaryGoogleAccountSigninAllowed: false});
+      loadTimeData.overrideValues(
+          {secondaryGoogleAccountSigninAllowed: false, isChild: false});
     });
 
     setup(function() {
@@ -291,7 +292,48 @@
 
     test('AddAccountCanBeDisabledByPolicy', function() {
       assertTrue(accountManager.$$('#add-account-button').disabled);
-      assertFalse(accountManager.$$('cr-policy-indicator').hidden);
+      assertFalse(accountManager.$$('#settings-box-user-message').hidden);
+    });
+
+    test('UserMessageSetForAccountType', function() {
+      assertEquals(
+          loadTimeData.getString('accountManagerSecondaryAccountsDisabledText'),
+          accountManager.$$('#user-message-text').textContent.trim());
+    });
+  });
+
+  suite('AccountManagerAccountAdditionDisabledChildAccountTests', function() {
+    let browserProxy = null;
+    let accountManager = null;
+    let accountList = null;
+
+    suiteSetup(function() {
+      loadTimeData.overrideValues(
+          {secondaryGoogleAccountSigninAllowed: false, isChild: true});
+    });
+
+    setup(function() {
+      browserProxy = new TestAccountManagerBrowserProxy();
+      settings.AccountManagerBrowserProxyImpl.instance_ = browserProxy;
+      PolymerTest.clearBody();
+
+      accountManager = document.createElement('settings-account-manager');
+      document.body.appendChild(accountManager);
+      accountList = accountManager.$$('#account-list');
+      assertTrue(!!accountList);
+
+      settings.navigateTo(settings.routes.ACCOUNT_MANAGER);
+    });
+
+    teardown(function() {
+      accountManager.remove();
+    });
+
+    test('UserMessageSetForAccountType', function() {
+      assertEquals(
+          loadTimeData.getString(
+              'accountManagerSecondaryAccountsDisabledChildText'),
+          accountManager.$$('#user-message-text').textContent.trim());
     });
   });
 });
diff --git a/chromecast/media/cma/backend/fuchsia/BUILD.gn b/chromecast/media/cma/backend/fuchsia/BUILD.gn
index 6340d47..040b05a 100644
--- a/chromecast/media/cma/backend/fuchsia/BUILD.gn
+++ b/chromecast/media/cma/backend/fuchsia/BUILD.gn
@@ -41,6 +41,7 @@
     "//chromecast/public/media",
     "//media",
     "//third_party/fuchsia-sdk/sdk:media",
+    "//third_party/fuchsia-sdk/sdk:sys_cpp",
   ]
 }
 
diff --git a/chromecast/media/cma/backend/fuchsia/mixer_output_stream_fuchsia.cc b/chromecast/media/cma/backend/fuchsia/mixer_output_stream_fuchsia.cc
index 618acbd9..c249c96 100644
--- a/chromecast/media/cma/backend/fuchsia/mixer_output_stream_fuchsia.cc
+++ b/chromecast/media/cma/backend/fuchsia/mixer_output_stream_fuchsia.cc
@@ -5,10 +5,11 @@
 #include "chromecast/media/cma/backend/fuchsia/mixer_output_stream_fuchsia.h"
 
 #include <fuchsia/media/cpp/fidl.h>
+#include <lib/sys/cpp/component_context.h>
 #include <zircon/syscalls.h>
 
 #include "base/command_line.h"
-#include "base/fuchsia/service_directory_client.h"
+#include "base/fuchsia/default_context.h"
 #include "base/memory/writable_shared_memory_region.h"
 #include "base/time/time.h"
 #include "chromecast/base/chromecast_switches.h"
@@ -53,8 +54,9 @@
 
   // Connect |audio_renderer_|.
   fuchsia::media::AudioPtr audio_server =
-      base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-          ->ConnectToService<fuchsia::media::Audio>();
+      base::fuchsia::ComponentContextForCurrentProcess()
+          ->svc()
+          ->Connect<fuchsia::media::Audio>();
   audio_server->CreateAudioRenderer(audio_renderer_.NewRequest());
   audio_renderer_.set_error_handler(
       [this](zx_status_t status) { this->OnRendererError(status); });
diff --git a/chromeos/dbus/cryptohome/cryptohome_client.cc b/chromeos/dbus/cryptohome/cryptohome_client.cc
index 2c8636b..144dbad 100644
--- a/chromeos/dbus/cryptohome/cryptohome_client.cc
+++ b/chromeos/dbus/cryptohome/cryptohome_client.cc
@@ -1091,6 +1091,12 @@
         base::BindOnce(&CryptohomeClientImpl::OnSignalConnected,
                        weak_ptr_factory_.GetWeakPtr()));
     proxy_->ConnectToSignal(
+        cryptohome::kCryptohomeInterface, cryptohome::kSignalTpmInitStatus,
+        base::Bind(&CryptohomeClientImpl::TpmInitStatusReceived,
+                   weak_ptr_factory_.GetWeakPtr()),
+        base::BindOnce(&CryptohomeClientImpl::OnSignalConnected,
+                       weak_ptr_factory_.GetWeakPtr()));
+    proxy_->ConnectToSignal(
         cryptohome::kCryptohomeInterface, cryptohome::kSignalLowDiskSpace,
         base::Bind(&CryptohomeClientImpl::LowDiskSpaceReceived,
                    weak_ptr_factory_.GetWeakPtr()),
@@ -1339,6 +1345,21 @@
       observer.AsyncCallStatusWithData(async_id, return_status, return_data);
   }
 
+  // Handles TpmInitStatus signal.
+  void TpmInitStatusReceived(dbus::Signal* signal) {
+    dbus::MessageReader reader(signal);
+    bool ready = false;
+    bool owned = false;
+    bool was_owned_this_boot = false;
+    if (!reader.PopBool(&ready) || !reader.PopBool(&owned) ||
+        !reader.PopBool(&was_owned_this_boot)) {
+      LOG(ERROR) << "Invalid signal: " << signal->ToString();
+      return;
+    }
+    for (auto& observer : observer_list_)
+      observer.TpmInitStatusUpdated(ready, owned, was_owned_this_boot);
+  }
+
   // Handles LowDiskSpace signal.
   void LowDiskSpaceReceived(dbus::Signal* signal) {
     dbus::MessageReader reader(signal);
diff --git a/chromeos/dbus/cryptohome/cryptohome_client.h b/chromeos/dbus/cryptohome/cryptohome_client.h
index b79253b1..9c5d768 100644
--- a/chromeos/dbus/cryptohome/cryptohome_client.h
+++ b/chromeos/dbus/cryptohome/cryptohome_client.h
@@ -70,6 +70,12 @@
                                          bool return_status,
                                          const std::string& data) {}
 
+    // Called when TpmInitStatus signal is received, when the status of the TPM
+    // initialization is changed.
+    virtual void TpmInitStatusUpdated(bool ready,
+                                      bool owned,
+                                      bool was_owned_this_boot) {}
+
     // Called when LowDiskSpace signal is received, when the cryptohome
     // partition is running out of disk space.
     virtual void LowDiskSpace(uint64_t disk_free_bytes) {}
diff --git a/chromeos/services/machine_learning/public/mojom/model.mojom b/chromeos/services/machine_learning/public/mojom/model.mojom
index a53eb7a3..50df002 100644
--- a/chromeos/services/machine_learning/public/mojom/model.mojom
+++ b/chromeos/services/machine_learning/public/mojom/model.mojom
@@ -32,6 +32,8 @@
   SMART_DIM_20190221 = 3,
   // The Top Cat (20190722) ML model.
   TOP_CAT_20190722 = 4,
+  // The Smart Dim (20190521) ML model.
+  SMART_DIM_20190521 = 5,
 };
 
 // These values are persisted to logs. Entries should not be renumbered and
diff --git a/components/autofill_assistant/browser/actions/autofill_action.cc b/components/autofill_assistant/browser/actions/autofill_action.cc
index 4f67d3f..9fdfa92 100644
--- a/components/autofill_assistant/browser/actions/autofill_action.cc
+++ b/components/autofill_assistant/browser/actions/autofill_action.cc
@@ -72,16 +72,19 @@
   process_action_callback_ = std::move(action_callback);
 
   // Ensure data already selected in a previous action.
+  auto* client_memory = delegate_->GetClientMemory();
   bool has_valid_data =
-      (is_autofill_card_ && delegate_->GetClientMemory()->selected_card()) ||
-      (!is_autofill_card_ &&
-       delegate_->GetClientMemory()->selected_address(name_));
+      (is_autofill_card_ && client_memory->selected_card()) ||
+      (!is_autofill_card_ && client_memory->selected_address(name_));
   if (!has_valid_data) {
     auto* error_info = processed_action_proto_->mutable_status_details()
                            ->mutable_autofill_error_info();
     error_info->set_address_key_requested(name_);
     error_info->set_client_memory_address_key_names(
-        delegate_->GetClientMemory()->GetAllAddressKeyNames());
+        client_memory->GetAllAddressKeyNames());
+    error_info->set_address_pointee_was_null(
+        !client_memory->has_selected_address(name_) ||
+        !client_memory->selected_address(name_));
     EndAction(PRECONDITION_FAILED);
     return;
   }
diff --git a/components/autofill_assistant/browser/actions/autofill_action_unittest.cc b/components/autofill_assistant/browser/actions/autofill_action_unittest.cc
index e2ad48920..6e782ef 100644
--- a/components/autofill_assistant/browser/actions/autofill_action_unittest.cc
+++ b/components/autofill_assistant/browser/actions/autofill_action_unittest.cc
@@ -175,6 +175,7 @@
   EXPECT_EQ(base::JoinString({kAddressName, "one_more"}, ","),
             error_info.client_memory_address_key_names());
   EXPECT_EQ(kAddressName, error_info.address_key_requested());
+  EXPECT_TRUE(error_info.address_pointee_was_null());
 }
 
 TEST_F(AutofillActionTest, ShortWaitForElementVisible) {
diff --git a/components/autofill_assistant/browser/actions/collect_user_data_action.cc b/components/autofill_assistant/browser/actions/collect_user_data_action.cc
index 1a83a32..5bf0d0b 100644
--- a/components/autofill_assistant/browser/actions/collect_user_data_action.cc
+++ b/components/autofill_assistant/browser/actions/collect_user_data_action.cc
@@ -29,6 +29,132 @@
 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
 #include "ui/base/l10n/l10n_util.h"
 
+namespace {
+
+using autofill_assistant::CollectUserDataOptions;
+using autofill_assistant::TermsAndConditionsState;
+bool IsCompleteContact(
+    const autofill::AutofillProfile* profile,
+    const CollectUserDataOptions& collect_user_data_options) {
+  if (!collect_user_data_options.request_payer_name &&
+      !collect_user_data_options.request_payer_email &&
+      !collect_user_data_options.request_payer_phone) {
+    return true;
+  }
+
+  if (!profile) {
+    return false;
+  }
+
+  if (collect_user_data_options.request_payer_name &&
+      profile->GetRawInfo(autofill::NAME_FULL).empty()) {
+    return false;
+  }
+
+  if (collect_user_data_options.request_payer_email &&
+      profile->GetRawInfo(autofill::EMAIL_ADDRESS).empty()) {
+    return false;
+  }
+
+  if (collect_user_data_options.request_payer_phone &&
+      profile->GetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER).empty()) {
+    return false;
+  }
+  return true;
+}
+
+bool IsCompleteAddress(const autofill::AutofillProfile* profile,
+                       bool require_postal_code) {
+  if (!profile) {
+    return false;
+  }
+  auto address_data = autofill::i18n::CreateAddressDataFromAutofillProfile(
+      *profile, base::android::GetDefaultLocaleString());
+  if (!autofill::addressinput::HasAllRequiredFields(*address_data)) {
+    return false;
+  }
+
+  if (require_postal_code && address_data->postal_code.empty()) {
+    return false;
+  }
+
+  return true;
+}
+
+bool IsCompleteBillingAddress(
+    const autofill::AutofillProfile* profile,
+    const CollectUserDataOptions& collect_user_data_options) {
+  return !collect_user_data_options.request_payment_method ||
+         IsCompleteAddress(
+             profile, collect_user_data_options.require_billing_postal_code);
+}
+
+bool IsCompleteShippingAddress(
+    const autofill::AutofillProfile* profile,
+    const CollectUserDataOptions& collect_user_data_options) {
+  return !collect_user_data_options.request_shipping ||
+         IsCompleteAddress(profile, /* require_postal_code = */ false);
+}
+
+bool IsCompleteCreditCard(
+    autofill::PersonalDataManager* personal_data_manager,
+    const autofill::CreditCard* credit_card,
+    const CollectUserDataOptions& collect_user_data_options) {
+  if (!collect_user_data_options.request_payment_method) {
+    return true;
+  }
+
+  if (!credit_card) {
+    return false;
+  }
+
+  if (credit_card->record_type() != autofill::CreditCard::MASKED_SERVER_CARD &&
+      !credit_card->HasValidCardNumber()) {
+    // Can't check validity of masked server card numbers because they are
+    // incomplete until decrypted.
+    return false;
+  }
+
+  if (!credit_card->HasValidExpirationDate() ||
+      credit_card->billing_address_id().empty()) {
+    return false;
+  }
+
+  auto* address_profile = personal_data_manager->GetProfileByGUID(
+      credit_card->billing_address_id());
+  if (!IsCompleteBillingAddress(address_profile, collect_user_data_options)) {
+    return false;
+  }
+
+  std::string basic_card_network =
+      autofill::data_util::GetPaymentRequestData(credit_card->network())
+          .basic_card_issuer_network;
+  if (!collect_user_data_options.supported_basic_card_networks.empty() &&
+      std::find(collect_user_data_options.supported_basic_card_networks.begin(),
+                collect_user_data_options.supported_basic_card_networks.end(),
+                basic_card_network) ==
+          collect_user_data_options.supported_basic_card_networks.end()) {
+    return false;
+  }
+  return true;
+}
+
+bool IsValidLoginChoice(
+    const std::string& choice_identifier,
+    const CollectUserDataOptions& collect_user_data_options) {
+  return !collect_user_data_options.request_login_choice ||
+         !choice_identifier.empty();
+}
+
+bool IsValidTermsChoice(
+    TermsAndConditionsState terms_state,
+    const CollectUserDataOptions& collect_user_data_options) {
+  return collect_user_data_options.accept_terms_and_conditions_text.empty() ||
+         terms_state != TermsAndConditionsState::NOT_SELECTED;
+}
+
+}  // namespace
+
 namespace autofill_assistant {
 
 CollectUserDataAction::LoginDetails::LoginDetails(
@@ -240,31 +366,27 @@
     }
 
     if (collect_user_data.has_contact_details()) {
+      DCHECK(user_data->contact_profile);
       auto contact_details_proto = collect_user_data.contact_details();
-      autofill::AutofillProfile contact_profile;
-      contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_FULL,
-                                 base::UTF8ToUTF16(user_data->payer_name));
-      autofill::data_util::NameParts parts = autofill::data_util::SplitName(
-          base::UTF8ToUTF16(user_data->payer_name));
-      contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_FIRST,
-                                 parts.given);
-      contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_MIDDLE,
-                                 parts.middle);
-      contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_LAST,
-                                 parts.family);
-      contact_profile.SetRawInfo(autofill::ServerFieldType::EMAIL_ADDRESS,
-                                 base::UTF8ToUTF16(user_data->payer_email));
-      contact_profile.SetRawInfo(
-          autofill::ServerFieldType::PHONE_HOME_WHOLE_NUMBER,
-          base::UTF8ToUTF16(user_data->payer_phone));
+
+      if (contact_details_proto.request_payer_name()) {
+        Metrics::RecordPaymentRequestFirstNameOnly(
+            user_data->contact_profile
+                ->GetRawInfo(autofill::ServerFieldType::NAME_LAST)
+                .empty());
+      }
+
+      if (contact_details_proto.request_payer_email()) {
+        processed_action_proto_->mutable_collect_user_data_result()
+            ->set_payer_email(
+                base::UTF16ToUTF8(user_data->contact_profile->GetRawInfo(
+                    autofill::ServerFieldType::EMAIL_ADDRESS)));
+      }
+
       if (!contact_details_proto.contact_details_name().empty()) {
         delegate_->GetClientMemory()->set_selected_address(
             contact_details_proto.contact_details_name(),
-            std::make_unique<autofill::AutofillProfile>(contact_profile));
-      }
-
-      if (contact_details_proto.request_payer_name()) {
-        Metrics::RecordPaymentRequestFirstNameOnly(parts.family.empty());
+            std::move(user_data->contact_profile));
       }
     }
 
@@ -285,8 +407,6 @@
         ->set_is_terms_and_conditions_accepted(
             user_data->terms_and_conditions ==
             TermsAndConditionsState::ACCEPTED);
-    processed_action_proto_->mutable_collect_user_data_result()
-        ->set_payer_email(user_data->payer_email);
   }
 
   EndAction(succeed ? ClientStatus(ACTION_APPLIED)
@@ -428,7 +548,7 @@
       auto completeContactIter = std::find_if(
           profiles.begin(), profiles.end(),
           [&collect_user_data_options](const auto& profile) {
-            return IsCompleteContact(*profile, collect_user_data_options);
+            return IsCompleteContact(profile, collect_user_data_options);
           });
       if (completeContactIter == profiles.end()) {
         return false;
@@ -436,11 +556,12 @@
     }
 
     if (collect_user_data_options.request_shipping) {
-      auto completeAddressIter = std::find_if(
-          profiles.begin(), profiles.end(), [](const auto* profile) {
-            return IsCompleteAddress(*profile,
-                                     /* require_postal_code = */ false);
-          });
+      auto completeAddressIter =
+          std::find_if(profiles.begin(), profiles.end(),
+                       [&collect_user_data_options](const auto* profile) {
+                         return IsCompleteShippingAddress(
+                             profile, collect_user_data_options);
+                       });
       if (completeAddressIter == profiles.end()) {
         return false;
       }
@@ -453,7 +574,7 @@
         credit_cards.begin(), credit_cards.end(),
         [&collect_user_data_options,
          personal_data_manager](const auto* credit_card) {
-          return IsCompleteCreditCard(personal_data_manager, *credit_card,
+          return IsCompleteCreditCard(personal_data_manager, credit_card,
                                       collect_user_data_options);
         });
     if (completeCardIter == credit_cards.end()) {
@@ -466,78 +587,18 @@
   return true;
 }
 
-bool CollectUserDataAction::IsCompleteContact(
-    const autofill::AutofillProfile& profile,
-    const CollectUserDataOptions& collect_user_data_options) {
-  if (collect_user_data_options.request_payer_name &&
-      profile.GetRawInfo(autofill::NAME_FULL).empty()) {
-    return false;
-  }
-
-  if (collect_user_data_options.request_payer_email &&
-      profile.GetRawInfo(autofill::EMAIL_ADDRESS).empty()) {
-    return false;
-  }
-
-  if (collect_user_data_options.request_payer_phone &&
-      profile.GetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER).empty()) {
-    return false;
-  }
-  return true;
-}
-
-bool CollectUserDataAction::IsCompleteAddress(
-    const autofill::AutofillProfile& profile,
-    bool require_postal_code) {
-  auto address_data = autofill::i18n::CreateAddressDataFromAutofillProfile(
-      profile, base::android::GetDefaultLocaleString());
-  if (!autofill::addressinput::HasAllRequiredFields(*address_data)) {
-    return false;
-  }
-
-  if (require_postal_code && address_data->postal_code.empty()) {
-    return false;
-  }
-
-  return true;
-}
-
-bool CollectUserDataAction::IsCompleteCreditCard(
+// static
+bool CollectUserDataAction::IsUserDataComplete(
     autofill::PersonalDataManager* personal_data_manager,
-    const autofill::CreditCard& credit_card,
-    const CollectUserDataOptions& collect_user_data_options) {
-  if (credit_card.record_type() != autofill::CreditCard::MASKED_SERVER_CARD &&
-      !credit_card.HasValidCardNumber()) {
-    // Can't check validity of masked server card numbers because they are
-    // incomplete until decrypted.
-    return false;
-  }
-
-  if (!credit_card.HasValidExpirationDate() ||
-      credit_card.billing_address_id().empty()) {
-    return false;
-  }
-
-  auto* address_profile =
-      personal_data_manager->GetProfileByGUID(credit_card.billing_address_id());
-  if (!address_profile ||
-      !IsCompleteAddress(
-          *address_profile,
-          collect_user_data_options.require_billing_postal_code)) {
-    return false;
-  }
-
-  std::string basic_card_network =
-      autofill::data_util::GetPaymentRequestData(credit_card.network())
-          .basic_card_issuer_network;
-  if (!collect_user_data_options.supported_basic_card_networks.empty() &&
-      std::find(collect_user_data_options.supported_basic_card_networks.begin(),
-                collect_user_data_options.supported_basic_card_networks.end(),
-                basic_card_network) ==
-          collect_user_data_options.supported_basic_card_networks.end()) {
-    return false;
-  }
-  return true;
+    const UserData& user_data,
+    const CollectUserDataOptions& options) {
+  return IsCompleteContact(user_data.contact_profile.get(), options) &&
+         IsCompleteBillingAddress(user_data.billing_address.get(), options) &&
+         IsCompleteShippingAddress(user_data.shipping_address.get(), options) &&
+         IsCompleteCreditCard(personal_data_manager, user_data.card.get(),
+                              options) &&
+         IsValidLoginChoice(user_data.login_choice_identifier, options) &&
+         IsValidTermsChoice(user_data.terms_and_conditions, options);
 }
 
 void CollectUserDataAction::OnPersonalDataChanged() {
diff --git a/components/autofill_assistant/browser/actions/collect_user_data_action.h b/components/autofill_assistant/browser/actions/collect_user_data_action.h
index 1e1a3a5b..b6c9abc5 100644
--- a/components/autofill_assistant/browser/actions/collect_user_data_action.h
+++ b/components/autofill_assistant/browser/actions/collect_user_data_action.h
@@ -32,6 +32,11 @@
   // From autofill::PersonalDataManagerObserver.
   void OnPersonalDataChanged() override;
 
+  static bool IsUserDataComplete(
+      autofill::PersonalDataManager* personal_data_manager,
+      const UserData& user_data,
+      const CollectUserDataOptions& collect_user_data_options);
+
  private:
   struct LoginDetails {
     LoginDetails(bool choose_automatically_if_no_other_options,
@@ -68,15 +73,6 @@
   bool CheckInitialAutofillDataComplete(
       autofill::PersonalDataManager* personal_data_manager,
       const CollectUserDataOptions& collect_user_data_options);
-  static bool IsCompleteContact(
-      const autofill::AutofillProfile& profile,
-      const CollectUserDataOptions& collect_user_data_options);
-  static bool IsCompleteAddress(const autofill::AutofillProfile& profile,
-                                bool require_postal_code);
-  static bool IsCompleteCreditCard(
-      autofill::PersonalDataManager* personal_data_manager,
-      const autofill::CreditCard& credit_card,
-      const CollectUserDataOptions& collect_user_data_options);
 
   bool shown_to_user_ = false;
   bool initially_prefilled = false;
diff --git a/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc b/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc
index f8a444d8..166759c8 100644
--- a/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc
+++ b/components/autofill_assistant/browser/actions/collect_user_data_action_unittest.cc
@@ -25,9 +25,6 @@
 const char kFakePassword[] = "example_password";
 
 const char kMemoryLocation[] = "billing";
-const char kName[] = "John Doe";
-const char kEmail[] = "john@doe.com";
-const char kPhone[] = "+1 234-567-8901";
 }  // namespace
 
 namespace autofill_assistant {
@@ -184,14 +181,27 @@
   contact_details_proto->set_request_payer_email(true);
   contact_details_proto->set_request_payer_phone(true);
 
+  autofill::AutofillProfile contact_profile;
+  contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_FULL,
+                             base::UTF8ToUTF16("Marion Mitchell Morrison"));
+  contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_FIRST,
+                             base::UTF8ToUTF16("Marion"));
+  contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_MIDDLE,
+                             base::UTF8ToUTF16("Mitchell"));
+  contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_LAST,
+                             base::UTF8ToUTF16("Morrison"));
+  contact_profile.SetRawInfo(autofill::ServerFieldType::EMAIL_ADDRESS,
+                             base::UTF8ToUTF16("marion@me.xyz"));
+  contact_profile.SetRawInfo(autofill::ServerFieldType::PHONE_HOME_WHOLE_NUMBER,
+                             base::UTF8ToUTF16("16505678910"));
+
   ON_CALL(mock_action_delegate_, CollectUserData(_, _))
       .WillByDefault(Invoke(
-          [](std::unique_ptr<CollectUserDataOptions> collect_user_data_options,
-             std::unique_ptr<UserData> user_data) {
+          [=](std::unique_ptr<CollectUserDataOptions> collect_user_data_options,
+              std::unique_ptr<UserData> user_data) {
             user_data->succeed = true;
-            user_data->payer_name.assign(kName);
-            user_data->payer_phone.assign(kPhone);
-            user_data->payer_email.assign(kEmail);
+            user_data->contact_profile =
+                std::make_unique<autofill::AutofillProfile>(contact_profile);
             std::move(collect_user_data_options->confirm_callback)
                 .Run(std::move(user_data));
           }));
@@ -201,17 +211,19 @@
                   Property(&ProcessedActionProto::status, ACTION_APPLIED),
                   Property(&ProcessedActionProto::collect_user_data_result,
                            Property(&CollectUserDataResultProto::payer_email,
-                                    kEmail))))));
+                                    "marion@me.xyz"))))));
+
   CollectUserDataAction action(&mock_action_delegate_, action_proto);
   action.ProcessAction(callback_.Get());
 
   EXPECT_EQ(client_memory_.has_selected_address(kMemoryLocation), true);
   auto* profile = client_memory_.selected_address(kMemoryLocation);
-  EXPECT_EQ(profile->GetRawInfo(autofill::NAME_FULL), base::UTF8ToUTF16(kName));
+  EXPECT_EQ(profile->GetRawInfo(autofill::NAME_FULL),
+            base::UTF8ToUTF16("Marion Mitchell Morrison"));
   EXPECT_EQ(profile->GetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER),
-            base::UTF8ToUTF16(kPhone));
+            base::UTF8ToUTF16("16505678910"));
   EXPECT_EQ(profile->GetRawInfo(autofill::EMAIL_ADDRESS),
-            base::UTF8ToUTF16(kEmail));
+            base::UTF8ToUTF16("marion@me.xyz"));
 }
 
 TEST_F(CollectUserDataActionTest, SelectPaymentMethod) {
@@ -272,10 +284,6 @@
 }
 
 TEST_F(CollectUserDataActionTest, ContactDetailsCanHandleUtf8) {
-  // String literal = 艾丽森 in UTF-8.
-  const std::string kNonAsciiName("\xE8\x89\xBE\xE4\xB8\xBD\xE6\xA3\xAE");
-  const std::string kNonAsciiEmail(
-      "\xE8\x89\xBE\xE4\xB8\xBD\xE6\xA3\xAE@example.com");
   ActionProto action_proto;
   auto* collect_user_data_proto = action_proto.mutable_collect_user_data();
   collect_user_data_proto->set_request_terms_and_conditions(false);
@@ -285,32 +293,194 @@
   contact_details_proto->set_request_payer_name(true);
   contact_details_proto->set_request_payer_email(true);
 
+  // Name = 艾丽森 in UTF-8.
+  autofill::AutofillProfile contact_profile;
+  contact_profile.SetRawInfo(
+      autofill::ServerFieldType::NAME_FULL,
+      base::UTF8ToUTF16("\xE8\x89\xBE\xE4\xB8\xBD\xE6\xA3\xAE"));
+  contact_profile.SetRawInfo(
+      autofill::ServerFieldType::EMAIL_ADDRESS,
+      base::UTF8ToUTF16("\xE8\x89\xBE\xE4\xB8\xBD\xE6\xA3\xAE@example.com"));
+
   ON_CALL(mock_action_delegate_, CollectUserData(_, _))
       .WillByDefault(Invoke(
-          [&](std::unique_ptr<CollectUserDataOptions> collect_user_data_options,
+          [=](std::unique_ptr<CollectUserDataOptions> collect_user_data_options,
               std::unique_ptr<UserData> user_data) {
             user_data->succeed = true;
-            user_data->payer_name.assign(kNonAsciiName);
-            user_data->payer_email.assign(kNonAsciiEmail);
+            user_data->contact_profile =
+                std::make_unique<autofill::AutofillProfile>(contact_profile);
             std::move(collect_user_data_options->confirm_callback)
                 .Run(std::move(user_data));
           }));
 
-  EXPECT_CALL(callback_,
-              Run(Pointee(AllOf(
-                  Property(&ProcessedActionProto::status, ACTION_APPLIED),
-                  Property(&ProcessedActionProto::collect_user_data_result,
-                           Property(&CollectUserDataResultProto::payer_email,
-                                    kNonAsciiEmail))))));
+  EXPECT_CALL(
+      callback_,
+      Run(Pointee(AllOf(
+          Property(&ProcessedActionProto::status, ACTION_APPLIED),
+          Property(
+              &ProcessedActionProto::collect_user_data_result,
+              Property(&CollectUserDataResultProto::payer_email,
+                       "\xE8\x89\xBE\xE4\xB8\xBD\xE6\xA3\xAE@example.com"))))));
   CollectUserDataAction action(&mock_action_delegate_, action_proto);
   action.ProcessAction(callback_.Get());
 
   EXPECT_EQ(client_memory_.has_selected_address(kMemoryLocation), true);
   auto* profile = client_memory_.selected_address(kMemoryLocation);
   EXPECT_EQ(profile->GetRawInfo(autofill::NAME_FULL),
-            base::UTF8ToUTF16(kNonAsciiName));
-  EXPECT_EQ(profile->GetRawInfo(autofill::EMAIL_ADDRESS),
-            base::UTF8ToUTF16(kNonAsciiEmail));
+            base::UTF8ToUTF16("\xE8\x89\xBE\xE4\xB8\xBD\xE6\xA3\xAE"));
+  EXPECT_EQ(
+      profile->GetRawInfo(autofill::EMAIL_ADDRESS),
+      base::UTF8ToUTF16("\xE8\x89\xBE\xE4\xB8\xBD\xE6\xA3\xAE@example.com"));
+}
+
+TEST_F(CollectUserDataActionTest, UserDataComplete_Contact) {
+  UserData user_data;
+  CollectUserDataOptions options;
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.contact_profile = std::make_unique<autofill::AutofillProfile>(
+      base::GenerateGUID(), kFakeUrl);
+  options.request_payer_email = true;
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.contact_profile->SetRawInfo(
+      autofill::ServerFieldType::EMAIL_ADDRESS,
+      base::UTF8ToUTF16("joedoe@example.com"));
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  options.request_payer_name = true;
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.contact_profile->SetRawInfo(autofill::ServerFieldType::NAME_FULL,
+                                        base::UTF8ToUTF16("Joe Doe"));
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  options.request_payer_phone = true;
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.contact_profile->SetRawInfo(
+      autofill::ServerFieldType::PHONE_HOME_WHOLE_NUMBER,
+      base::UTF8ToUTF16("+1 23 456 789 01"));
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+}
+
+TEST_F(CollectUserDataActionTest, UserDataComplete_Payment) {
+  UserData user_data;
+  CollectUserDataOptions options;
+
+  options.request_payment_method = true;
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  // Valid credit card, but no billing address.
+  user_data.card =
+      std::make_unique<autofill::CreditCard>(base::GenerateGUID(), kFakeUrl);
+  autofill::test::SetCreditCardInfo(user_data.card.get(), "Marion Mitchell",
+                                    "4111 1111 1111 1111", "01", "2020",
+                                    /* billing_address_id = */ "");
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  // Valid credit card, but invalid billing address.
+  user_data.card->set_billing_address_id("invalid");
+  ON_CALL(mock_personal_data_manager_, GetProfileByGUID("invalid"))
+      .WillByDefault(Return(nullptr));
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  // Incomplete billing address.
+  user_data.billing_address = std::make_unique<autofill::AutofillProfile>(
+      base::GenerateGUID(), kFakeUrl);
+  autofill::test::SetProfileInfo(user_data.billing_address.get(), "Marion",
+                                 "Mitchell", "Morrison", "marion@me.xyz", "Fox",
+                                 "123 Zoo St.", "unit 5", "Hollywood", "CA",
+                                 /* zipcode = */ "", "US", "16505678910");
+  ON_CALL(mock_personal_data_manager_,
+          GetProfileByGUID(user_data.billing_address->guid()))
+      .WillByDefault(Return(user_data.billing_address.get()));
+  user_data.card->set_billing_address_id(user_data.billing_address->guid());
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.billing_address->SetRawInfo(autofill::ADDRESS_HOME_ZIP,
+                                        base::UTF8ToUTF16("91601"));
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  // Zip code is optional in Argentinian address.
+  user_data.billing_address->SetRawInfo(autofill::ADDRESS_HOME_ZIP,
+                                        base::UTF8ToUTF16(""));
+  user_data.billing_address->SetRawInfo(autofill::ADDRESS_HOME_COUNTRY,
+                                        base::UTF8ToUTF16("AR"));
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  options.require_billing_postal_code = true;
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.billing_address->SetRawInfo(autofill::ADDRESS_HOME_ZIP,
+                                        base::UTF8ToUTF16("B1675"));
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+}
+
+TEST_F(CollectUserDataActionTest, UserDataComplete_Terms) {
+  UserData user_data;
+  CollectUserDataOptions options;
+  options.accept_terms_and_conditions_text.assign("Accept T&C");
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.terms_and_conditions = REQUIRES_REVIEW;
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.terms_and_conditions = ACCEPTED;
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+}
+
+TEST_F(CollectUserDataActionTest, UserDataComplete_Login) {
+  UserData user_data;
+  CollectUserDataOptions options;
+  options.request_login_choice = true;
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.login_choice_identifier.assign("1");
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+}
+
+TEST_F(CollectUserDataActionTest, UserDataComplete_ShippingAddress) {
+  UserData user_data;
+  CollectUserDataOptions options;
+  options.request_shipping = true;
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  // Incomplete address.
+  user_data.shipping_address = std::make_unique<autofill::AutofillProfile>(
+      base::GenerateGUID(), kFakeUrl);
+  autofill::test::SetProfileInfo(user_data.shipping_address.get(), "Marion",
+                                 "Mitchell", "Morrison", "marion@me.xyz", "Fox",
+                                 "123 Zoo St.", "unit 5", "Hollywood", "CA",
+                                 /* zipcode = */ "", "US", "16505678910");
+  EXPECT_FALSE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
+
+  user_data.shipping_address->SetRawInfo(autofill::ADDRESS_HOME_ZIP,
+                                         base::UTF8ToUTF16("91601"));
+  EXPECT_TRUE(CollectUserDataAction::IsUserDataComplete(
+      &mock_personal_data_manager_, user_data, options));
 }
 
 }  // namespace
diff --git a/components/autofill_assistant/browser/controller.cc b/components/autofill_assistant/browser/controller.cc
index 346786c..d1343ff1 100644
--- a/components/autofill_assistant/browser/controller.cc
+++ b/components/autofill_assistant/browser/controller.cc
@@ -15,6 +15,7 @@
 #include "base/task/post_task.h"
 #include "base/time/tick_clock.h"
 #include "base/values.h"
+#include "components/autofill_assistant/browser/actions/collect_user_data_action.h"
 #include "components/autofill_assistant/browser/controller_observer.h"
 #include "components/autofill_assistant/browser/features.h"
 #include "components/autofill_assistant/browser/metrics.h"
@@ -979,27 +980,12 @@
   UpdateCollectUserDataActions();
 }
 
-void Controller::SetBillingAddress(
-    std::unique_ptr<autofill::AutofillProfile> address) {
+void Controller::SetContactInfo(
+    std::unique_ptr<autofill::AutofillProfile> profile) {
   if (!user_data_)
     return;
 
-  user_data_->billing_address = std::move(address);
-  for (ControllerObserver& observer : observers_) {
-    observer.OnUserDataChanged(user_data_.get());
-  }
-  UpdateCollectUserDataActions();
-}
-
-void Controller::SetContactInfo(std::string name,
-                                std::string phone,
-                                std::string email) {
-  if (!user_data_)
-    return;
-
-  user_data_->payer_name = name;
-  user_data_->payer_phone = phone;
-  user_data_->payer_email = email;
+  user_data_->contact_profile = std::move(profile);
   for (ControllerObserver& observer : observers_) {
     observer.OnUserDataChanged(user_data_.get());
   }
@@ -1010,6 +996,19 @@
   if (!user_data_)
     return;
 
+  autofill::AutofillProfile* billing_profile =
+      !card || card->billing_address_id().empty()
+          ? nullptr
+          : GetPersonalDataManager()->GetProfileByGUID(
+                card->billing_address_id());
+  if (billing_profile) {
+    auto billing_address =
+        std::make_unique<autofill::AutofillProfile>(*billing_profile);
+    user_data_->billing_address = std::move(billing_address);
+  } else {
+    user_data_->billing_address.reset();
+  }
+
   user_data_->card = std::move(card);
   for (ControllerObserver& observer : observers_) {
     observer.OnUserDataChanged(user_data_.get());
@@ -1050,35 +1049,8 @@
     return;
   }
 
-  bool contact_info_ok = (!collect_user_data_options_->request_payer_name ||
-                          !user_data_->payer_name.empty()) &&
-                         (!collect_user_data_options_->request_payer_email ||
-                          !user_data_->payer_email.empty()) &&
-                         (!collect_user_data_options_->request_payer_phone ||
-                          !user_data_->payer_phone.empty());
-
-  bool shipping_address_ok = !collect_user_data_options_->request_shipping ||
-                             user_data_->shipping_address;
-
-  bool payment_method_ok =
-      !collect_user_data_options_->request_payment_method || user_data_->card;
-
-  bool billing_address_ok =
-      !collect_user_data_options_->require_billing_postal_code ||
-      (user_data_->billing_address &&
-       !user_data_->billing_address->GetRawInfo(autofill::ADDRESS_HOME_ZIP)
-            .empty());
-
-  bool terms_ok =
-      user_data_->terms_and_conditions != NOT_SELECTED ||
-      collect_user_data_options_->accept_terms_and_conditions_text.empty();
-
-  bool login_ok = !collect_user_data_options_->request_login_choice ||
-                  !user_data_->login_choice_identifier.empty();
-
-  bool confirm_button_enabled = contact_info_ok && shipping_address_ok &&
-                                payment_method_ok && billing_address_ok &&
-                                terms_ok && login_ok;
+  bool confirm_button_enabled = CollectUserDataAction::IsUserDataComplete(
+      GetPersonalDataManager(), *user_data_, *collect_user_data_options_);
 
   UserAction confirm(collect_user_data_options_->confirm_action);
   confirm.SetEnabled(confirm_button_enabled);
diff --git a/components/autofill_assistant/browser/controller.h b/components/autofill_assistant/browser/controller.h
index 686e61b..a7777502 100644
--- a/components/autofill_assistant/browser/controller.h
+++ b/components/autofill_assistant/browser/controller.h
@@ -150,11 +150,8 @@
   const UserData* GetUserData() const override;
   void SetShippingAddress(
       std::unique_ptr<autofill::AutofillProfile> address) override;
-  void SetBillingAddress(
-      std::unique_ptr<autofill::AutofillProfile> address) override;
-  void SetContactInfo(std::string name,
-                      std::string phone,
-                      std::string email) override;
+  void SetContactInfo(
+      std::unique_ptr<autofill::AutofillProfile> profile) override;
   void SetCreditCard(std::unique_ptr<autofill::CreditCard> card) override;
   void SetTermsAndConditions(
       TermsAndConditionsState terms_and_conditions) override;
diff --git a/components/autofill_assistant/browser/controller_unittest.cc b/components/autofill_assistant/browser/controller_unittest.cc
index 672c941d..50227cb 100644
--- a/components/autofill_assistant/browser/controller_unittest.cc
+++ b/components/autofill_assistant/browser/controller_unittest.cc
@@ -7,11 +7,14 @@
 #include <memory>
 #include <utility>
 
+#include "base/guid.h"
 #include "base/test/gmock_callback_support.h"
 #include "base/test/mock_callback.h"
 #include "base/test/scoped_feature_list.h"
+#include "components/autofill/core/browser/autofill_test_utils.h"
 #include "components/autofill_assistant/browser/features.h"
 #include "components/autofill_assistant/browser/mock_controller_observer.h"
+#include "components/autofill_assistant/browser/mock_personal_data_manager.h"
 #include "components/autofill_assistant/browser/mock_service.h"
 #include "components/autofill_assistant/browser/service.h"
 #include "components/autofill_assistant/browser/trigger_context.h"
@@ -57,8 +60,8 @@
   // Implements Client
   std::string GetApiKey() override { return ""; }
   AccessTokenFetcher* GetAccessTokenFetcher() override { return nullptr; }
-  autofill::PersonalDataManager* GetPersonalDataManager() override {
-    return nullptr;
+  MockPersonalDataManager* GetPersonalDataManager() override {
+    return &mock_personal_data_manager_;
   }
   WebsiteLoginFetcher* GetWebsiteLoginFetcher() override { return nullptr; }
   std::string GetServerUrl() override { return ""; }
@@ -68,6 +71,22 @@
   MOCK_METHOD1(Shutdown, void(Metrics::DropOutReason reason));
   MOCK_METHOD0(AttachUI, void());
   MOCK_METHOD0(DestroyUI, void());
+
+ private:
+  MockPersonalDataManager mock_personal_data_manager_;
+};
+
+// Same as non-mock, but provides default mock callbacks.
+struct MockCollectUserDataOptions : public CollectUserDataOptions {
+  MockCollectUserDataOptions() {
+    base::MockOnceCallback<void(std::unique_ptr<UserData>)>
+        mock_confirm_callback;
+    confirm_callback = std::move(mock_confirm_callback.Get());
+    base::MockOnceCallback<void(int)> mock_actions_callback;
+    additional_actions_callback = std::move(mock_actions_callback.Get());
+    base::MockOnceCallback<void(int)> mock_terms_callback;
+    terms_link_callback = std::move(mock_terms_callback.Get());
+  }
 };
 
 }  // namespace
@@ -1394,4 +1413,165 @@
                                    AutofillAssistantState::STOPPED));
 }
 
+TEST_F(ControllerTest, UserDataFormEmpty) {
+  auto options = std::make_unique<MockCollectUserDataOptions>();
+  auto user_data = std::make_unique<UserData>();
+
+  // Request nothing, expect continue button to be enabled.
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(true)))))
+      .Times(1);
+  EXPECT_CALL(mock_observer_, OnCollectUserDataOptionsChanged(Not(nullptr)))
+      .Times(1);
+  EXPECT_CALL(mock_observer_, OnUserDataChanged(Not(nullptr))).Times(1);
+  controller_->SetCollectUserDataOptions(std::move(options),
+                                         std::move(user_data));
+}
+
+TEST_F(ControllerTest, UserDataFormContactInfo) {
+  auto options = std::make_unique<MockCollectUserDataOptions>();
+  auto user_data = std::make_unique<UserData>();
+
+  options->request_payer_name = true;
+  options->request_payer_email = true;
+  options->request_payer_phone = true;
+
+  testing::InSequence seq;
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(false)))))
+      .Times(1);
+  controller_->SetCollectUserDataOptions(std::move(options),
+                                         std::move(user_data));
+
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(true)))))
+      .Times(1);
+
+  autofill::AutofillProfile contact_profile;
+  contact_profile.SetRawInfo(autofill::ServerFieldType::EMAIL_ADDRESS,
+                             base::UTF8ToUTF16("joedoe@example.com"));
+  contact_profile.SetRawInfo(autofill::ServerFieldType::NAME_FULL,
+                             base::UTF8ToUTF16("Joe Doe"));
+  contact_profile.SetRawInfo(autofill::ServerFieldType::PHONE_HOME_WHOLE_NUMBER,
+                             base::UTF8ToUTF16("+1 23 456 789 01"));
+  controller_->SetContactInfo(
+      std::make_unique<autofill::AutofillProfile>(contact_profile));
+  EXPECT_THAT(
+      controller_->GetUserData()->contact_profile->Compare(contact_profile),
+      Eq(0));
+}
+
+TEST_F(ControllerTest, UserDataFormCreditCard) {
+  auto options = std::make_unique<MockCollectUserDataOptions>();
+  auto user_data = std::make_unique<UserData>();
+
+  options->request_payment_method = true;
+  testing::InSequence seq;
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(false)))))
+      .Times(1);
+  controller_->SetCollectUserDataOptions(std::move(options),
+                                         std::move(user_data));
+
+  // Credit card without billing address is invalid.
+  auto credit_card = std::make_unique<autofill::CreditCard>(
+      base::GenerateGUID(), "https://www.example.com");
+  autofill::test::SetCreditCardInfo(credit_card.get(), "Marion Mitchell",
+                                    "4111 1111 1111 1111", "01", "2020",
+                                    /* billing_address_id = */ "");
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(false)))))
+      .Times(1);
+  controller_->SetCreditCard(
+      std::make_unique<autofill::CreditCard>(*credit_card));
+
+  // Credit card with valid billing address is ok.
+  auto billing_address = std::make_unique<autofill::AutofillProfile>(
+      base::GenerateGUID(), "https://www.example.com");
+  autofill::test::SetProfileInfo(billing_address.get(), "Marion", "Mitchell",
+                                 "Morrison", "marion@me.xyz", "Fox",
+                                 "123 Zoo St.", "unit 5", "Hollywood", "CA",
+                                 "91601", "US", "16505678910");
+  credit_card->set_billing_address_id(billing_address->guid());
+  ON_CALL(*fake_client_.GetPersonalDataManager(),
+          GetProfileByGUID(billing_address->guid()))
+      .WillByDefault(Return(billing_address.get()));
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(true)))))
+      .Times(1);
+  controller_->SetCreditCard(
+      std::make_unique<autofill::CreditCard>(*credit_card));
+  EXPECT_THAT(controller_->GetUserData()->card->Compare(*credit_card), Eq(0));
+}
+
+TEST_F(ControllerTest, SetTermsAndConditions) {
+  auto options = std::make_unique<MockCollectUserDataOptions>();
+  auto user_data = std::make_unique<UserData>();
+
+  options->accept_terms_and_conditions_text.assign("Accept T&C");
+  testing::InSequence seq;
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(false)))))
+      .Times(1);
+  controller_->SetCollectUserDataOptions(std::move(options),
+                                         std::move(user_data));
+
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(true)))))
+      .Times(1);
+  controller_->SetTermsAndConditions(TermsAndConditionsState::ACCEPTED);
+  EXPECT_THAT(controller_->GetUserData()->terms_and_conditions,
+              Eq(TermsAndConditionsState::ACCEPTED));
+}
+
+TEST_F(ControllerTest, SetLoginOption) {
+  auto options = std::make_unique<MockCollectUserDataOptions>();
+  auto user_data = std::make_unique<UserData>();
+
+  options->request_login_choice = true;
+  testing::InSequence seq;
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(false)))))
+      .Times(1);
+  controller_->SetCollectUserDataOptions(std::move(options),
+                                         std::move(user_data));
+
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(true)))))
+      .Times(1);
+  controller_->SetLoginOption("1");
+  EXPECT_THAT(controller_->GetUserData()->login_choice_identifier, Eq("1"));
+}
+
+TEST_F(ControllerTest, SetShippingAddress) {
+  auto options = std::make_unique<MockCollectUserDataOptions>();
+  auto user_data = std::make_unique<UserData>();
+
+  options->request_shipping = true;
+  testing::InSequence seq;
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(false)))))
+      .Times(1);
+  controller_->SetCollectUserDataOptions(std::move(options),
+                                         std::move(user_data));
+
+  auto shipping_address = std::make_unique<autofill::AutofillProfile>(
+      base::GenerateGUID(), "https://www.example.com");
+  autofill::test::SetProfileInfo(shipping_address.get(), "Marion", "Mitchell",
+                                 "Morrison", "marion@me.xyz", "Fox",
+                                 "123 Zoo St.", "unit 5", "Hollywood", "CA",
+                                 "91601", "US", "16505678910");
+  ON_CALL(*fake_client_.GetPersonalDataManager(),
+          GetProfileByGUID(shipping_address->guid()))
+      .WillByDefault(Return(shipping_address.get()));
+  EXPECT_CALL(mock_observer_, OnUserActionsChanged(UnorderedElementsAre(
+                                  Property(&UserAction::enabled, Eq(true)))))
+      .Times(1);
+  controller_->SetShippingAddress(
+      std::make_unique<autofill::AutofillProfile>(*shipping_address));
+  EXPECT_THAT(
+      controller_->GetUserData()->shipping_address->Compare(*shipping_address),
+      Eq(0));
+}
+
 }  // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/mock_controller_observer.h b/components/autofill_assistant/browser/mock_controller_observer.h
index 3039fde..151bdc1 100644
--- a/components/autofill_assistant/browser/mock_controller_observer.h
+++ b/components/autofill_assistant/browser/mock_controller_observer.h
@@ -27,8 +27,9 @@
   MOCK_METHOD1(OnStateChanged, void(AutofillAssistantState));
   MOCK_METHOD1(OnUserActionsChanged,
                void(const std::vector<UserAction>& user_actions));
-  MOCK_METHOD1(OnPaymentRequestChanged,
+  MOCK_METHOD1(OnCollectUserDataOptionsChanged,
                void(const CollectUserDataOptions* options));
+  MOCK_METHOD1(OnUserDataChanged, void(const UserData* user_data));
   MOCK_METHOD1(OnDetailsChanged, void(const Details* details));
   MOCK_METHOD1(OnInfoBoxChanged, void(const InfoBox* info_box));
   MOCK_METHOD1(OnProgressChanged, void(int progress));
@@ -43,6 +44,8 @@
   MOCK_METHOD1(OnPeekModeChanged,
                void(ConfigureBottomSheetProto::PeekMode peek_mode));
   MOCK_METHOD1(OnFormChanged, void(const FormProto* form));
+
+  // TODO(b/141163294): add missing methods and unit tests.
 };
 
 }  // namespace autofill_assistant
diff --git a/components/autofill_assistant/browser/service.proto b/components/autofill_assistant/browser/service.proto
index e4be415..2e3e4bc 100644
--- a/components/autofill_assistant/browser/service.proto
+++ b/components/autofill_assistant/browser/service.proto
@@ -583,6 +583,9 @@
   // Name of the address key requested in the list of keys in
   // |client_memory_address_key_names|.
   optional string address_key_requested = 2;
+
+  // Whether the client memory at |address_key_requested| pointed to null.
+  optional bool address_pointee_was_null = 3;
 }
 
 enum ProcessedActionStatusProto {
diff --git a/components/autofill_assistant/browser/ui_delegate.h b/components/autofill_assistant/browser/ui_delegate.h
index 1c637dcd..b6d5f7c2 100644
--- a/components/autofill_assistant/browser/ui_delegate.h
+++ b/components/autofill_assistant/browser/ui_delegate.h
@@ -104,14 +104,9 @@
   virtual void SetShippingAddress(
       std::unique_ptr<autofill::AutofillProfile> address) = 0;
 
-  // Sets billing address, in response to the current collect user data options.
-  virtual void SetBillingAddress(
-      std::unique_ptr<autofill::AutofillProfile> address) = 0;
-
   // Sets contact info, in response to the current collect user data options.
-  virtual void SetContactInfo(std::string name,
-                              std::string phone,
-                              std::string email) = 0;
+  virtual void SetContactInfo(
+      std::unique_ptr<autofill::AutofillProfile> profile) = 0;
 
   // Sets credit card, in response to the current collect user data options.
   virtual void SetCreditCard(std::unique_ptr<autofill::CreditCard> card) = 0;
diff --git a/components/autofill_assistant/browser/user_data.h b/components/autofill_assistant/browser/user_data.h
index ada8c1b4..4e39474 100644
--- a/components/autofill_assistant/browser/user_data.h
+++ b/components/autofill_assistant/browser/user_data.h
@@ -49,13 +49,11 @@
   ~UserData();
 
   bool succeed = false;
+  std::unique_ptr<autofill::AutofillProfile> contact_profile;
   std::unique_ptr<autofill::CreditCard> card;
   std::unique_ptr<autofill::AutofillProfile> shipping_address;
   std::unique_ptr<autofill::AutofillProfile> billing_address;
   std::string login_choice_identifier;
-  std::string payer_name;
-  std::string payer_phone;
-  std::string payer_email;
   TermsAndConditionsState terms_and_conditions = NOT_SELECTED;
 };
 
diff --git a/components/download/public/common/download_features.cc b/components/download/public/common/download_features.cc
index 65fc66ec..1e2db1e 100644
--- a/components/download/public/common/download_features.cc
+++ b/components/download/public/common/download_features.cc
@@ -36,7 +36,7 @@
 #endif
 
 const base::Feature kPreventDownloadsWithSamePath{
-    "PreventDownloadsWithSamePath", base::FEATURE_DISABLED_BY_DEFAULT};
+    "PreventDownloadsWithSamePath", base::FEATURE_ENABLED_BY_DEFAULT};
 
 const base::Feature kUseInProgressDownloadManagerForDownloadService{
     "UseInProgressDownloadManagerForDownloadService",
diff --git a/components/mirroring/mojom/mirroring_service.mojom b/components/mirroring/mojom/mirroring_service.mojom
index 1b9bf8b..df85bc3 100644
--- a/components/mirroring/mojom/mirroring_service.mojom
+++ b/components/mirroring/mojom/mirroring_service.mojom
@@ -20,8 +20,8 @@
   // To stop the session, just close the message pipe.
   Start(SessionParameters params,
         gfx.mojom.Size max_resolution,
-        SessionObserver observer,
-        ResourceProvider resource_provider,
+        pending_remote<SessionObserver> observer,
+        pending_remote<ResourceProvider> resource_provider,
         pending_remote<CastMessageChannel> outbound_channel,
         pending_receiver<CastMessageChannel> inbound_channel);
 };
diff --git a/components/mirroring/mojom/mirroring_service_host.mojom b/components/mirroring/mojom/mirroring_service_host.mojom
index 9c4febda..279aa2f 100644
--- a/components/mirroring/mojom/mirroring_service_host.mojom
+++ b/components/mirroring/mojom/mirroring_service_host.mojom
@@ -17,7 +17,7 @@
   // the messages from the mirroring receiver to the Mirroring Service.
   // To stop the session, just close the message pipe.
   Start(SessionParameters params,
-        SessionObserver observer,
+        pending_remote<SessionObserver> observer,
         pending_remote<CastMessageChannel> outbound_channel,
         pending_receiver<CastMessageChannel> inbound_channel);
 
diff --git a/components/mirroring/service/mirroring_service.cc b/components/mirroring/service/mirroring_service.cc
index e3f93c7..e6ae6f9 100644
--- a/components/mirroring/service/mirroring_service.cc
+++ b/components/mirroring/service/mirroring_service.cc
@@ -22,8 +22,8 @@
 void MirroringService::Start(
     mojom::SessionParametersPtr params,
     const gfx::Size& max_resolution,
-    mojom::SessionObserverPtr observer,
-    mojom::ResourceProviderPtr resource_provider,
+    mojo::PendingRemote<mojom::SessionObserver> observer,
+    mojo::PendingRemote<mojom::ResourceProvider> resource_provider,
     mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel,
     mojo::PendingReceiver<mojom::CastMessageChannel> inbound_channel) {
   session_.reset();  // Stops the current session if active.
diff --git a/components/mirroring/service/mirroring_service.h b/components/mirroring/service/mirroring_service.h
index 91e774093..5d84d52 100644
--- a/components/mirroring/service/mirroring_service.h
+++ b/components/mirroring/service/mirroring_service.h
@@ -27,8 +27,8 @@
   // mojom::MirroringService implementation.
   void Start(mojom::SessionParametersPtr params,
              const gfx::Size& max_resolution,
-             mojom::SessionObserverPtr observer,
-             mojom::ResourceProviderPtr resource_provider,
+             mojo::PendingRemote<mojom::SessionObserver> observer,
+             mojo::PendingRemote<mojom::ResourceProvider> resource_provider,
              mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel,
              mojo::PendingReceiver<mojom::CastMessageChannel> inbound_channel)
       override;
diff --git a/components/mirroring/service/session.cc b/components/mirroring/service/session.cc
index 00ea669..892a596 100644
--- a/components/mirroring/service/session.cc
+++ b/components/mirroring/service/session.cc
@@ -376,8 +376,8 @@
 Session::Session(
     mojom::SessionParametersPtr session_params,
     const gfx::Size& max_resolution,
-    mojom::SessionObserverPtr observer,
-    mojom::ResourceProviderPtr resource_provider,
+    mojo::PendingRemote<mojom::SessionObserver> observer,
+    mojo::PendingRemote<mojom::ResourceProvider> resource_provider,
     mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel,
     mojo::PendingReceiver<mojom::CastMessageChannel> inbound_channel,
     scoped_refptr<base::SingleThreadTaskRunner> io_task_runner)
diff --git a/components/mirroring/service/session.h b/components/mirroring/service/session.h
index 71c84d4..b97a401 100644
--- a/components/mirroring/service/session.h
+++ b/components/mirroring/service/session.h
@@ -62,8 +62,8 @@
  public:
   Session(mojom::SessionParametersPtr session_params,
           const gfx::Size& max_resolution,
-          mojom::SessionObserverPtr observer,
-          mojom::ResourceProviderPtr resource_provider,
+          mojo::PendingRemote<mojom::SessionObserver> observer,
+          mojo::PendingRemote<mojom::ResourceProvider> resource_provider,
           mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel,
           mojo::PendingReceiver<mojom::CastMessageChannel> inbound_channel,
           scoped_refptr<base::SingleThreadTaskRunner> io_task_runner);
@@ -157,8 +157,8 @@
     STOPPED,    // The session is stopped due to user's request or errors.
   } state_;
 
-  mojom::SessionObserverPtr observer_;
-  mojom::ResourceProviderPtr resource_provider_;
+  mojo::Remote<mojom::SessionObserver> observer_;
+  mojo::Remote<mojom::ResourceProvider> resource_provider_;
   MirrorSettings mirror_settings_;
 
   MessageDispatcher message_dispatcher_;
diff --git a/components/mirroring/service/session_unittest.cc b/components/mirroring/service/session_unittest.cc
index ca9c0e64..ccf88236 100644
--- a/components/mirroring/service/session_unittest.cc
+++ b/components/mirroring/service/session_unittest.cc
@@ -19,7 +19,6 @@
 #include "components/mirroring/service/value_util.h"
 #include "media/cast/test/utility/default_config.h"
 #include "media/cast/test/utility/net_utility.h"
-#include "mojo/public/cpp/bindings/binding.h"
 #include "mojo/public/cpp/bindings/pending_receiver.h"
 #include "mojo/public/cpp/bindings/pending_remote.h"
 #include "mojo/public/cpp/bindings/receiver.h"
@@ -76,10 +75,7 @@
                     public mojom::CastMessageChannel,
                     public ::testing::Test {
  public:
-  SessionTest()
-      : receiver_endpoint_(media::cast::test::GetFreeLocalPort()),
-        resource_provider_binding_(this),
-        session_observer_binding_(this) {}
+  SessionTest() : receiver_endpoint_(media::cast::test::GetFreeLocalPort()) {}
 
   ~SessionTest() override { task_environment_.RunUntilIdle(); }
 
@@ -202,11 +198,13 @@
     session_params->type = session_type_;
     session_params->receiver_model_name = "Chromecast";
     cast_mode_ = "mirroring";
-    mojom::ResourceProviderPtr resource_provider_ptr;
-    mojom::SessionObserverPtr session_observer_ptr;
+    mojo::PendingRemote<mojom::ResourceProvider> resource_provider_remote;
+    mojo::PendingRemote<mojom::SessionObserver> session_observer_remote;
     mojo::PendingRemote<mojom::CastMessageChannel> outbound_channel_remote;
-    resource_provider_binding_.Bind(mojo::MakeRequest(&resource_provider_ptr));
-    session_observer_binding_.Bind(mojo::MakeRequest(&session_observer_ptr));
+    resource_provider_receiver_.Bind(
+        resource_provider_remote.InitWithNewPipeAndPassReceiver());
+    session_observer_receiver_.Bind(
+        session_observer_remote.InitWithNewPipeAndPassReceiver());
     outbound_channel_receiver_.Bind(
         outbound_channel_remote.InitWithNewPipeAndPassReceiver());
     // Expect to send OFFER message when session is created.
@@ -215,7 +213,7 @@
     EXPECT_CALL(*this, OnOutboundMessage("OFFER")).Times(1);
     session_ = std::make_unique<Session>(
         std::move(session_params), gfx::Size(1920, 1080),
-        std::move(session_observer_ptr), std::move(resource_provider_ptr),
+        std::move(session_observer_remote), std::move(resource_provider_remote),
         std::move(outbound_channel_remote),
         inbound_channel_.BindNewPipeAndPassReceiver(), nullptr);
     task_environment_.RunUntilIdle();
@@ -341,8 +339,8 @@
  private:
   base::test::TaskEnvironment task_environment_;
   const net::IPEndPoint receiver_endpoint_;
-  mojo::Binding<mojom::ResourceProvider> resource_provider_binding_;
-  mojo::Binding<mojom::SessionObserver> session_observer_binding_;
+  mojo::Receiver<mojom::ResourceProvider> resource_provider_receiver_{this};
+  mojo::Receiver<mojom::SessionObserver> session_observer_receiver_{this};
   mojo::Receiver<mojom::CastMessageChannel> outbound_channel_receiver_{this};
   mojo::Remote<mojom::CastMessageChannel> inbound_channel_;
   SessionType session_type_ = SessionType::AUDIO_AND_VIDEO;
diff --git a/components/omnibox/common/omnibox_features.cc b/components/omnibox/common/omnibox_features.cc
index e91d237..6c3ff55 100644
--- a/components/omnibox/common/omnibox_features.cc
+++ b/components/omnibox/common/omnibox_features.cc
@@ -60,7 +60,7 @@
 // except for the default match which is unchanged in position.
 const base::Feature kOmniboxGroupSuggestionsBySearchVsUrl{
   "OmniboxGroupSuggestionsBySearchVsUrl",
-#if defined(OS_IOS) || defined(OS_ANDROID)
+#if defined(OS_IOS)
       base::FEATURE_DISABLED_BY_DEFAULT
 #else
       base::FEATURE_ENABLED_BY_DEFAULT
@@ -265,7 +265,7 @@
 // Exempts the default match from demotion-by-type.
 const base::Feature kOmniboxPreserveDefaultMatchScore {
   "OmniboxPreserveDefaultMatchScore",
-#if defined(OS_IOS) || defined(OS_ANDROID)
+#if defined(OS_IOS)
       base::FEATURE_DISABLED_BY_DEFAULT
 #else
       base::FEATURE_ENABLED_BY_DEFAULT
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn
index 37acd2b..c6f10204 100644
--- a/components/password_manager/core/browser/BUILD.gn
+++ b/components/password_manager/core/browser/BUILD.gn
@@ -97,6 +97,8 @@
     "import/password_csv_reader.h",
     "import/password_importer.cc",
     "import/password_importer.h",
+    "leaked_credentials_table.cc",
+    "leaked_credentials_table.h",
     "login_database.cc",
     "login_database.h",
     "login_database_ios.cc",
@@ -503,6 +505,7 @@
     "import/csv_reader_unittest.cc",
     "import/password_csv_reader_unittest.cc",
     "import/password_importer_unittest.cc",
+    "leaked_credentials_table_unittest.cc",
     "login_database_unittest.cc",
     "multi_store_form_fetcher_unittest.cc",
     "origin_credential_store_unittest.cc",
diff --git a/components/password_manager/core/browser/leaked_credentials_table.cc b/components/password_manager/core/browser/leaked_credentials_table.cc
new file mode 100644
index 0000000..861b48a
--- /dev/null
+++ b/components/password_manager/core/browser/leaked_credentials_table.cc
@@ -0,0 +1,113 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "components/password_manager/core/browser/leaked_credentials_table.h"
+
+#include "components/password_manager/core/browser/sql_table_builder.h"
+#include "sql/database.h"
+#include "sql/statement.h"
+
+namespace password_manager {
+namespace {
+
+constexpr char kLeakedCredentialsTableName[] = "leaked_credentials";
+
+// Represents all the columns of the leaked credentials table.
+enum class LeakedCredentialsTableColumn {
+  kUrl,
+  kUsername,
+  kCreateTime,
+  kMaxValue = kCreateTime
+};
+
+// Casts the leaked credentials table column enum to its integer value.
+int GetColumnNumber(LeakedCredentialsTableColumn column) {
+  return static_cast<int>(column);
+}
+
+// Teaches |builder| about the different DB schemes in different versions.
+void InitializeLeakedCredentialsBuilder(SQLTableBuilder* builder) {
+  // Version 0.
+  builder->AddColumnToUniqueKey("url", "VARCHAR NOT NULL");
+  builder->AddColumnToUniqueKey("username", "VARCHAR NOT NULL");
+  builder->AddColumn("create_time", "INTEGER NOT NULL");
+  builder->AddIndex("leaked_credentials_index", {"url", "username"});
+  builder->SealVersion();
+}
+
+// Returns a leaked credentials vector from the SQL statement.
+std::vector<LeakedCredentials> StatementToLeakedCredentials(sql::Statement* s) {
+  std::vector<LeakedCredentials> results;
+  while (s->Step()) {
+    results.push_back(LeakedCredentials());
+    results.back().url = GURL(
+        s->ColumnString(GetColumnNumber(LeakedCredentialsTableColumn::kUrl)));
+    results.back().username = s->ColumnString16(
+        GetColumnNumber(LeakedCredentialsTableColumn::kUsername));
+    results.back().create_time = base::Time::FromDeltaSinceWindowsEpoch(
+        (base::TimeDelta::FromMicroseconds(s->ColumnInt64(
+            GetColumnNumber(LeakedCredentialsTableColumn::kCreateTime)))));
+  }
+  return results;
+}
+
+}  // namespace
+
+bool operator==(const LeakedCredentials& lhs, const LeakedCredentials& rhs) {
+  return lhs.url == rhs.url && lhs.username == rhs.username &&
+         lhs.create_time == rhs.create_time;
+}
+
+LeakedCredentialsTable::LeakedCredentialsTable(sql::Database* db) : db_(db) {}
+
+bool LeakedCredentialsTable::CreateTableIfNecessary() {
+  if (!db_->DoesTableExist(kLeakedCredentialsTableName)) {
+    SQLTableBuilder builder(kLeakedCredentialsTableName);
+    InitializeLeakedCredentialsBuilder(&builder);
+    if (!builder.CreateTable(db_))
+      return false;
+  }
+  return true;
+}
+
+bool LeakedCredentialsTable::AddRow(
+    const LeakedCredentials& leaked_credentials) {
+  if (!leaked_credentials.url.is_valid())
+    return false;
+  sql::Statement s(
+      db_->GetCachedStatement(SQL_FROM_HERE,
+                              "INSERT OR IGNORE INTO leaked_credentials "
+                              "(url, username, create_time) "
+                              "VALUES (?, ?, ?)"));
+  s.BindString(GetColumnNumber(LeakedCredentialsTableColumn::kUrl),
+               leaked_credentials.url.spec());
+  s.BindString16(GetColumnNumber(LeakedCredentialsTableColumn::kUsername),
+                 leaked_credentials.username);
+  s.BindInt64(GetColumnNumber(LeakedCredentialsTableColumn::kCreateTime),
+              leaked_credentials.create_time.ToDeltaSinceWindowsEpoch()
+                  .InMicroseconds());
+  return s.Run();
+}
+
+bool LeakedCredentialsTable::RemoveRow(const GURL& url,
+                                       const base::string16& username) {
+  if (!url.is_valid())
+    return false;
+  sql::Statement s(db_->GetCachedStatement(
+      SQL_FROM_HERE,
+      "DELETE FROM leaked_credentials WHERE url = ? AND username = ? "));
+  s.BindString(GetColumnNumber(LeakedCredentialsTableColumn::kUrl), url.spec());
+  s.BindString16(GetColumnNumber(LeakedCredentialsTableColumn::kUsername),
+                 username);
+  return s.Run();
+}
+
+std::vector<LeakedCredentials> LeakedCredentialsTable::GetAllRows() {
+  static constexpr char query[] =
+      "SELECT url, username, create_time FROM leaked_credentials";
+  sql::Statement s(db_->GetCachedStatement(SQL_FROM_HERE, query));
+  return StatementToLeakedCredentials(&s);
+}
+
+}  // namespace password_manager
diff --git a/components/password_manager/core/browser/leaked_credentials_table.h b/components/password_manager/core/browser/leaked_credentials_table.h
new file mode 100644
index 0000000..ff7c75c4
--- /dev/null
+++ b/components/password_manager/core/browser/leaked_credentials_table.h
@@ -0,0 +1,60 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_LEAKED_CREDENTIALS_TABLE_H_
+#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_LEAKED_CREDENTIALS_TABLE_H_
+
+#include "base/macros.h"
+#include "base/time/time.h"
+#include "url/gurl.h"
+
+namespace sql {
+class Database;
+}
+
+namespace password_manager {
+
+// Represents information about the particular credentials leak.
+// TODO(crbug.com/1005746): Discuss the design whether we should have additional
+// |update_time| field or store multiple records with different |create_time|.
+struct LeakedCredentials {
+  // The url of the website of the leak.
+  GURL url;
+  // The value of the leaked username.
+  base::string16 username;
+  // The date when the record was created.
+  base::Time create_time;
+};
+
+bool operator==(const LeakedCredentials& lhs, const LeakedCredentials& rhs);
+
+// Represents the 'leaked credentials' table in the Login Database.
+class LeakedCredentialsTable {
+ public:
+  explicit LeakedCredentialsTable(sql::Database* db);
+  ~LeakedCredentialsTable() = default;
+
+  // Creates the leaked credentials table if it doesn't exist.
+  bool CreateTableIfNecessary();
+
+  // Adds information about the leaked credentials. Returns true if the SQL
+  // completed successfully.
+  bool AddRow(const LeakedCredentials& leaked_credentials);
+
+  // Removes information about the credentials leaked for |username| on |url|.
+  // Returns true if the SQL completed successfully.
+  bool RemoveRow(const GURL& url, const base::string16& username);
+
+  // Returns all leaked credentials from the database.
+  std::vector<LeakedCredentials> GetAllRows();
+
+ private:
+  sql::Database* db_;
+
+  DISALLOW_COPY_AND_ASSIGN(LeakedCredentialsTable);
+};
+
+}  // namespace password_manager
+
+#endif  // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_LEAKED_CREDENTIALS_TABLE_H_
diff --git a/components/password_manager/core/browser/leaked_credentials_table_unittest.cc b/components/password_manager/core/browser/leaked_credentials_table_unittest.cc
new file mode 100644
index 0000000..a8f89c5
--- /dev/null
+++ b/components/password_manager/core/browser/leaked_credentials_table_unittest.cc
@@ -0,0 +1,117 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "components/password_manager/core/browser/leaked_credentials_table.h"
+
+#include "base/files/scoped_temp_dir.h"
+#include "base/strings/utf_string_conversions.h"
+#include "sql/database.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace password_manager {
+namespace {
+
+const char kTestDomain[] = "http://example.com";
+const char kTestDomain2[] = "http://test.com";
+const char kUsername[] = "user";
+const char kUsername2[] = "user2";
+
+using testing::ElementsAre;
+using testing::IsEmpty;
+
+class LeakedCredentialsTableTest : public testing::Test {
+ protected:
+  void SetUp() override {
+    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
+    ReloadDatabase();
+
+    test_data_.url = GURL(kTestDomain);
+    test_data_.username = base::ASCIIToUTF16(kUsername);
+    test_data_.create_time = base::Time::FromTimeT(1);
+  }
+
+  void ReloadDatabase() {
+    base::FilePath file = temp_dir_.GetPath().AppendASCII("TestDatabase");
+    connection_.reset(new sql::Database);
+    connection_->set_exclusive_locking();
+    ASSERT_TRUE(connection_->Open(file));
+    db_.reset(new LeakedCredentialsTable(connection_.get()));
+    ASSERT_TRUE(db_->CreateTableIfNecessary());
+  }
+
+  LeakedCredentials& test_data() { return test_data_; }
+  LeakedCredentialsTable* db() { return db_.get(); }
+
+ private:
+  base::ScopedTempDir temp_dir_;
+  std::unique_ptr<sql::Database> connection_;
+  std::unique_ptr<LeakedCredentialsTable> db_;
+  LeakedCredentials test_data_;
+};
+
+TEST_F(LeakedCredentialsTableTest, Sanity) {
+  EXPECT_TRUE(db()->AddRow(test_data()));
+  EXPECT_THAT(db()->GetAllRows(), ElementsAre(test_data()));
+  EXPECT_TRUE(db()->RemoveRow(test_data().url, test_data().username));
+  EXPECT_THAT(db()->GetAllRows(), IsEmpty());
+}
+
+TEST_F(LeakedCredentialsTableTest, Reload) {
+  EXPECT_TRUE(db()->AddRow(test_data()));
+  ReloadDatabase();
+  EXPECT_THAT(db()->GetAllRows(), ElementsAre(test_data()));
+}
+
+TEST_F(LeakedCredentialsTableTest, SameUrlDifferentUsername) {
+  LeakedCredentials leaked_credentials1 = test_data();
+  LeakedCredentials leaked_credentials2 = test_data();
+  leaked_credentials2.username = base::ASCIIToUTF16(kUsername2);
+
+  EXPECT_TRUE(db()->AddRow(leaked_credentials1));
+  EXPECT_TRUE(db()->AddRow(leaked_credentials2));
+  EXPECT_THAT(db()->GetAllRows(),
+              ElementsAre(leaked_credentials1, leaked_credentials2));
+}
+
+TEST_F(LeakedCredentialsTableTest, SameUsernameDifferentUrl) {
+  LeakedCredentials leaked_credentials1 = test_data();
+  LeakedCredentials leaked_credentials2 = test_data();
+  leaked_credentials2.url = GURL(kTestDomain2);
+
+  EXPECT_TRUE(db()->AddRow(leaked_credentials1));
+  EXPECT_TRUE(db()->AddRow(leaked_credentials2));
+  EXPECT_THAT(db()->GetAllRows(),
+              ElementsAre(leaked_credentials1, leaked_credentials2));
+}
+
+TEST_F(LeakedCredentialsTableTest, SameUrlAndUsernameDifferentTime) {
+  LeakedCredentials leaked_credentials1 = test_data();
+  LeakedCredentials leaked_credentials2 = test_data();
+  leaked_credentials2.create_time = base::Time::FromTimeT(2);
+
+  EXPECT_TRUE(db()->AddRow(leaked_credentials1));
+  // It should return true as the sql statement ran correctly. It ignored
+  // new row though because of unique constraints, hence there is only one
+  // record in the database.
+  EXPECT_TRUE(db()->AddRow(leaked_credentials2));
+  EXPECT_THAT(db()->GetAllRows(), ElementsAre(leaked_credentials1));
+}
+
+TEST_F(LeakedCredentialsTableTest, BadURL) {
+  test_data().url = GURL("bad");
+  EXPECT_FALSE(db()->AddRow(test_data()));
+  EXPECT_THAT(db()->GetAllRows(), IsEmpty());
+  EXPECT_FALSE(db()->RemoveRow(test_data().url, test_data().username));
+}
+
+TEST_F(LeakedCredentialsTableTest, EmptyURL) {
+  test_data().url = GURL();
+  EXPECT_FALSE(db()->AddRow(test_data()));
+  EXPECT_THAT(db()->GetAllRows(), IsEmpty());
+  EXPECT_FALSE(db()->RemoveRow(test_data().url, test_data().username));
+}
+
+}  // namespace
+}  // namespace password_manager
diff --git a/components/policy/BUILD.gn b/components/policy/BUILD.gn
index 353e8e40..c0cad6e3 100644
--- a/components/policy/BUILD.gn
+++ b/components/policy/BUILD.gn
@@ -72,6 +72,16 @@
 cloud_policy_full_runtime_proto_path =
     "$target_gen_dir/proto/cloud_policy_full_runtime.proto"
 
+# This protobuf contains the common definitions of the shared messages
+# between user and device policies
+policy_common_definitions_proto_abspath =
+    "//components/policy/proto/policy_common_definitions.proto"
+
+# This file is used by tools/traffic_annotation/traffic_annotation.proto as it
+# needs a version without LITE_RUNTIME optimization.
+policy_common_definitions_full_runtime_proto_path =
+    "$target_gen_dir/proto/policy_common_definitions_full_runtime.proto"
+
 # This is the "full" protobuf, which defines one protobuf message per
 # policy. It is also the format currently used by the server.
 chrome_settings_proto_path = "$target_gen_dir/proto/chrome_settings.proto"
@@ -86,7 +96,7 @@
 app_restrictions_path = "$target_gen_dir/app_restrictions.xml"
 risk_tag_header_path = "$target_gen_dir/risk_tag.h"
 
-action("cloud_policy_code_generate") {
+action("policy_code_generate") {
   script = "tools/generate_policy_source.py"
   chrome_version_abspath = "//chrome/VERSION"
   chrome_version_path = rebase_path(chrome_version_abspath, root_build_dir)
@@ -142,6 +152,7 @@
   outputs = [
     cloud_policy_full_runtime_proto_path,
     chrome_settings_full_runtime_proto_path,
+    policy_common_definitions_full_runtime_proto_path,
   ]
 
   args = [
@@ -156,6 +167,11 @@
         rebase_path(cloud_policy_full_runtime_proto_path, root_build_dir),
     "--chrome-settings-full-runtime-protobuf=" +
         rebase_path(chrome_settings_full_runtime_proto_path, root_build_dir),
+    "--policy-common-definitions-protobuf=" +
+        rebase_path(policy_common_definitions_proto_abspath, root_build_dir),
+    "--policy-common-definitions-full-runtime-protobuf=" +
+        rebase_path(policy_common_definitions_full_runtime_proto_path,
+                    root_build_dir),
   ]
 }
 
@@ -282,23 +298,22 @@
   ]
 }
 proto_library("cloud_policy_proto_generated_compile_proto") {
-  visibility = [
-    ":cloud_policy_proto_generated_compile",
-    ":chrome_settings_proto_generated_compile",
-    ":chrome_settings_proto_generated_compile_proto",
-    ":chrome_settings_proto_generated_compile_proto_gen",
-  ]
+  visibility = [ ":cloud_policy_proto_generated_compile" ]
+
   sources = [
     cloud_policy_proto_path,
   ]
 
+  import_dirs = [ "//components/policy/proto" ]
   proto_out_dir = "components/policy/proto"
   cc_generator_options = "dllexport_decl=POLICY_PROTO_EXPORT:"
   cc_include = "components/policy/proto/policy_proto_export.h"
   component_build_force_source_set = true
   defines = [ "POLICY_PROTO_COMPILATION" ]
 
-  proto_deps = [ ":cloud_policy_code_generate" ]
+  link_deps =
+      [ "//components/policy/proto:policy_common_definitions_compile_proto" ]
+  proto_deps = [ ":policy_code_generate" ]
 }
 
 # This target builds the "full" protobuf, used for tests only.
@@ -306,25 +321,26 @@
   testonly = true
   public_deps = [
     ":chrome_settings_proto_generated_compile_proto",
-    ":cloud_policy_proto_generated_compile",
   ]
 }
 proto_library("chrome_settings_proto_generated_compile_proto") {
   testonly = true
   visibility = [ ":chrome_settings_proto_generated_compile" ]
+
   sources = [
     chrome_settings_proto_path,
   ]
 
+  import_dirs = [ "//components/policy/proto" ]
   proto_out_dir = "components/policy/proto"
   cc_generator_options = "dllexport_decl=POLICY_CHROME_SETTINGS_PROTO_EXPORT:"
   cc_include = "components/policy/proto/policy_proto_export.h"
   component_build_force_source_set = true
   defines = [ "POLICY_CHROME_SETTINGS_PROTO_COMPILATION" ]
 
-  proto_deps = [ ":cloud_policy_code_generate" ]
-
-  link_deps = [ ":cloud_policy_proto_generated_compile" ]
+  link_deps =
+      [ "//components/policy/proto:policy_common_definitions_compile_proto" ]
+  proto_deps = [ ":policy_code_generate" ]
 }
 
 static_library("generated") {
@@ -336,10 +352,11 @@
 
   defines = [ "POLICY_COMPONENT_IMPLEMENTATION" ]
   public_deps = [
-    ":cloud_policy_code_generate",
     ":cloud_policy_proto_generated_compile",
+    ":policy_code_generate",
     "//base",
     "//components/policy/core/common:common_constants",
+    "//components/policy/proto:policy_common_definitions_compile_proto",
     "//third_party/protobuf:protobuf_lite",
   ]
   deps = [
@@ -360,7 +377,7 @@
       "$_generated_resources_dir/xml-v21/app_restrictions.xml",
     ]
     deps = [
-      ":cloud_policy_code_generate",
+      ":policy_code_generate",
       ":policy_templates",
     ]
   }
diff --git a/components/policy/proto/BUILD.gn b/components/policy/proto/BUILD.gn
index a7039ac9..66358133 100644
--- a/components/policy/proto/BUILD.gn
+++ b/components/policy/proto/BUILD.gn
@@ -14,6 +14,21 @@
   ]
 }
 
+proto_library("policy_common_definitions_compile_proto") {
+  visibility = [
+    "//components/policy:cloud_policy_proto_generated_compile_proto",
+    "//components/policy:chrome_settings_proto_generated_compile_proto",
+    "//components/policy:generated",
+    ":proto_internal",
+  ]
+
+  sources = [
+    "policy_common_definitions.proto",
+  ]
+
+  proto_out_dir = "components/policy/proto"
+}
+
 proto_library("proto_internal") {
   visibility = [ ":proto" ]
 
@@ -33,6 +48,7 @@
     sources += [ "chrome_extension_policy.proto" ]
   }
 
+  link_deps = [ ":policy_common_definitions_compile_proto" ]
   cc_generator_options = "dllexport_decl=POLICY_PROTO_EXPORT:"
   cc_include = "components/policy/proto/policy_proto_export.h"
   component_build_force_source_set = true
diff --git a/components/policy/proto/chrome_device_policy.proto b/components/policy/proto/chrome_device_policy.proto
index 26d16b03..6cd7d79a 100644
--- a/components/policy/proto/chrome_device_policy.proto
+++ b/components/policy/proto/chrome_device_policy.proto
@@ -8,54 +8,7 @@
 
 package enterprise_management;
 
-// This message should be kept in sync with StringList message definition in the
-// user policy proto.
-message DeviceStringList {
-  repeated string entries = 1;
-}
-
-// TODO(http://crbug.com/552439) move all of these common proto definitions of
-// user and device policies into a common proto file. This message should be
-// kept in sync with PolicyOptions message definition in the user policy proto.
-message DevicePolicyOptions {
-  enum PolicyMode {
-    // The given settings are applied regardless of user choice.
-    MANDATORY = 0;
-    // The user may choose to override the given settings.
-    RECOMMENDED = 1;
-    // No policy value is present and the policy should be ignored.
-    UNSET = 2;
-  }
-  optional PolicyMode mode = 1 [default = MANDATORY];
-}
-
-// This message should be kept in sync with BooleanPolicyProto message
-// definition in the user policy proto.
-message DeviceBooleanPolicyProto {
-  optional DevicePolicyOptions policy_options = 1;
-  optional bool value = 2;
-}
-
-// This message should be kept in sync with IntegerPolicyProto message
-// definition in the user policy proto.
-message DeviceIntegerPolicyProto {
-  optional DevicePolicyOptions policy_options = 1;
-  optional int64 value = 2;
-}
-
-// This message should be kept in sync with StringPolicyProto message
-// definition in the user policy proto.
-message DeviceStringPolicyProto {
-  optional DevicePolicyOptions policy_options = 1;
-  optional string value = 2;
-}
-
-// This message should be kept in sync with StringListPolicyProto message
-// definition in the user policy proto.
-message DeviceStringListPolicyProto {
-  optional DevicePolicyOptions policy_options = 1;
-  optional DeviceStringList value = 2;
-}
+import "policy_common_definitions.proto";
 
 message DevicePolicyRefreshRateProto {
   // In milliseconds.
@@ -633,17 +586,49 @@
   // screen. If this policy is set to true, the large cursor will be enabled
   // when the login screen is shown. If this policy is set to false, the large
   // cursor will be disabled when the login screen is shown. If the
-  // DevicePolicyOptions mode was being mandatory then the user won't be able to
-  // change these settings. Only if DevicePolicyOptions was being set as
+  // PolicyOptions mode was being mandatory then the user won't be able to
+  // change these settings. Only if PolicyOptions was being set as recommended
+  // users can temporarily override this setting by enabling or disabling the
+  // large cursor. However, the user's choice is not persistent and the default
+  // is restored whenever the login screen is shown anew or the user remains
+  // idle on the login screen for a minute. If this policy is left unset, the
+  // large cursor is disabled when the login screen is first shown. Users can
+  // enable or disable the large cursor anytime and its status on the login
+  // screen is persisted between users.
+  optional bool login_screen_large_cursor_enabled = 6;
+  optional PolicyOptions login_screen_large_cursor_enabled_options = 7;
+
+  // Sets the state of the spoken feedback accessibility feature on the login
+  // screen. If this policy is set to true, the spoken feedback will be enabled
+  // when the login screen is shown. If this policy is set to false, the spoken
+  // feedback will be disabled when the spoken feedback is shown. If the
+  // PolicyOptions mode was being mandatory then the user won't be able to
+  // change these settings. Only if PolicyOptions was being set as
   // recommended users can temporarily override this setting by enabling or
-  // disabling the large cursor. However, the user's choice is not persistent
+  // disabling the spoken feedback. However, the user's choice is not persistent
   // and the default is restored whenever the login screen is shown anew or the
   // user remains idle on the login screen for a minute. If this policy is left
-  // unset, the large cursor is disabled when the login screen is first shown.
-  // Users can enable or disable the large cursor anytime and its status on the
-  // login screen is persisted between users.
-  optional bool login_screen_large_cursor_enabled = 6;
-  optional DevicePolicyOptions login_screen_large_cursor_enabled_options = 7;
+  // unset, the spoken feedback is disabled when the login screen is first
+  // shown. Users can enable or disable the spoken feedback anytime and its
+  // status on the login screen is persisted between users.
+  optional bool login_screen_spoken_feedback_enabled = 8;
+  optional PolicyOptions login_screen_spoken_feedback_enabled_options = 9;
+
+  // Sets the state of the high contrast accessibility feature on the login
+  // screen. If this policy is set to true, the high contrast will be enabled
+  // when the login screen is shown. If this policy is set to false, the spoken
+  // feedback will be disabled when the high contrast is shown. If the
+  // PolicyOptions mode was being mandatory then the user won't be able to
+  // change these settings. Only if PolicyOptions was being set as
+  // recommended users can temporarily override this setting by enabling or
+  // disabling the high contrast. However, the user's choice is not persistent
+  // and the default is restored whenever the login screen is shown anew or the
+  // user remains idle on the login screen for a minute. If this policy is left
+  // unset, the high contrast is disabled when the login screen is first
+  // shown. Users can enable or disable the high contrast anytime and its
+  // status on the login screen is persisted between users.
+  optional bool login_screen_high_contrast_enabled = 10;
+  optional PolicyOptions login_screen_high_contrast_enabled_options = 11;
 }
 
 message SupervisedUsersSettingsProto {
diff --git a/components/policy/proto/policy_common_definitions.proto b/components/policy/proto/policy_common_definitions.proto
new file mode 100644
index 0000000..274ae91
--- /dev/null
+++ b/components/policy/proto/policy_common_definitions.proto
@@ -0,0 +1,45 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+syntax = "proto2";
+
+option optimize_for = LITE_RUNTIME;
+
+package enterprise_management;
+
+message StringList {
+  repeated string entries = 1;
+}
+
+message PolicyOptions {
+  enum PolicyMode {
+    // The given settings are applied regardless of user choice.
+    MANDATORY = 0;
+    // The user may choose to override the given settings.
+    RECOMMENDED = 1;
+    // No policy value is present and the policy should be ignored.
+    UNSET = 2;
+  }
+  optional PolicyMode mode = 1 [default = MANDATORY];
+}
+
+message BooleanPolicyProto {
+  optional PolicyOptions policy_options = 1;
+  optional bool value = 2;
+}
+
+message IntegerPolicyProto {
+  optional PolicyOptions policy_options = 1;
+  optional int64 value = 2;
+}
+
+message StringPolicyProto {
+  optional PolicyOptions policy_options = 1;
+  optional string value = 2;
+}
+
+message StringListPolicyProto {
+  optional PolicyOptions policy_options = 1;
+  optional StringList value = 2;
+}
\ No newline at end of file
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json
index c2c5aee..18d7a7d 100644
--- a/components/policy/resources/policy_templates.json
+++ b/components/policy/resources/policy_templates.json
@@ -641,6 +641,9 @@
         'DeviceLoginScreenDefaultHighContrastEnabled',
         'DeviceLoginScreenDefaultVirtualKeyboardEnabled',
         'DeviceLoginScreenDefaultScreenMagnifierType',
+        'DeviceLoginScreenLargeCursorEnabled',
+        'DeviceLoginScreenSpokenFeedbackEnabled',
+        'DeviceLoginScreenHighContrastEnabled',
       ],
     },
     {
@@ -10164,7 +10167,34 @@
 
           If you set this policy, users can temporarily override it by enabling or disabling spoken feedback. However, the user's choice is not persistent and the default is restored whenever the login screen is shown anew or the user remains idle on the login screen for a minute.
 
-          If this policy is left unset, spoken feedback is disabled when the login screen is first shown. Users can enable or disable spoken feedback anytime and its status on the login screen is persisted between users.''',
+          If this policy is left unset, spoken feedback is disabled when the login screen is first shown. Users can enable or disable spoken feedback anytime and its status on the login screen is persisted between users.
+
+          Note: <ph name="DEVICE_LOGIN_SCREEN_SPOKEN_FEEDBACK_ENABLED_POLICY_NAME">DeviceLoginScreenSpokenFeedbackEnabled</ph> overrides this policy if the former is specified.''',
+    },
+    {
+      'name': 'DeviceLoginScreenSpokenFeedbackEnabled',
+      'owners': ['amraboelkher@chromium.org', 'emaxx@chromium.org'],
+      'type': 'main',
+      'schema': { 'type': 'boolean' },
+      'supported_on': ['chrome_os:79-'],
+      'device_only': True,
+      'features': {
+        'can_be_recommended': True,
+        'dynamic_refresh': True,
+      },
+      'example_value': True,
+      'id': 605,
+      'caption': '''Enable the spoken feedback on the login screen''',
+      'tags': [],
+      'desc': '''Enable the spoken feedback accessibility feature on the login screen.
+
+          If this policy is set to true, the spoken feedback will always be enabled on the login screen.
+
+          If this policy is set to false, the spoken feedback will always be disabled on the login screen.
+
+          If you set this policy, users cannot change or override it.
+
+          If this policy is left unset, the spoken feedback is disabled on the login screen initially but can be enabled by the user anytime.''',
     },
     {
       'name': 'DeviceLoginScreenDefaultHighContrastEnabled',
@@ -10188,7 +10218,34 @@
 
           If you set this policy, users can temporarily override it by enabling or disabling high contrast mode. However, the user's choice is not persistent and the default is restored whenever the login screen is shown anew or the user remains idle on the login screen for a minute.
 
-          If this policy is left unset, high contrast mode is disabled when the login screen is first shown. Users can enable or disable high contrast mode anytime and its status on the login screen is persisted between users.''',
+          If this policy is left unset, high contrast mode is disabled when the login screen is first shown. Users can enable or disable high contrast mode anytime and its status on the login screen is persisted between users.
+
+          Note: <ph name="DEVICE_LOGIN_SCREEN_HIGH_CONTRAST_ENABLED_POLICY_NAME">DeviceLoginScreenHighContrastEnabled</ph> overrides this policy if the former is specified.''',
+    },
+    {
+      'name': 'DeviceLoginScreenHighContrastEnabled',
+      'owners': ['amraboelkher@chromium.org', 'emaxx@chromium.org'],
+      'type': 'main',
+      'schema': { 'type': 'boolean' },
+      'supported_on': ['chrome_os:79-'],
+      'device_only': True,
+      'features': {
+        'can_be_recommended': True,
+        'dynamic_refresh': True,
+      },
+      'example_value': True,
+      'id': 606,
+      'caption': '''Enable the high contrast on the login screen''',
+      'tags': [],
+      'desc': '''Enable the high contrast accessibility feature on the login screen.
+
+          If this policy is set to true, the high contrast will always be enabled on the login screen.
+
+          If this policy is set to false, the high contrast will always be disabled on the login screen.
+
+          If you set this policy, users cannot change or override it.
+
+          If this policy is left unset, the high contrast is disabled on the login screen initially but can be enabled by the user anytime.''',
     },
     {
       'name': 'DeviceLoginScreenDefaultVirtualKeyboardEnabled',
@@ -17990,8 +18047,10 @@
     'DeviceAutoUpdateP2PEnabled': 'auto_update_settings.p2p_enabled',
     'DeviceLoginScreenDefaultLargeCursorEnabled': 'accessibility_settings.login_screen_default_large_cursor_enabled',
     'DeviceLoginScreenLargeCursorEnabled': 'accessibility_settings.login_screen_large_cursor_enabled',
+    'DeviceLoginScreenSpokenFeedbackEnabled': 'accessibility_settings.login_screen_spoken_feedback_enabled',
     'DeviceLoginScreenDefaultSpokenFeedbackEnabled': 'accessibility_settings.login_screen_default_spoken_feedback_enabled',
     'DeviceLoginScreenDefaultHighContrastEnabled': 'accessibility_settings.login_screen_default_high_contrast_enabled',
+    'DeviceLoginScreenHighContrastEnabled': 'accessibility_settings.login_screen_high_contrast_enabled',
     'DeviceLoginScreenDefaultScreenMagnifierType': 'accessibility_settings.login_screen_default_screen_magnifier_type',
     'DeviceLoginScreenDefaultVirtualKeyboardEnabled': 'accessibility_settings.login_screen_default_virtual_keyboard_enabled',
     'AttestationEnabledForDevice': 'attestation_settings.attestation_enabled',
@@ -18494,6 +18553,6 @@
   ],
   'placeholders': [],
   'deleted_policy_ids': [412, 546, 562, 569],
-  'highest_id_currently_used': 604,
+  'highest_id_currently_used': 606,
   'highest_atomic_group_id_currently_used': 37
 }
diff --git a/components/policy/test_support/policy_testserver.py b/components/policy/test_support/policy_testserver.py
index 0c1f76fa..954022d 100644
--- a/components/policy/test_support/policy_testserver.py
+++ b/components/policy/test_support/policy_testserver.py
@@ -99,6 +99,7 @@
 
 import device_management_backend_pb2 as dm
 import cloud_policy_pb2 as cp
+import policy_common_definitions_pb2 as cd
 
 # Policy for extensions is not supported on Android.
 try:
@@ -1031,16 +1032,16 @@
 
       # Look for this policy's value in the mandatory or recommended dicts.
       if field.name in policies.get('mandatory', {}):
-        mode = cp.PolicyOptions.MANDATORY
+        mode = cd.PolicyOptions.MANDATORY
         value = policies['mandatory'][field.name]
       elif field.name in policies.get('recommended', {}):
-        mode = cp.PolicyOptions.RECOMMENDED
+        mode = cd.PolicyOptions.RECOMMENDED
         value = policies['recommended'][field.name]
       else:
         continue
 
       # Create protobuf message for this policy.
-      policy_message = eval('cp.' + field.message_type.name + '()')
+      policy_message = eval('cd.' + field.message_type.name + '()')
       policy_message.policy_options.mode = mode
       field_descriptor = policy_message.DESCRIPTOR.fields_by_name['value']
       self.SetProtobufMessageField(policy_message, field_descriptor, value)
diff --git a/components/policy/tools/generate_policy_source.py b/components/policy/tools/generate_policy_source.py
index 28db4dd2..f785f18 100755
--- a/components/policy/tools/generate_policy_source.py
+++ b/components/policy/tools/generate_policy_source.py
@@ -242,6 +242,16 @@
       help='generate chrome settings protobuf file',
       metavar='FILE')
   parser.add_option(
+      '--policy-common-definitions-protobuf',
+      dest='policy_common_definitions_proto_path',
+      help='policy common definitions protobuf file path',
+      metavar='FILE')
+  parser.add_option(
+      '--policy-common-definitions-full-runtime-protobuf',
+      dest='policy_common_definitions_full_runtime_proto_path',
+      help='generate policy common definitions full runtime protobuf file',
+      metavar='FILE')
+  parser.add_option(
       '--csfrp',
       '--chrome-settings-full-runtime-protobuf',
       dest='chrome_settings_full_runtime_proto_path',
@@ -371,6 +381,12 @@
     GenerateFile(opts.risk_header_path, _WritePolicyRiskTagHeader)
   if opts.cloud_policy_proto_path:
     GenerateFile(opts.cloud_policy_proto_path, _WriteCloudPolicyProtobuf)
+  if (opts.policy_common_definitions_full_runtime_proto_path and
+      opts.policy_common_definitions_proto_path):
+    GenerateFile(
+        opts.policy_common_definitions_full_runtime_proto_path,
+        partial(_WritePolicyCommonDefinitionsFullRuntimeProtobuf,
+                opts.policy_common_definitions_proto_path))
   if opts.cloud_policy_full_runtime_proto_path:
     GenerateFile(opts.cloud_policy_full_runtime_proto_path,
                  _WriteCloudPolicyFullRuntimeProtobuf)
@@ -1327,7 +1343,7 @@
 package enterprise_management;
 
 // For StringList and PolicyOptions.
-import "cloud_policy.proto";
+import "policy_common_definitions.proto";
 
 '''
 
@@ -1338,42 +1354,7 @@
 
 package enterprise_management;
 
-message StringList {
-  repeated string entries = 1;
-}
-
-message PolicyOptions {
-  enum PolicyMode {
-    // The given settings are applied regardless of user choice.
-    MANDATORY = 0;
-    // The user may choose to override the given settings.
-    RECOMMENDED = 1;
-    // No policy value is present and the policy should be ignored.
-    UNSET = 2;
-  }
-  optional PolicyMode mode = 1 [default = MANDATORY];
-}
-
-message BooleanPolicyProto {
-  optional PolicyOptions policy_options = 1;
-  optional bool value = 2;
-}
-
-message IntegerPolicyProto {
-  optional PolicyOptions policy_options = 1;
-  optional int64 value = 2;
-}
-
-message StringPolicyProto {
-  optional PolicyOptions policy_options = 1;
-  optional string value = 2;
-}
-
-message StringListPolicyProto {
-  optional PolicyOptions policy_options = 1;
-  optional StringList value = 2;
-}
-
+import "policy_common_definitions.proto";
 '''
 
 # Field IDs [1..RESERVED_IDS] will not be used in the wrapping protobuf.
@@ -1432,7 +1413,9 @@
           "option optimize_for = LITE_RUNTIME;",
           "//option optimize_for = LITE_RUNTIME;").replace(
               "import \"cloud_policy.proto\";",
-              "import \"cloud_policy_full_runtime.proto\";"))
+              "import \"cloud_policy_full_runtime.proto\";").replace(
+                  "import \"policy_common_definitions.proto\";",
+                  "import \"policy_common_definitions_full_runtime.proto\";"))
   fields = []
   f.write('// PBs for individual settings.\n\n')
   for policy in policies:
@@ -1464,8 +1447,11 @@
                                          target_platform, f, risk_tags):
   # For full runtime, disable LITE_RUNTIME switch
   f.write(
-      CLOUD_POLICY_PROTO_HEAD.replace("option optimize_for = LITE_RUNTIME;",
-                                      "//option optimize_for = LITE_RUNTIME;"))
+      CLOUD_POLICY_PROTO_HEAD.replace(
+          "option optimize_for = LITE_RUNTIME;",
+          "//option optimize_for = LITE_RUNTIME;").replace(
+              "import \"policy_common_definitions.proto\";",
+              "import \"policy_common_definitions_full_runtime.proto\";"))
   f.write('message CloudPolicySettings {\n')
   for policy in policies:
     if policy.is_supported and not policy.is_device_only:
@@ -1475,6 +1461,18 @@
   f.write('}\n\n')
 
 
+def _WritePolicyCommonDefinitionsFullRuntimeProtobuf(
+    policy_common_definitions_proto_path, policies, policy_atomic_groups,
+    target_platform, f, risk_tags):
+  # For full runtime, disable LITE_RUNTIME switch
+  with open(policy_common_definitions_proto_path, 'r') as proto_file:
+    policy_common_definitions_proto_code = proto_file.read()
+  f.write(
+      policy_common_definitions_proto_code.replace(
+          "option optimize_for = LITE_RUNTIME;",
+          "//option optimize_for = LITE_RUNTIME;"))
+
+
 #------------------ Chrome OS policy constants header --------------#
 
 # This code applies to Active Directory management only.
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc
index 4b77677a..97fb26be 100644
--- a/components/printing/renderer/print_render_frame_helper.cc
+++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -368,10 +368,7 @@
 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
 // Returns true if the current destination printer is PRINT_TO_PDF.
 bool IsPrintToPdfRequested(const base::DictionaryValue& job_settings) {
-  bool print_to_pdf = false;
-  if (!job_settings.GetBoolean(kSettingPrintToPDF, &print_to_pdf))
-    NOTREACHED();
-  return print_to_pdf;
+  return job_settings.FindBoolKey(kSettingPrintToPDF).value();
 }
 
 bool PrintingFrameHasPageSizeStyle(blink::WebLocalFrame* frame,
@@ -449,11 +446,13 @@
 }
 
 bool FitToPageEnabled(const base::DictionaryValue& job_settings) {
-  bool fit_to_paper_size = false;
-  if (!job_settings.GetBoolean(kSettingFitToPageEnabled, &fit_to_paper_size)) {
-    NOTREACHED();
-  }
-  return fit_to_paper_size;
+  return job_settings.FindBoolKey(kSettingFitToPageEnabled).value();
+}
+
+bool FitToPaperEnabled(const base::DictionaryValue& job_settings) {
+  // TODO(dhoss): Bug 989978: Should have a value. Will fix when
+  // |job_settings| contains a "fitToPaperEnabled" boolean field.
+  return job_settings.FindBoolKey(kSettingFitToPaperEnabled).value_or(false);
 }
 
 // Returns the print scaling option to retain/scale/crop the source page size
@@ -480,12 +479,20 @@
     return blink::kWebPrintScalingOptionSourceSize;
 
   if (!source_is_html) {
-    if (!FitToPageEnabled(job_settings))
+    bool fit_to_page = FitToPageEnabled(job_settings);
+    bool fit_to_paper = FitToPaperEnabled(job_settings);
+
+    // The following conditions are ordered for an optimization that avoids
+    // calling PDFShouldDisableScaling(), which has to make a call using PPAPI.
+    if (!fit_to_page && !fit_to_paper)
       return blink::kWebPrintScalingOptionNone;
 
     bool no_plugin_scaling = PDFShouldDisableScaling(frame, node, params, true);
     if (params.is_first_request && no_plugin_scaling)
       return blink::kWebPrintScalingOptionNone;
+
+    if (fit_to_paper)
+      return blink::kWebPrintScalingOptionFitToPaper;
   }
   return blink::kWebPrintScalingOptionFitToPrintableArea;
 }
@@ -721,21 +728,21 @@
   ExecuteScript(frame, kPageLoadScriptFormat, html);
 
   auto options = std::make_unique<base::DictionaryValue>();
-  options->SetDouble(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
-  options->SetDouble("width", page_size.width);
-  options->SetDouble("height", page_size.height);
-  options->SetDouble("topMargin", page_layout.margin_top);
-  options->SetDouble("bottomMargin", page_layout.margin_bottom);
-  options->SetDouble("leftMargin", page_layout.margin_left);
-  options->SetDouble("rightMargin", page_layout.margin_right);
-  options->SetInteger("pageNumber", page_number);
-  options->SetInteger("totalPages", total_pages);
-  options->SetString("url", params.url);
+  options->SetDoubleKey(kSettingHeaderFooterDate, base::Time::Now().ToJsTime());
+  options->SetDoubleKey("width", page_size.width);
+  options->SetDoubleKey("height", page_size.height);
+  options->SetDoubleKey("topMargin", page_layout.margin_top);
+  options->SetDoubleKey("bottomMargin", page_layout.margin_bottom);
+  options->SetDoubleKey("leftMargin", page_layout.margin_left);
+  options->SetDoubleKey("rightMargin", page_layout.margin_right);
+  options->SetIntKey("pageNumber", page_number);
+  options->SetIntKey("totalPages", total_pages);
+  options->SetStringKey("url", params.url);
   base::string16 title = source_frame.GetDocument().Title().Utf16();
-  options->SetString("title", title.empty() ? params.title : title);
-  options->SetString("headerTemplate", params.header_template);
-  options->SetString("footerTemplate", params.footer_template);
-  options->SetBoolean("isRtl", base::i18n::IsRTL());
+  options->SetStringKey("title", title.empty() ? params.title : title);
+  options->SetStringKey("headerTemplate", params.header_template);
+  options->SetStringKey("footerTemplate", params.footer_template);
+  options->SetBoolKey("isRtl", base::i18n::IsRTL());
 
   ExecuteScript(frame, kPageSetupScriptFormat, *options);
 
@@ -1275,10 +1282,9 @@
 
 void PrintRenderFrameHelper::UpdateFrameMarginsCssInfo(
     const base::DictionaryValue& settings) {
-  int margins_type = 0;
-  if (!settings.GetInteger(kSettingMarginsType, &margins_type))
-    margins_type = DEFAULT_MARGINS;
-  ignore_css_margins_ = (margins_type != DEFAULT_MARGINS);
+  base::Optional<int> margins_type = settings.FindIntKey(kSettingMarginsType);
+  ignore_css_margins_ =
+      margins_type.value_or(DEFAULT_MARGINS) != DEFAULT_MARGINS;
 }
 
 #if BUILDFLAG(ENABLE_PRINT_PREVIEW)
@@ -2004,8 +2010,8 @@
     job_settings = &passed_job_settings;
   } else {
     modified_job_settings.MergeDictionary(&passed_job_settings);
-    modified_job_settings.SetBoolean(kSettingHeaderFooterEnabled, false);
-    modified_job_settings.SetInteger(kSettingMarginsType, NO_MARGINS);
+    modified_job_settings.SetBoolKey(kSettingHeaderFooterEnabled, false);
+    modified_job_settings.SetIntKey(kSettingMarginsType, NO_MARGINS);
     job_settings = &modified_job_settings;
   }
 
@@ -2022,6 +2028,7 @@
     return false;
   }
 
+  // TODO(dhoss): Replace deprecated base::DictionaryValue::Get<Type>() calls
   if (!job_settings->GetInteger(kPreviewUIID, &settings.params.preview_ui_id)) {
     NOTREACHED();
     print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING);
diff --git a/components/printing/test/print_mock_render_thread.cc b/components/printing/test/print_mock_render_thread.cc
index dba264f..b126747b 100644
--- a/components/printing/test/print_mock_render_thread.cc
+++ b/components/printing/test/print_mock_render_thread.cc
@@ -133,73 +133,80 @@
     *canceled = false;
   // Check and make sure the required settings are all there.
   // We don't actually care about the values.
-  std::string dummy_string;
-  int margins_type = 0;
-  if (!job_settings.GetBoolean(printing::kSettingLandscape, nullptr) ||
-      !job_settings.GetBoolean(printing::kSettingCollate, nullptr) ||
-      !job_settings.GetInteger(printing::kSettingColor, nullptr) ||
-      !job_settings.GetBoolean(printing::kSettingPrintToPDF, nullptr) ||
-      !job_settings.GetBoolean(printing::kIsFirstRequest, nullptr) ||
-      !job_settings.GetString(printing::kSettingDeviceName, &dummy_string) ||
-      !job_settings.GetInteger(printing::kSettingDuplexMode, nullptr) ||
-      !job_settings.GetInteger(printing::kSettingCopies, nullptr) ||
-      !job_settings.GetInteger(printing::kPreviewUIID, nullptr) ||
-      !job_settings.GetInteger(printing::kPreviewRequestID, nullptr) ||
-      !job_settings.GetInteger(printing::kSettingMarginsType, &margins_type)) {
+  base::Optional<int> margins_type =
+      job_settings.FindIntKey(printing::kSettingMarginsType);
+  if (!margins_type.has_value() ||
+      !job_settings.FindBoolKey(printing::kSettingLandscape) ||
+      !job_settings.FindBoolKey(printing::kSettingCollate) ||
+      !job_settings.FindIntKey(printing::kSettingColor) ||
+      !job_settings.FindBoolKey(printing::kSettingPrintToPDF) ||
+      !job_settings.FindBoolKey(printing::kIsFirstRequest) ||
+      !job_settings.FindStringKey(printing::kSettingDeviceName) ||
+      !job_settings.FindIntKey(printing::kSettingDuplexMode) ||
+      !job_settings.FindIntKey(printing::kSettingCopies) ||
+      !job_settings.FindIntKey(printing::kPreviewUIID) ||
+      !job_settings.FindIntKey(printing::kPreviewRequestID)) {
     return;
   }
 
   // Just return the default settings.
-  const base::ListValue* page_range_array;
+  const base::Value* page_range =
+      job_settings.FindListKey(printing::kSettingPageRange);
   printing::PageRanges new_ranges;
-  if (job_settings.GetList(printing::kSettingPageRange, &page_range_array)) {
-    for (size_t index = 0; index < page_range_array->GetSize(); ++index) {
-      const base::DictionaryValue* dict;
-      if (!page_range_array->GetDictionary(index, &dict))
+  if (page_range) {
+    for (const base::Value& dict : page_range->GetList()) {
+      if (!dict.is_dict())
         continue;
-      printing::PageRange range;
-      if (!dict->GetInteger(printing::kSettingPageRangeFrom, &range.from) ||
-          !dict->GetInteger(printing::kSettingPageRangeTo, &range.to)) {
+
+      base::Optional<int> range_from =
+          dict.FindIntKey(printing::kSettingPageRangeFrom);
+      base::Optional<int> range_to =
+          dict.FindIntKey(printing::kSettingPageRangeTo);
+      if (!range_from || !range_to)
         continue;
-      }
+
       // Page numbers are 1-based in the dictionary.
       // Page numbers are 0-based for the printing context.
-      range.from--;
-      range.to--;
+      printing::PageRange range;
+      range.from = range_from.value() - 1;
+      range.to = range_to.value() - 1;
       new_ranges.push_back(range);
     }
   }
 
   // Get media size
-  const base::DictionaryValue* media_size_value = nullptr;
+  const base::Value* media_size_value =
+      job_settings.FindDictKey(printing::kSettingMediaSize);
   gfx::Size page_size;
-  if (job_settings.GetDictionary(printing::kSettingMediaSize,
-                                 &media_size_value)) {
-    int width_microns = 0;
-    int height_microns = 0;
-    if (media_size_value->GetInteger(printing::kSettingMediaSizeWidthMicrons,
-                                     &width_microns) &&
-        media_size_value->GetInteger(printing::kSettingMediaSizeHeightMicrons,
-                                     &height_microns)) {
+  if (media_size_value) {
+    base::Optional<int> width_microns =
+        media_size_value->FindIntKey(printing::kSettingMediaSizeWidthMicrons);
+    base::Optional<int> height_microns =
+        media_size_value->FindIntKey(printing::kSettingMediaSizeHeightMicrons);
+
+    if (width_microns && height_microns) {
       float device_microns_per_unit =
           static_cast<float>(printing::kMicronsPerInch) /
           printing::kDefaultPdfDpi;
-      page_size = gfx::Size(width_microns / device_microns_per_unit,
-                            height_microns / device_microns_per_unit);
+      page_size = gfx::Size(width_microns.value() / device_microns_per_unit,
+                            height_microns.value() / device_microns_per_unit);
     }
   }
 
   // Get scaling
-  int scale_factor = 100;
-  job_settings.GetInteger(printing::kSettingScaleFactor, &scale_factor);
+  base::Optional<int> setting_scale_factor =
+      job_settings.FindIntKey(printing::kSettingScaleFactor);
+  int scale_factor = setting_scale_factor.value_or(100);
 
   std::vector<int> pages(printing::PageRange::GetPages(new_ranges));
-  printer_->UpdateSettings(document_cookie, params, pages, margins_type,
+  printer_->UpdateSettings(document_cookie, params, pages, margins_type.value(),
                            page_size, scale_factor);
-  job_settings.GetBoolean(printing::kSettingShouldPrintSelectionOnly,
-                          &params->params.selection_only);
-  job_settings.GetBoolean(printing::kSettingShouldPrintBackgrounds,
-                          &params->params.should_print_backgrounds);
+  base::Optional<bool> selection_only =
+      job_settings.FindBoolKey(printing::kSettingShouldPrintSelectionOnly);
+  base::Optional<bool> should_print_backgrounds =
+      job_settings.FindBoolKey(printing::kSettingShouldPrintBackgrounds);
+  params->params.selection_only = selection_only.value();
+  params->params.should_print_backgrounds = should_print_backgrounds.value();
 }
 
 MockPrinter* PrintMockRenderThread::printer() {
diff --git a/components/signin/core/browser/about_signin_internals.cc b/components/signin/core/browser/about_signin_internals.cc
index 7291d86..20dcc82 100644
--- a/components/signin/core/browser/about_signin_internals.cc
+++ b/components/signin/core/browser/about_signin_internals.cc
@@ -606,8 +606,6 @@
   // A summary of signin related info first.
   base::ListValue* basic_info =
       AddSection(signin_info.get(), "Basic Information");
-  AddSectionEntry(basic_info, "Chrome Version",
-                  signin_client->GetProductVersion());
   AddSectionEntry(basic_info, "Account Consistency",
                   GetAccountConsistencyDescription(account_consistency));
   AddSectionEntry(
diff --git a/components/signin/internal/identity_manager/BUILD.gn b/components/signin/internal/identity_manager/BUILD.gn
index bfcb201..92030b8d 100644
--- a/components/signin/internal/identity_manager/BUILD.gn
+++ b/components/signin/internal/identity_manager/BUILD.gn
@@ -104,12 +104,14 @@
   if (is_ios) {
     configs += [ "//build/config/compiler:enable_arc" ]
 
+    deps += [ "//components/signin/public/identity_manager/ios" ]
+  }
+
+  if (is_ios || is_android) {
     sources += [
       "device_accounts_synchronizer_impl.cc",
       "device_accounts_synchronizer_impl.h",
     ]
-
-    deps += [ "//components/signin/public/identity_manager/ios" ]
   }
 }
 
diff --git a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc
index d2a4f923..1507e18 100644
--- a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc
+++ b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.cc
@@ -17,6 +17,16 @@
 
 DeviceAccountsSynchronizerImpl::~DeviceAccountsSynchronizerImpl() = default;
 
+#if defined(OS_ANDROID)
+void DeviceAccountsSynchronizerImpl::
+    ReloadAllAccountsFromSystemWithPrimaryAccount(
+        const CoreAccountId& primary_account_id) {
+  token_service_delegate_->ReloadAllAccountsFromSystemWithPrimaryAccount(
+      primary_account_id);
+}
+#endif
+
+#if defined(OS_IOS)
 void DeviceAccountsSynchronizerImpl::ReloadAllAccountsFromSystem() {
   token_service_delegate_->ReloadAllAccountsFromSystem();
 }
@@ -25,5 +35,6 @@
     const CoreAccountId& account_id) {
   token_service_delegate_->ReloadAccountFromSystem(account_id);
 }
+#endif
 
 }  // namespace signin
diff --git a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h
index 74679a0..f043b2a 100644
--- a/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h
+++ b/components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h
@@ -5,6 +5,7 @@
 #ifndef COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_IMPL_H_
 #define COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_IMPL_H_
 
+#include "build/build_config.h"
 #include "components/signin/public/identity_manager/device_accounts_synchronizer.h"
 
 class ProfileOAuth2TokenServiceDelegate;
@@ -19,8 +20,15 @@
   ~DeviceAccountsSynchronizerImpl() override;
 
   // DeviceAccountsSynchronizer implementation.
+#if defined(OS_ANDROID)
+  void ReloadAllAccountsFromSystemWithPrimaryAccount(
+      const CoreAccountId& primary_account_id) override;
+#endif
+
+#if defined(OS_IOS)
   void ReloadAllAccountsFromSystem() override;
   void ReloadAccountFromSystem(const CoreAccountId& account_id) override;
+#endif
 
  private:
   ProfileOAuth2TokenServiceDelegate* token_service_delegate_ = nullptr;
diff --git a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc
index d5aad257..ba2a161 100644
--- a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc
+++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.cc
@@ -463,8 +463,9 @@
   }
 }
 
-void OAuth2TokenServiceDelegateAndroid::ReloadAccountsFromSystem(
-    const CoreAccountId& primary_account_id) {
+void OAuth2TokenServiceDelegateAndroid::
+    ReloadAllAccountsFromSystemWithPrimaryAccount(
+        const CoreAccountId& primary_account_id) {
   // UpdateAccountList() effectively synchronizes the accounts in the Token
   // Service with those present at the system level.
   UpdateAccountList(primary_account_id, GetValidAccounts(),
diff --git a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h
index 00eedee..206734e5 100644
--- a/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h
+++ b/components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h
@@ -74,7 +74,7 @@
 
   void LoadCredentials(const CoreAccountId& primary_account_id) override;
 
-  void ReloadAccountsFromSystem(
+  void ReloadAllAccountsFromSystemWithPrimaryAccount(
       const CoreAccountId& primary_account_id) override;
 
  protected:
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.h b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.h
index 67b93772..219ec69 100644
--- a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.h
+++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.h
@@ -142,7 +142,7 @@
 
   // Triggers platform specific implementation for Android to reload accounts
   // from system.
-  virtual void ReloadAccountsFromSystem(
+  virtual void ReloadAllAccountsFromSystemWithPrimaryAccount(
       const CoreAccountId& primary_account_id) {}
 #endif
 
diff --git a/components/signin/public/base/signin_client.h b/components/signin/public/base/signin_client.h
index 88ecd18..578d4d5c 100644
--- a/components/signin/public/base/signin_client.h
+++ b/components/signin/public/base/signin_client.h
@@ -56,10 +56,6 @@
   // Returns the CookieManager for the client.
   virtual network::mojom::CookieManager* GetCookieManager() = 0;
 
-  // Returns a string containing the version info of the product in which the
-  // Signin component is being used.
-  virtual std::string GetProductVersion() = 0;
-
   // Called before Google sign-out started. Implementers must run the
   // |on_signout_decision_reached|, passing a SignoutDecision to allow/disallow
   // sign-out to continue. When to disallow sign-out is implementation specific.
diff --git a/components/signin/public/base/test_signin_client.cc b/components/signin/public/base/test_signin_client.cc
index cefecdd..d7a5567 100644
--- a/components/signin/public/base/test_signin_client.cc
+++ b/components/signin/public/base/test_signin_client.cc
@@ -70,10 +70,6 @@
   test_url_loader_factory_ = factory;
 }
 
-std::string TestSigninClient::GetProductVersion() {
-  return "";
-}
-
 void TestSigninClient::SetNetworkCallsDelayed(bool value) {
   network_calls_delayed_ = value;
 
diff --git a/components/signin/public/base/test_signin_client.h b/components/signin/public/base/test_signin_client.h
index 120f2881..009adc9 100644
--- a/components/signin/public/base/test_signin_client.h
+++ b/components/signin/public/base/test_signin_client.h
@@ -47,9 +47,6 @@
       base::OnceCallback<void(SignoutDecision)> on_signout_decision_reached,
       signin_metrics::ProfileSignout signout_source_metric) override;
 
-  // Returns the empty string.
-  std::string GetProductVersion() override;
-
   // Wraps the test_url_loader_factory().
   scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
 
diff --git a/components/signin/public/identity_manager/BUILD.gn b/components/signin/public/identity_manager/BUILD.gn
index 6d2a0b9..537e423e 100644
--- a/components/signin/public/identity_manager/BUILD.gn
+++ b/components/signin/public/identity_manager/BUILD.gn
@@ -24,12 +24,13 @@
     "identity_manager.h",
     "identity_manager_builder.cc",
     "identity_manager_builder.h",
+    "identity_mutator.cc",
+    "identity_mutator.h",
     "identity_utils.cc",
     "identity_utils.h",
     "load_credentials_state.h",
     "primary_account_access_token_fetcher.cc",
     "primary_account_access_token_fetcher.h",
-    "primary_account_mutator.cc",
     "primary_account_mutator.h",
     "set_accounts_in_cookie_result.h",
     "ubertoken_fetcher.cc",
diff --git a/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityMutator.java b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityMutator.java
index 172f5f3..311c8a3 100644
--- a/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityMutator.java
+++ b/components/signin/public/identity_manager/android/java/src/org/chromium/components/signin/identitymanager/IdentityMutator.java
@@ -10,23 +10,19 @@
 import org.chromium.components.signin.metrics.SignoutReason;
 
 /**
- * IdentityMutator is the write interface of IdentityManager, see identity_manager.h and
- * primary_account_mutator.h for more information.
+ * IdentityMutator is the write interface of IdentityManager, see identity_mutator.h for more
+ * information.
  */
 public class IdentityMutator {
     private static final String TAG = "IdentityMutator";
 
-    // Pointer to native PrimaryAccountMutator, not final because of destroy().
-    private long mNativePrimaryAccountMutator;
-    // Pointer to native IdentityManager, not final because of destroy().
-    private long mNativeIdentityManager;
+    // Pointer to native IdentityMutator, not final because of destroy().
+    private long mNativeIdentityMutator;
 
     @CalledByNative
-    private IdentityMutator(long nativePrimaryAccountMutator, long nativeIdentityManager) {
-        assert nativePrimaryAccountMutator != 0;
-        assert nativeIdentityManager != 0;
-        mNativePrimaryAccountMutator = nativePrimaryAccountMutator;
-        mNativeIdentityManager = nativeIdentityManager;
+    private IdentityMutator(long nativeIdentityMutator) {
+        assert nativeIdentityMutator != 0;
+        mNativeIdentityMutator = nativeIdentityMutator;
     }
 
     /**
@@ -34,8 +30,7 @@
      */
     @CalledByNative
     private void destroy() {
-        mNativeIdentityManager = 0;
-        mNativePrimaryAccountMutator = 0;
+        mNativeIdentityMutator = 0;
     }
 
     /**
@@ -47,7 +42,7 @@
      *   - there is not already a primary account set.
      */
     public boolean setPrimaryAccount(CoreAccountId accountId) {
-        return IdentityMutatorJni.get().setPrimaryAccount(mNativePrimaryAccountMutator, accountId);
+        return IdentityMutatorJni.get().setPrimaryAccount(mNativeIdentityMutator, accountId);
     }
 
     /**
@@ -57,23 +52,25 @@
     public boolean clearPrimaryAccount(@ClearAccountsAction int action,
             @SignoutReason int sourceMetric, @SignoutDelete int deleteMetric) {
         return IdentityMutatorJni.get().clearPrimaryAccount(
-                mNativePrimaryAccountMutator, action, sourceMetric, deleteMetric);
+                mNativeIdentityMutator, action, sourceMetric, deleteMetric);
     }
 
     /**
      * Reloads the accounts in the token service from the system accounts. This API calls
-     * ProfileOAuth2TokenServiceDelegate::ReloadAccountsFromSystem.
+     * ProfileOAuth2TokenServiceDelegate::ReloadAllAccountsFromSystemWithPrimaryAccount.
      */
-    public void reloadAccountsFromSystem() {
-        IdentityMutatorJni.get().reloadAccountsFromSystem(mNativeIdentityManager);
+    public void reloadAllAccountsFromSystemWithPrimaryAccount(CoreAccountId accountId) {
+        IdentityMutatorJni.get().reloadAllAccountsFromSystemWithPrimaryAccount(
+                mNativeIdentityMutator, accountId);
     }
 
     @NativeMethods
     interface Natives {
-        public boolean setPrimaryAccount(long nativePrimaryAccountMutator, CoreAccountId accountId);
-        public boolean clearPrimaryAccount(long nativePrimaryAccountMutator,
+        public boolean setPrimaryAccount(long nativeJniIdentityMutator, CoreAccountId accountId);
+        public boolean clearPrimaryAccount(long nativeJniIdentityMutator,
                 @ClearAccountsAction int action, @SignoutReason int sourceMetric,
                 @SignoutDelete int deleteMetric);
-        public void reloadAccountsFromSystem(long nativeIdentityManager);
+        public void reloadAllAccountsFromSystemWithPrimaryAccount(
+                long nativeJniIdentityMutator, CoreAccountId accountId);
     }
 }
diff --git a/components/signin/public/identity_manager/device_accounts_synchronizer.h b/components/signin/public/identity_manager/device_accounts_synchronizer.h
index bf99d7cb..a5ccc95a 100644
--- a/components/signin/public/identity_manager/device_accounts_synchronizer.h
+++ b/components/signin/public/identity_manager/device_accounts_synchronizer.h
@@ -5,6 +5,7 @@
 #ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_H_
 #define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_DEVICE_ACCOUNTS_SYNCHRONIZER_H_
 
+#include "build/build_config.h"
 #include "google_apis/gaia/core_account_id.h"
 
 namespace signin {
@@ -16,6 +17,15 @@
   DeviceAccountsSynchronizer() = default;
   virtual ~DeviceAccountsSynchronizer() = default;
 
+#if defined(OS_ANDROID)
+  // Reloads the information of all device-level accounts. All device-level
+  // accounts will be visible in IdentityManager::GetAccountsWithRefreshTokens()
+  // with any persistent errors cleared after this method is called.
+  virtual void ReloadAllAccountsFromSystemWithPrimaryAccount(
+      const CoreAccountId& primary_account_id) = 0;
+#endif
+
+#if defined(OS_IOS)
   // Reloads the information of all device-level accounts. All device-level
   // accounts will be visible in IdentityManager::GetAccountsWithRefreshTokens()
   // with any persistent errors cleared after this method is called.
@@ -25,6 +35,7 @@
   // account will be visible in IdentityManager::GetAccountsWithRefreshTokens()
   // with any persistent error cleared after this method is called.
   virtual void ReloadAccountFromSystem(const CoreAccountId& account_id) = 0;
+#endif
 
   // Class is non-copyable, non-moveable.
   DeviceAccountsSynchronizer(const DeviceAccountsSynchronizer&) = delete;
diff --git a/components/signin/public/identity_manager/identity_manager.cc b/components/signin/public/identity_manager/identity_manager.cc
index 2b7719d..4e6987a4 100644
--- a/components/signin/public/identity_manager/identity_manager.cc
+++ b/components/signin/public/identity_manager/identity_manager.cc
@@ -25,8 +25,7 @@
 #if defined(OS_ANDROID)
 #include "base/android/jni_string.h"
 #include "components/signin/internal/identity_manager/android/jni_headers/IdentityManager_jni.h"
-#include "components/signin/internal/identity_manager/android/jni_headers/IdentityMutator_jni.h"
-#include "components/signin/internal/identity_manager/oauth2_token_service_delegate_android.h"
+#include "components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.h"
 #elif !defined(OS_IOS)
 #include "components/signin/internal/identity_manager/mutable_profile_oauth2_token_service_delegate.h"
 #endif
@@ -49,18 +48,14 @@
       gaia_cookie_manager_service_(std::move(gaia_cookie_manager_service)),
       primary_account_manager_(std::move(primary_account_manager)),
       account_fetcher_service_(std::move(account_fetcher_service)),
-      primary_account_mutator_(std::move(primary_account_mutator)),
-      accounts_mutator_(std::move(accounts_mutator)),
-      accounts_cookie_mutator_(std::move(accounts_cookie_mutator)),
-      diagnostics_provider_(std::move(diagnostics_provider)),
-      device_accounts_synchronizer_(std::move(device_accounts_synchronizer)) {
+      identity_mutator_(std::move(primary_account_mutator),
+                        std::move(accounts_mutator),
+                        std::move(accounts_cookie_mutator),
+                        std::move(device_accounts_synchronizer)),
+      diagnostics_provider_(std::move(diagnostics_provider)) {
   DCHECK(account_fetcher_service_);
-  DCHECK(accounts_cookie_mutator_);
   DCHECK(diagnostics_provider_);
 
-  DCHECK(!accounts_mutator_ || !device_accounts_synchronizer_)
-      << "Cannot have both an AccountsMutator and a DeviceAccountsSynchronizer";
-
   // IdentityManager will outlive the PrimaryAccountManager, so base::Unretained
   // is safe.
   primary_account_manager_->SetGoogleSigninSucceededCallback(
@@ -100,14 +95,6 @@
     UpdateUnconsentedPrimaryAccount();
 
 #if defined(OS_ANDROID)
-  java_identity_mutator_ =
-      primary_account_mutator_
-          ? Java_IdentityMutator_Constructor(
-                base::android::AttachCurrentThread(),
-                reinterpret_cast<intptr_t>(primary_account_mutator_.get()),
-                reinterpret_cast<intptr_t>(this))
-          : nullptr;
-
   java_identity_manager_ = Java_IdentityManager_create(
       base::android::AttachCurrentThread(), reinterpret_cast<intptr_t>(this));
 #endif
@@ -126,9 +113,6 @@
   if (java_identity_manager_)
     Java_IdentityManager_destroy(base::android::AttachCurrentThread(),
                                  java_identity_manager_);
-  if (java_identity_mutator_)
-    Java_IdentityMutator_destroy(base::android::AttachCurrentThread(),
-                                 java_identity_mutator_);
 #endif
 }
 
@@ -347,19 +331,19 @@
 }
 
 PrimaryAccountMutator* IdentityManager::GetPrimaryAccountMutator() {
-  return primary_account_mutator_.get();
+  return identity_mutator_.GetPrimaryAccountMutator();
 }
 
 AccountsMutator* IdentityManager::GetAccountsMutator() {
-  return accounts_mutator_.get();
+  return identity_mutator_.GetAccountsMutator();
 }
 
 AccountsCookieMutator* IdentityManager::GetAccountsCookieMutator() {
-  return accounts_cookie_mutator_.get();
+  return identity_mutator_.GetAccountsCookieMutator();
 }
 
 DeviceAccountsSynchronizer* IdentityManager::GetDeviceAccountsSynchronizer() {
-  return device_accounts_synchronizer_.get();
+  return identity_mutator_.GetDeviceAccountsSynchronizer();
 }
 
 void IdentityManager::AddDiagnosticsObserver(DiagnosticsObserver* observer) {
@@ -409,11 +393,6 @@
 }
 
 #if defined(OS_ANDROID)
-void IdentityManager::LegacyReloadAccountsFromSystem() {
-  token_service_->GetDelegate()->ReloadAccountsFromSystem(
-      GetPrimaryAccountId());
-}
-
 base::android::ScopedJavaLocalRef<jobject>
 IdentityManager::LegacyGetAccountTrackerServiceJavaObject() {
   return account_tracker_service_->GetJavaObject();
@@ -431,8 +410,8 @@
 
 base::android::ScopedJavaLocalRef<jobject>
 IdentityManager::GetIdentityMutatorJavaObject() {
-  DCHECK(java_identity_manager_);
-  return base::android::ScopedJavaLocalRef<jobject>(java_identity_mutator_);
+  return base::android::ScopedJavaLocalRef<jobject>(
+      identity_mutator_.GetJavaObject());
 }
 
 void IdentityManager::ForceRefreshOfExtendedAccountInfo(
@@ -456,10 +435,6 @@
     return nullptr;
   return ConvertToJavaCoreAccountInfo(env, account_info.value());
 }
-
-void IdentityManager::ReloadAccountsFromSystem(JNIEnv* env) {
-  LegacyReloadAccountsFromSystem();
-}
 #endif
 
 PrimaryAccountManager* IdentityManager::GetPrimaryAccountManager() {
diff --git a/components/signin/public/identity_manager/identity_manager.h b/components/signin/public/identity_manager/identity_manager.h
index e15acf7..7d2ecb1c 100644
--- a/components/signin/public/identity_manager/identity_manager.h
+++ b/components/signin/public/identity_manager/identity_manager.h
@@ -15,6 +15,7 @@
 #include "components/signin/internal/identity_manager/profile_oauth2_token_service_observer.h"
 #include "components/signin/public/identity_manager/access_token_fetcher.h"
 #include "components/signin/public/identity_manager/account_info.h"
+#include "components/signin/public/identity_manager/identity_mutator.h"
 #include "components/signin/public/identity_manager/ubertoken_fetcher.h"
 #include "google_apis/gaia/oauth2_access_token_manager.h"
 #include "services/identity/public/cpp/scope_set.h"
@@ -43,14 +44,10 @@
 
 namespace signin {
 
-class AccountsMutator;
-class AccountsCookieMutator;
 struct AccountsInCookieJarInfo;
 class IdentityManagerTest;
 class IdentityTestEnvironment;
-class DeviceAccountsSynchronizer;
 class DiagnosticsProvider;
-class PrimaryAccountMutator;
 enum class ClearPrimaryAccountPolicy;
 struct CookieParamsForTest;
 
@@ -426,14 +423,6 @@
   DiagnosticsProvider* GetDiagnosticsProvider();
 
 #if defined(OS_ANDROID)
-  // Reloads the accounts in the token service from the system accounts. This
-  // API calls ProfileOAuth2TokenServiceDelegate::ReloadAccountsFromSystem and
-  // it triggers platform specific implementation for Android. NOTE: In normal
-  // usage, this method SHOULD NOT be called.
-  // TODO(https://crbug.com/930094): Expose this through
-  // DeviceAccountsSynchronizer
-  void LegacyReloadAccountsFromSystem();
-
   // Returns a pointer to the AccountTrackerService Java instance associated
   // with this object.
   // TODO(https://crbug.com/934688): Eliminate this method once
@@ -467,8 +456,6 @@
   FindExtendedAccountInfoForAccountWithRefreshTokenByEmailAddress(
       JNIEnv* env,
       const base::android::JavaParamRef<jstring>& j_email) const;
-
-  void ReloadAccountsFromSystem(JNIEnv* env);
 #endif
 
  private:
@@ -658,24 +645,11 @@
   std::unique_ptr<PrimaryAccountManager> primary_account_manager_;
   std::unique_ptr<AccountFetcherService> account_fetcher_service_;
 
-  // PrimaryAccountMutator instance. May be null if mutation of the primary
-  // account state is not supported on the current platform.
-  std::unique_ptr<PrimaryAccountMutator> primary_account_mutator_;
-
-  // AccountsMutator instance. May be null if mutation of accounts is not
-  // supported on the current platform.
-  std::unique_ptr<AccountsMutator> accounts_mutator_;
-
-  // AccountsCookieMutator instance. Guaranteed to be non-null, as this
-  // functionality is supported on all platforms.
-  std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator_;
+  IdentityMutator identity_mutator_;
 
   // DiagnosticsProvider instance.
   std::unique_ptr<DiagnosticsProvider> diagnostics_provider_;
 
-  // DeviceAccountsSynchronizer instance.
-  std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer_;
-
   // Lists of observers.
   // Makes sure lists are empty on destruction.
   base::ObserverList<Observer, true>::Unchecked observer_list_;
@@ -689,8 +663,6 @@
 #if defined(OS_ANDROID)
   // Java-side IdentityManager object.
   base::android::ScopedJavaGlobalRef<jobject> java_identity_manager_;
-  // Java-side IdentityMutator object.
-  base::android::ScopedJavaGlobalRef<jobject> java_identity_mutator_;
 #endif
 
   DISALLOW_COPY_AND_ASSIGN(IdentityManager);
diff --git a/components/signin/public/identity_manager/identity_manager_builder.cc b/components/signin/public/identity_manager/identity_manager_builder.cc
index 7dc60a28..da11364 100644
--- a/components/signin/public/identity_manager/identity_manager_builder.cc
+++ b/components/signin/public/identity_manager/identity_manager_builder.cc
@@ -30,10 +30,13 @@
 #endif
 
 #if defined(OS_IOS)
-#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h"
 #include "components/signin/public/identity_manager/ios/device_accounts_provider.h"
 #endif
 
+#if defined(OS_ANDROID) || defined(OS_IOS)
+#include "components/signin/internal/identity_manager/device_accounts_synchronizer_impl.h"
+#endif
+
 #if !defined(OS_ANDROID) && !defined(OS_IOS)
 #include "components/signin/internal/identity_manager/accounts_mutator_impl.h"
 #endif
@@ -155,7 +158,7 @@
                                  std::move(params->image_decoder));
 
   std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer;
-#if defined(OS_IOS)
+#if defined(OS_IOS) || defined(OS_ANDROID)
   device_accounts_synchronizer =
       std::make_unique<DeviceAccountsSynchronizerImpl>(
           token_service->GetDelegate());
diff --git a/components/signin/public/identity_manager/identity_mutator.cc b/components/signin/public/identity_manager/identity_mutator.cc
new file mode 100644
index 0000000..33100167
--- /dev/null
+++ b/components/signin/public/identity_manager/identity_mutator.cc
@@ -0,0 +1,109 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "components/signin/public/identity_manager/identity_mutator.h"
+
+#include "components/signin/public/identity_manager/accounts_cookie_mutator.h"
+#include "components/signin/public/identity_manager/accounts_mutator.h"
+#include "components/signin/public/identity_manager/device_accounts_synchronizer.h"
+#include "components/signin/public/identity_manager/primary_account_mutator.h"
+
+#if defined(OS_ANDROID)
+#include "base/android/jni_string.h"
+#include "components/signin/internal/identity_manager/android/jni_headers/IdentityMutator_jni.h"
+#include "components/signin/public/identity_manager/account_info.h"
+#endif
+
+namespace signin {
+
+#if defined(OS_ANDROID)
+JniIdentityMutator::JniIdentityMutator(IdentityMutator* identity_mutator)
+    : identity_mutator_(identity_mutator) {}
+
+bool JniIdentityMutator::SetPrimaryAccount(
+    JNIEnv* env,
+    const base::android::JavaParamRef<jobject>& primary_account_id) {
+  PrimaryAccountMutator* primary_account_mutator =
+      identity_mutator_->GetPrimaryAccountMutator();
+  DCHECK(primary_account_mutator);
+  return primary_account_mutator->SetPrimaryAccount(
+      ConvertFromJavaCoreAccountId(env, primary_account_id));
+}
+
+bool JniIdentityMutator::ClearPrimaryAccount(JNIEnv* env,
+                                             jint action,
+                                             jint source_metric,
+                                             jint delete_metric) {
+  PrimaryAccountMutator* primary_account_mutator =
+      identity_mutator_->GetPrimaryAccountMutator();
+  DCHECK(primary_account_mutator);
+  return primary_account_mutator->ClearPrimaryAccount(
+      PrimaryAccountMutator::ClearAccountsAction::kDefault,
+      static_cast<signin_metrics::ProfileSignout>(source_metric),
+      static_cast<signin_metrics::SignoutDelete>(delete_metric));
+}
+
+void JniIdentityMutator::ReloadAllAccountsFromSystemWithPrimaryAccount(
+    JNIEnv* env,
+    const base::android::JavaParamRef<jobject>& primary_account_id) {
+  DeviceAccountsSynchronizer* device_accounts_synchronizer =
+      identity_mutator_->GetDeviceAccountsSynchronizer();
+  DCHECK(device_accounts_synchronizer);
+  device_accounts_synchronizer->ReloadAllAccountsFromSystemWithPrimaryAccount(
+      ConvertFromJavaCoreAccountId(env, primary_account_id));
+}
+#endif  // defined(OS_ANDROID)
+
+IdentityMutator::IdentityMutator(
+    std::unique_ptr<PrimaryAccountMutator> primary_account_mutator,
+    std::unique_ptr<AccountsMutator> accounts_mutator,
+    std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator,
+    std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer)
+    : primary_account_mutator_(std::move(primary_account_mutator)),
+      accounts_mutator_(std::move(accounts_mutator)),
+      accounts_cookie_mutator_(std::move(accounts_cookie_mutator)),
+      device_accounts_synchronizer_(std::move(device_accounts_synchronizer)) {
+  DCHECK(accounts_cookie_mutator_);
+  DCHECK(!accounts_mutator_ || !device_accounts_synchronizer_)
+      << "Cannot have both an AccountsMutator and a DeviceAccountsSynchronizer";
+
+#if defined(OS_ANDROID)
+  jni_identity_mutator_.reset(new JniIdentityMutator(this));
+  java_identity_mutator_ = Java_IdentityMutator_Constructor(
+      base::android::AttachCurrentThread(),
+      reinterpret_cast<intptr_t>(jni_identity_mutator_.get()));
+#endif
+}
+
+IdentityMutator::~IdentityMutator() {
+#if defined(OS_ANDROID)
+  if (java_identity_mutator_)
+    Java_IdentityMutator_destroy(base::android::AttachCurrentThread(),
+                                 java_identity_mutator_);
+#endif
+}
+
+#if defined(OS_ANDROID)
+base::android::ScopedJavaLocalRef<jobject> IdentityMutator::GetJavaObject() {
+  DCHECK(java_identity_mutator_);
+  return base::android::ScopedJavaLocalRef<jobject>(java_identity_mutator_);
+}
+#endif
+
+PrimaryAccountMutator* IdentityMutator::GetPrimaryAccountMutator() {
+  return primary_account_mutator_.get();
+}
+
+AccountsMutator* IdentityMutator::GetAccountsMutator() {
+  return accounts_mutator_.get();
+}
+
+AccountsCookieMutator* IdentityMutator::GetAccountsCookieMutator() {
+  return accounts_cookie_mutator_.get();
+}
+
+DeviceAccountsSynchronizer* IdentityMutator::GetDeviceAccountsSynchronizer() {
+  return device_accounts_synchronizer_.get();
+}
+}  // namespace signin
diff --git a/components/signin/public/identity_manager/identity_mutator.h b/components/signin/public/identity_manager/identity_mutator.h
new file mode 100644
index 0000000..c6316e7a
--- /dev/null
+++ b/components/signin/public/identity_manager/identity_mutator.h
@@ -0,0 +1,138 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_MUTATOR_H_
+#define COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_MUTATOR_H_
+
+#include <memory>
+
+#include "build/build_config.h"
+#if defined(OS_ANDROID)
+#include "base/android/jni_android.h"
+#endif
+
+namespace signin {
+class AccountsMutator;
+class AccountsCookieMutator;
+class PrimaryAccountMutator;
+class DeviceAccountsSynchronizer;
+
+#if defined(OS_ANDROID)
+class IdentityMutator;
+
+// This class is the JNI interface accessing IdentityMutator.
+// This is created by IdentityMutator and can only be accessed by JNI generated
+// code (IdentityMutator_jni.h), i.e. by IdentityMutator.java.
+class JniIdentityMutator {
+ public:
+  // JniIdentityMutator is non-copyable, non-movable
+  JniIdentityMutator(IdentityMutator&& other) = delete;
+  JniIdentityMutator const& operator=(IdentityMutator&& other) = delete;
+
+  JniIdentityMutator(const IdentityMutator& other) = delete;
+  JniIdentityMutator const& operator=(const IdentityMutator& other) = delete;
+
+  // Called by java to mark the account with |account_id| as the primary
+  // account, and return whether the operation succeeded or not. To succeed,
+  // this requires that:
+  //   - the account is known by the IdentityManager.
+  //   - setting the primary account is allowed,
+  //   - the account username is allowed by policy,
+  //   - there is not already a primary account set.
+  bool SetPrimaryAccount(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& primary_account_id);
+
+  // Called by java to clear the primary account, and return whether the
+  // operation succeeded or not. Depending on |action|, the other accounts known
+  // to the IdentityManager may be deleted.
+  bool ClearPrimaryAccount(JNIEnv* env,
+                           jint action,
+                           jint source_metric,
+                           jint delete_metric);
+
+  // Called by java to reload the accounts in the token service from the system
+  // accounts.
+  void ReloadAllAccountsFromSystemWithPrimaryAccount(
+      JNIEnv* env,
+      const base::android::JavaParamRef<jobject>& primary_account_id);
+
+ private:
+  friend IdentityMutator;
+
+  JniIdentityMutator(IdentityMutator* identity_mutator);
+
+  IdentityMutator* identity_mutator_;
+};
+#endif
+
+// IdentityMutator is the mutating interface for IdentityManager.
+class IdentityMutator {
+ public:
+  IdentityMutator(
+      std::unique_ptr<PrimaryAccountMutator> primary_account_mutator,
+      std::unique_ptr<AccountsMutator> accounts_mutator,
+      std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator,
+      std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer);
+
+  virtual ~IdentityMutator();
+
+  // IdentityMutator is non-copyable, non-moveable.
+  IdentityMutator(IdentityMutator&& other) = delete;
+  IdentityMutator const& operator=(IdentityMutator&& other) = delete;
+
+  IdentityMutator(const IdentityMutator& other) = delete;
+  IdentityMutator const& operator=(const IdentityMutator& other) = delete;
+
+#if defined(OS_ANDROID)
+  // Get the reference on the java IdentityManager.
+  base::android::ScopedJavaLocalRef<jobject> GetJavaObject();
+#endif
+
+  // Returns pointer to the object used to change the signed-in state of the
+  // primary account, if supported on the current platform. Otherwise, returns
+  // null.
+  PrimaryAccountMutator* GetPrimaryAccountMutator();
+
+  // Returns pointer to the object used to seed accounts and mutate state of
+  // accounts' refresh tokens, if supported on the current platform. Otherwise,
+  // returns null.
+  AccountsMutator* GetAccountsMutator();
+
+  // Returns pointer to the object used to manipulate the cookies stored and the
+  // accounts associated with them. Guaranteed to be non-null.
+  AccountsCookieMutator* GetAccountsCookieMutator();
+
+  // Returns pointer to the object used to seed accounts information from the
+  // device-level accounts. May be null if the system has no such notion.
+  DeviceAccountsSynchronizer* GetDeviceAccountsSynchronizer();
+
+ private:
+#if defined(OS_ANDROID)
+  // C++ endpoint for identity mutator calls originating from java.
+  std::unique_ptr<JniIdentityMutator> jni_identity_mutator_;
+
+  // Java-side IdentityMutator object.
+  base::android::ScopedJavaGlobalRef<jobject> java_identity_mutator_;
+#endif
+
+  // PrimaryAccountMutator instance. May be null if mutation of the primary
+  // account state is not supported on the current platform.
+  std::unique_ptr<PrimaryAccountMutator> primary_account_mutator_;
+
+  // AccountsMutator instance. May be null if mutation of accounts is not
+  // supported on the current platform.
+  std::unique_ptr<AccountsMutator> accounts_mutator_;
+
+  // AccountsCookieMutator instance. Guaranteed to be non-null, as this
+  // functionality is supported on all platforms.
+  std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator_;
+
+  // DeviceAccountsSynchronizer instance.
+  std::unique_ptr<DeviceAccountsSynchronizer> device_accounts_synchronizer_;
+};
+
+}  // namespace signin
+
+#endif  // COMPONENTS_SIGNIN_PUBLIC_IDENTITY_MANAGER_IDENTITY_MUTATOR_H_
diff --git a/components/signin/public/identity_manager/primary_account_mutator.cc b/components/signin/public/identity_manager/primary_account_mutator.cc
deleted file mode 100644
index 7e691e43..0000000
--- a/components/signin/public/identity_manager/primary_account_mutator.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "components/signin/public/identity_manager/primary_account_mutator.h"
-
-#include "components/signin/public/identity_manager/account_info.h"
-
-#if defined(OS_ANDROID)
-#include "base/android/jni_string.h"
-#endif
-
-namespace signin {
-
-PrimaryAccountMutator::PrimaryAccountMutator() {}
-
-PrimaryAccountMutator::~PrimaryAccountMutator() {}
-
-#if defined(OS_ANDROID)
-bool PrimaryAccountMutator::SetPrimaryAccount(
-    JNIEnv* env,
-    const base::android::JavaParamRef<jobject>& account_id) {
-  return SetPrimaryAccount(ConvertFromJavaCoreAccountId(env, account_id));
-}
-
-bool PrimaryAccountMutator::ClearPrimaryAccount(JNIEnv* env,
-                                                jint action,
-                                                jint source_metric,
-                                                jint delete_metric) {
-  return ClearPrimaryAccount(
-      ClearAccountsAction::kDefault,
-      static_cast<signin_metrics::ProfileSignout>(source_metric),
-      static_cast<signin_metrics::SignoutDelete>(delete_metric));
-}
-#endif
-
-}  // namespace signin
diff --git a/components/signin/public/identity_manager/primary_account_mutator.h b/components/signin/public/identity_manager/primary_account_mutator.h
index bd6d6a4..0b23bde 100644
--- a/components/signin/public/identity_manager/primary_account_mutator.h
+++ b/components/signin/public/identity_manager/primary_account_mutator.h
@@ -8,9 +8,6 @@
 #include <string>
 
 #include "build/build_config.h"
-#if defined(OS_ANDROID)
-#include "base/android/jni_android.h"
-#endif
 
 namespace signin_metrics {
 enum ProfileSignout : int;
@@ -39,8 +36,8 @@
     kRemoveAll,  // Remove all accounts.
   };
 
-  PrimaryAccountMutator();
-  virtual ~PrimaryAccountMutator();
+  PrimaryAccountMutator() = default;
+  virtual ~PrimaryAccountMutator() = default;
 
   // PrimaryAccountMutator is non-copyable, non-moveable.
   PrimaryAccountMutator(PrimaryAccountMutator&& other) = delete;
@@ -85,22 +82,6 @@
       signin_metrics::ProfileSignout source_metric,
       signin_metrics::SignoutDelete delete_metric) = 0;
 #endif
-
-#if defined(OS_ANDROID)
-  // Overloads for calls from java:
-  bool SetPrimaryAccount(
-      JNIEnv* env,
-      const base::android::JavaParamRef<jobject>& account_id);
-
-  bool ClearPrimaryAccount(JNIEnv* env,
-                           jint action,
-                           jint source_metric,
-                           jint delete_metric);
-
-  base::android::ScopedJavaLocalRef<jobject> GetJavaObject();
-
-  base::android::ScopedJavaGlobalRef<jobject> java_primary_account_mutator_;
-#endif
 };
 
 }  // namespace signin
diff --git a/components/viz/common/BUILD.gn b/components/viz/common/BUILD.gn
index 250fa6be..9ce99f8 100644
--- a/components/viz/common/BUILD.gn
+++ b/components/viz/common/BUILD.gn
@@ -114,6 +114,8 @@
   sources = [
     "constants.cc",
     "constants.h",
+    "display/de_jelly.cc",
+    "display/de_jelly.h",
     "display/overlay_strategy.cc",
     "display/overlay_strategy.h",
     "display/renderer_settings.cc",
diff --git a/components/viz/common/display/de_jelly.cc b/components/viz/common/display/de_jelly.cc
new file mode 100644
index 0000000..3975ee4
--- /dev/null
+++ b/components/viz/common/display/de_jelly.cc
@@ -0,0 +1,39 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "components/viz/common/display/de_jelly.h"
+
+#include "base/command_line.h"
+#include "components/viz/common/switches.h"
+
+namespace viz {
+
+bool DeJellyEnabled() {
+  return base::CommandLine::ForCurrentProcess()->HasSwitch(
+      switches::kEnableDeJelly);
+}
+
+bool DeJellyActive() {
+  // TODO(ericrk): Android specific bits to be added in a follow-up CL.
+  return DeJellyEnabled();
+}
+
+float DeJellyScreenWidth() {
+  std::string value =
+      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
+          switches::kDeJellyScreenWidth);
+  if (!value.empty())
+    return std::atoi(value.c_str());
+
+  // TODO(ericrk): We can automatically handle this on Android. For now return
+  // a reasonable default.
+  return 1440.0f;
+}
+
+float MaxDeJellyHeight() {
+  // Not currently configurable.
+  return 30.0f;
+}
+
+}  // namespace viz
diff --git a/components/viz/common/display/de_jelly.h b/components/viz/common/display/de_jelly.h
new file mode 100644
index 0000000..187f063
--- /dev/null
+++ b/components/viz/common/display/de_jelly.h
@@ -0,0 +1,35 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef COMPONENTS_VIZ_COMMON_DISPLAY_DE_JELLY_H_
+#define COMPONENTS_VIZ_COMMON_DISPLAY_DE_JELLY_H_
+
+#include "components/viz/common/viz_common_export.h"
+
+namespace viz {
+
+// Utility functions for use with de-jelly logic. Used in both viz process and
+// render process.
+
+// Whether experimental de-jelly is enabled. This indicates whether
+// DeJellyActive below may ever return true, and is used by the renderer
+// process to determine whether it should prepare frames for potential
+// de-jelly.
+bool VIZ_COMMON_EXPORT DeJellyEnabled();
+
+// Whether experimental de-jelly is *currently* active. This is different from
+// whether it is generally enabled, and may change frame-over-frame. This is
+// queried from the Viz process, before drawing a frame.
+bool VIZ_COMMON_EXPORT DeJellyActive();
+
+// The screen width to use for de-jelly logic.
+float VIZ_COMMON_EXPORT DeJellyScreenWidth();
+
+// The maximum additional content which may be exposed in a layer by de-jelly
+// skewing.
+float VIZ_COMMON_EXPORT MaxDeJellyHeight();
+
+}  // namespace viz
+
+#endif  // COMPONENTS_VIZ_COMMON_DISPLAY_DE_JELLY_H_
diff --git a/components/viz/common/quads/shared_quad_state.h b/components/viz/common/quads/shared_quad_state.h
index 2f0ed214..85e6104 100644
--- a/components/viz/common/quads/shared_quad_state.h
+++ b/components/viz/common/quads/shared_quad_state.h
@@ -75,6 +75,9 @@
   // occluding surfaces and is only for quads that are the only quad in
   // their surface. SetAll() doesn't update this data.
   base::Optional<gfx::Rect> occluding_damage_rect;
+
+  // The amount to skew quads in this layer. For experimental de-jelly effect.
+  float de_jelly_delta_y = 0.0f;
 };
 
 }  // namespace viz
diff --git a/components/viz/common/switches.cc b/components/viz/common/switches.cc
index 26f8d97..c007b26 100644
--- a/components/viz/common/switches.cc
+++ b/components/viz/common/switches.cc
@@ -10,6 +10,10 @@
 
 namespace switches {
 
+// Screen width is useful for debugging. Shipping implementations should detect
+// this.
+const char kDeJellyScreenWidth[] = "de-jelly-screen-width";
+
 // The default number of the BeginFrames to wait to activate a surface with
 // dependencies.
 const char kDeadlineToSynchronizeSurfaces[] =
@@ -19,6 +23,9 @@
 // Also implies --disable-gpu-vsync (see //ui/gl/gl_switches.h).
 const char kDisableFrameRateLimit[] = "disable-frame-rate-limit";
 
+// Experimental de-jelly support.
+const char kEnableDeJelly[] = "enable-de-jelly";
+
 // Enable compositing individual elements via hardware overlays when
 // permitted by device.
 // Setting the flag to "single-fullscreen" will try to promote a single
diff --git a/components/viz/common/switches.h b/components/viz/common/switches.h
index ae94f04..87a1d37 100644
--- a/components/viz/common/switches.h
+++ b/components/viz/common/switches.h
@@ -14,8 +14,10 @@
 namespace switches {
 
 // Keep list in alphabetical order.
+VIZ_COMMON_EXPORT extern const char kDeJellyScreenWidth[];
 VIZ_COMMON_EXPORT extern const char kDeadlineToSynchronizeSurfaces[];
 VIZ_COMMON_EXPORT extern const char kDisableFrameRateLimit[];
+VIZ_COMMON_EXPORT extern const char kEnableDeJelly[];
 VIZ_COMMON_EXPORT extern const char kEnableHardwareOverlays[];
 VIZ_COMMON_EXPORT extern const char kEnableVizDevTools[];
 VIZ_COMMON_EXPORT extern const char kEnableVizHitTestDebug[];
diff --git a/components/viz/service/display/display.cc b/components/viz/service/display/display.cc
index a634bc9..c788d833 100644
--- a/components/viz/service/display/display.cc
+++ b/components/viz/service/display/display.cc
@@ -59,10 +59,10 @@
 
 gfx::PresentationFeedback SanitizePresentationFeedback(
     const gfx::PresentationFeedback& feedback,
-    base::TimeTicks swap_time) {
+    base::TimeTicks draw_time) {
   // Temporary to investigate large presentation times.
   // https://crbug.com/894440
-  DCHECK(!swap_time.is_null());
+  DCHECK(!draw_time.is_null());
   if (feedback.timestamp.is_null())
     return feedback;
 
@@ -78,14 +78,14 @@
     return gfx::PresentationFeedback::Failure();
   }
 
-  if (feedback.timestamp < swap_time) {
-    const auto diff = swap_time - feedback.timestamp;
+  if (feedback.timestamp < draw_time) {
+    const auto diff = draw_time - feedback.timestamp;
     UMA_HISTOGRAM_MEDIUM_TIMES(
         "Graphics.PresentationTimestamp.InvalidBeforeSwap", diff);
     return gfx::PresentationFeedback::Failure();
   }
 
-  const auto difference = feedback.timestamp - swap_time;
+  const auto difference = feedback.timestamp - draw_time;
   if (difference.InMinutes() > 3) {
     UMA_HISTOGRAM_CUSTOM_TIMES(
         "Graphics.PresentationTimestamp.LargePresentationDelta", difference,
@@ -131,9 +131,7 @@
 constexpr base::TimeDelta Display::kDrawToSwapMin;
 constexpr base::TimeDelta Display::kDrawToSwapMax;
 
-Display::PresentationGroupTiming::PresentationGroupTiming(
-    base::TimeTicks draw_and_swap_triggered_timestamp)
-    : draw_and_swap_triggered_timestamp_(draw_and_swap_triggered_timestamp) {}
+Display::PresentationGroupTiming::PresentationGroupTiming() = default;
 
 Display::PresentationGroupTiming::PresentationGroupTiming(
     Display::PresentationGroupTiming&& other) = default;
@@ -580,7 +578,7 @@
                               draw_timer->Elapsed().InMicroseconds());
     }
 
-    PresentationGroupTiming presentation_group_timing(now_time);
+    PresentationGroupTiming presentation_group_timing;
     presentation_group_timing.OnDraw(draw_timer->Begin());
 
     for (const auto& id_entry : aggregator_->previous_contained_surfaces()) {
@@ -604,7 +602,6 @@
     TRACE_EVENT_ASYNC_STEP_INTO0("viz,benchmark",
                                  "Graphics.Pipeline.DrawAndSwap",
                                  swapped_trace_id_, "Swap");
-    draw_start_times_pending_swap_ack_.emplace_back(draw_timer->Begin());
     swapped_since_resize_ = true;
 
     if (scheduler_) {
@@ -665,7 +662,10 @@
 }
 
 void Display::DidReceiveSwapBuffersAck(const gfx::SwapTimings& timings) {
-  DCHECK(!draw_start_times_pending_swap_ack_.empty());
+  // Adding to |pending_presentation_group_timings_| must
+  // have been done in DrawAndSwap(), and should not be popped until
+  // DidReceiveSwapBuffersAck.
+  DCHECK(!pending_presentation_group_timings_.empty());
 
   if (scheduler_) {
     scheduler_->DidReceiveSwapBuffersAck();
@@ -676,39 +676,31 @@
   if (renderer_)
     renderer_->SwapBuffersComplete();
 
-  // Adding to |pending_presentation_group_timings_| must
-  // have been done in DrawAndSwap(), and should not be popped until
-  // DidReceiveSwapBuffersAck.
-  DCHECK(!pending_presentation_group_timings_.empty());
-
   // It's possible to receive multiple calls to DidReceiveSwapBuffersAck()
   // before DidReceivePresentationFeedback(). Ensure that we're not setting
   // |swap_timings_| for the same PresentationGroupTiming multiple times.
-  base::TimeTicks draw_and_swap_triggered_timestamp;
+  base::TimeTicks draw_start_timestamp;
   for (auto& group_timing : pending_presentation_group_timings_) {
     if (!group_timing.HasSwapped()) {
       group_timing.OnSwap(timings);
-      draw_and_swap_triggered_timestamp =
-          group_timing.draw_and_swap_triggered_timestamp();
+      draw_start_timestamp = group_timing.draw_start_timestamp();
       break;
     }
   }
 
   // We should have at least one group that hasn't received a SwapBuffersAck
-  DCHECK(!draw_and_swap_triggered_timestamp.is_null());
+  DCHECK(!draw_start_timestamp.is_null());
 
   // Check that the swap timings correspond with the timestamp from when
   // the swap was triggered. Note that not all output surfaces provide timing
   // information, hence the check for a valid swap_start.
   if (!timings.swap_start.is_null()) {
-    DCHECK_LE(draw_and_swap_triggered_timestamp, timings.swap_start);
-    base::TimeDelta delta =
-        timings.swap_start - draw_start_times_pending_swap_ack_.front();
+    DCHECK_LE(draw_start_timestamp, timings.swap_start);
+    base::TimeDelta delta = timings.swap_start - draw_start_timestamp;
     UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
         "Compositing.Display.DrawToSwapUs", delta, kDrawToSwapMin,
         kDrawToSwapMax, kDrawToSwapUsBuckets);
   }
-  draw_start_times_pending_swap_ack_.pop_front();
 }
 
 void Display::DidReceiveTextureInUseResponses(
@@ -740,7 +732,7 @@
       last_presented_trace_id_, feedback.timestamp);
   auto& presentation_group_timing = pending_presentation_group_timings_.front();
   auto copy_feedback = SanitizePresentationFeedback(
-      feedback, presentation_group_timing.draw_and_swap_triggered_timestamp());
+      feedback, presentation_group_timing.draw_start_timestamp());
   TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(
       "benchmark,viz", "Display::FrameDisplayed", TRACE_EVENT_SCOPE_THREAD,
       copy_feedback.timestamp);
diff --git a/components/viz/service/display/display.h b/components/viz/service/display/display.h
index d1b2bbb9..6ee4efa 100644
--- a/components/viz/service/display/display.h
+++ b/components/viz/service/display/display.h
@@ -185,7 +185,7 @@
   // presented.
   class PresentationGroupTiming {
    public:
-    explicit PresentationGroupTiming(base::TimeTicks swap_triggered_timestamp);
+    PresentationGroupTiming();
     PresentationGroupTiming(PresentationGroupTiming&& other);
     ~PresentationGroupTiming();
 
@@ -196,14 +196,11 @@
     bool HasSwapped() const { return !swap_timings_.is_null(); }
     void OnPresent(const gfx::PresentationFeedback& feedback);
 
-    base::TimeTicks draw_and_swap_triggered_timestamp() const {
-      return draw_and_swap_triggered_timestamp_;
+    base::TimeTicks draw_start_timestamp() const {
+      return draw_start_timestamp_;
     }
 
    private:
-    // Not currently tracked by metrics but is used for
-    // SanitizePresentationFeedback()
-    base::TimeTicks draw_and_swap_triggered_timestamp_;
     base::TimeTicks draw_start_timestamp_;
     gfx::SwapTimings swap_timings_;
     std::vector<std::unique_ptr<Surface::PresentationHelper>>
@@ -266,10 +263,6 @@
   int64_t swapped_trace_id_ = 0;
   int64_t last_presented_trace_id_ = 0;
 
-  // TODO(nazabris, crbug.com/1003892): remove this member now that
-  // PresentationGroupTiming stores the same info.
-  base::circular_deque<base::TimeTicks> draw_start_times_pending_swap_ack_;
-
   DISALLOW_COPY_AND_ASSIGN(Display);
 };
 
diff --git a/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc b/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
index 8663927..3456046d 100644
--- a/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
+++ b/content/browser/accessibility/accessibility_tree_formatter_auralinux.cc
@@ -55,6 +55,7 @@
   std::unique_ptr<base::DictionaryValue> BuildAccessibilityTreeWithNode(
       AtspiAccessible* node);
 
+  void AddTextProperties(AtkText* atk_text, base::DictionaryValue* dict);
   void AddValueProperties(AtkObject* atk_object, base::DictionaryValue* dict);
   void AddTableProperties(AtkObject* atk_object, base::DictionaryValue* dict);
   void AddTableCellProperties(const ui::AXPlatformNodeAuraLinux* node,
@@ -325,6 +326,51 @@
     "footnote",  // ATK_ROLE_FOOTNOTE = 122.
 };
 
+void AccessibilityTreeFormatterAuraLinux::AddTextProperties(
+    AtkText* atk_text,
+    base::DictionaryValue* dict) {
+  auto text_values = std::make_unique<base::ListValue>();
+  int character_count = atk_text_get_character_count(atk_text);
+  text_values->AppendString(
+      base::StringPrintf("character_count=%i", character_count));
+
+  int caret_offset = atk_text_get_caret_offset(atk_text);
+  if (caret_offset != -1)
+    text_values->AppendString(
+        base::StringPrintf("caret_offset=%i", caret_offset));
+
+  int selection_start, selection_end;
+  char* selection_text =
+      atk_text_get_selection(atk_text, 0, &selection_start, &selection_end);
+  g_free(selection_text);
+  if (selection_start || selection_end) {
+    text_values->AppendString(
+        base::StringPrintf("selection_start=%i", selection_start));
+    text_values->AppendString(
+        base::StringPrintf("selection_end=%i", selection_end));
+  }
+
+  auto add_attribute_set_values = [](gpointer value, gpointer list) {
+    const AtkAttribute* attribute = static_cast<const AtkAttribute*>(value);
+    static_cast<base::ListValue*>(list)->AppendString(
+        base::StringPrintf("%s=%s", attribute->name, attribute->value));
+  };
+
+  int current_offset = 0, start_offset, end_offset;
+  while (current_offset < character_count) {
+    AtkAttributeSet* text_attributes = atk_text_get_run_attributes(
+        atk_text, current_offset, &start_offset, &end_offset);
+    text_values->AppendString(base::StringPrintf("offset=%i", start_offset));
+    g_slist_foreach(text_attributes, add_attribute_set_values,
+                    text_values.get());
+    atk_attribute_set_free(text_attributes);
+
+    current_offset = end_offset;
+  }
+
+  dict->Set("text", std::move(text_values));
+}
+
 void AccessibilityTreeFormatterAuraLinux::AddValueProperties(
     AtkObject* atk_object,
     base::DictionaryValue* dict) {
@@ -530,7 +576,7 @@
   }
   atk_attribute_set_free(attributes);
 
-  // Properties obtained via AtkValue.
+  AddTextProperties(ATK_TEXT(atk_object), dict);
   AddValueProperties(atk_object, dict);
   AddTableProperties(atk_object, dict);
   AddTableCellProperties(ax_platform_node, atk_object, dict);
@@ -601,8 +647,8 @@
     "container-live",
     "container-relevant",
     "current",
-    "dropeffect",
     "display",
+    "dropeffect",
     "explicit-name",
     "grabbed",
     "haspopup",
@@ -717,6 +763,15 @@
     }
   }
 
+  const base::ListValue* text_info;
+  if (node.GetList("text", &text_info)) {
+    for (auto it = text_info->begin(); it != text_info->end(); ++it) {
+      std::string cell_property;
+      if (it->GetAsString(&cell_property))
+        WriteAttribute(false, cell_property, &line);
+    }
+  }
+
   return line;
 }
 
diff --git a/content/browser/browser_context.cc b/content/browser/browser_context.cc
index 220d0a43..6861852 100644
--- a/content/browser/browser_context.cc
+++ b/content/browser/browser_context.cc
@@ -60,6 +60,7 @@
 #include "media/base/media_switches.h"
 #include "media/capabilities/in_memory_video_decode_stats_db_impl.h"
 #include "media/capabilities/video_decode_stats_db_impl.h"
+#include "media/learning/common/media_learning_tasks.h"
 #include "media/learning/impl/learning_session_impl.h"
 #include "media/mojo/services/video_decode_perf_history.h"
 #include "mojo/public/cpp/bindings/remote.h"
@@ -823,6 +824,15 @@
         std::make_unique<media::learning::LearningSessionImpl>(
             base::SequencedTaskRunnerHandle::Get());
 
+    // Register all the LearningTasks.
+    auto cb = base::BindRepeating(
+        [](media::learning::LearningSessionImpl* session,
+           const media::learning::LearningTask& task) {
+          session->RegisterTask(task);
+        },
+        new_learning_session.get());
+    media::learning::MediaLearningTasks::Register(std::move(cb));
+
     learning_session = new_learning_session.get();
 
     SetUserData(kLearningSession, std::move(new_learning_session));
diff --git a/content/browser/cache_storage/cache_storage_scheduler.cc b/content/browser/cache_storage/cache_storage_scheduler.cc
index 5e0685c..253e7710 100644
--- a/content/browser/cache_storage/cache_storage_scheduler.cc
+++ b/content/browser/cache_storage/cache_storage_scheduler.cc
@@ -21,8 +21,11 @@
 
 namespace {
 
+// Maximum parallel shared operations.  This constant was selected via
+// experimentation.  We tried 4, 16, and 64 for the limit.  16 was clearly
+// better than 4, but 64 was did not provide significant further benefit.
 const base::FeatureParam<int> kCacheStorageMaxSharedOps{
-    &features::kCacheStorageParallelOps, "max_shared_ops", 1};
+    &features::kCacheStorageParallelOps, "max_shared_ops", 16};
 
 }  // namespace
 
diff --git a/content/browser/frame_host/form_submission_throttle.cc b/content/browser/frame_host/form_submission_throttle.cc
index 0f9ca0af..9c83ef7 100644
--- a/content/browser/frame_host/form_submission_throttle.cc
+++ b/content/browser/frame_host/form_submission_throttle.cc
@@ -3,7 +3,7 @@
 // found in the LICENSE file.
 
 #include "content/browser/frame_host/form_submission_throttle.h"
-#include "content/browser/frame_host/navigation_handle_impl.h"
+#include "content/browser/frame_host/navigation_request.h"
 #include "content/public/browser/browser_thread.h"
 #include "content/public/browser/navigation_handle.h"
 #include "content/public/browser/navigation_throttle.h"
@@ -62,19 +62,20 @@
   if (!was_server_redirect)
     return NavigationThrottle::PROCEED;
 
-  NavigationHandleImpl* handle =
-      static_cast<NavigationHandleImpl*>(navigation_handle());
+  NavigationRequest* request = NavigationRequest::From(navigation_handle());
 
-  if (handle->should_check_main_world_csp() == CSPDisposition::DO_NOT_CHECK)
+  if (request->common_params().initiator_csp_info.should_check_main_world_csp ==
+      CSPDisposition::DO_NOT_CHECK) {
     return NavigationThrottle::PROCEED;
+  }
 
-  const GURL& url = handle->GetURL();
+  const GURL& url = request->GetURL();
 
   // TODO(arthursonzogni): This is not the right RenderFrameHostImpl. The one
   // that has initiated the navigation must be used instead.
   // See https://crbug.com/700964
   RenderFrameHostImpl* render_frame =
-      handle->frame_tree_node()->current_frame_host();
+      request->frame_tree_node()->current_frame_host();
 
   // TODO(estark): Move this check into NavigationRequest and split it into (1)
   // check report-only CSP, (2) upgrade request if needed, (3) check enforced
@@ -82,7 +83,7 @@
   if (render_frame->IsAllowedByCsp(
           CSPDirective::FormAction, url, was_server_redirect,
           false /* is_response_check */,
-          handle->source_location().value_or(SourceLocation()),
+          request->common_params().source_location.value_or(SourceLocation()),
           CSPContext::CHECK_ALL_CSP, true /* is_form_submission */)) {
     return NavigationThrottle::PROCEED;
   }
diff --git a/content/browser/frame_host/frame_tree_node.cc b/content/browser/frame_host/frame_tree_node.cc
index 3c9f40a..87fd3ff4 100644
--- a/content/browser/frame_host/frame_tree_node.cc
+++ b/content/browser/frame_host/frame_tree_node.cc
@@ -550,10 +550,8 @@
 bool FrameTreeNode::StopLoading() {
   if (navigation_request_) {
     int expected_pending_nav_entry_id = navigation_request_->nav_entry_id();
-    if (navigation_request_->navigation_handle()) {
+    if (navigation_request_->IsNavigationStarted())
       navigation_request_->set_net_error(net::ERR_ABORTED);
-      expected_pending_nav_entry_id = navigation_request_->nav_entry_id();
-    }
     navigator_->DiscardPendingEntryIfNeeded(expected_pending_nav_entry_id);
   }
   ResetNavigationRequest(false, true);
diff --git a/content/browser/frame_host/navigation_handle_impl.h b/content/browser/frame_host/navigation_handle_impl.h
index 01cc352d..df6a980 100644
--- a/content/browser/frame_host/navigation_handle_impl.h
+++ b/content/browser/frame_host/navigation_handle_impl.h
@@ -118,17 +118,6 @@
   void RegisterSubresourceOverride(
       mojom::TransferrableURLLoaderPtr transferrable_loader) override;
 
-  blink::mojom::RequestContextType request_context_type() const {
-    return navigation_request_->request_context_type();
-  }
-
-  // Get the unique id from the NavigationEntry associated with this
-  // NavigationHandle. Note that a synchronous, renderer-initiated navigation
-  // will not have a NavigationEntry associated with it, and this will return 0.
-  int pending_nav_entry_id() const {
-    return navigation_request_->nav_entry_id();
-  }
-
   // Returns the FrameTreeNode this navigation is happening in.
   FrameTreeNode* frame_tree_node() const {
     return navigation_request_->frame_tree_node();
@@ -138,15 +127,6 @@
     return navigation_request_->navigation_type();
   }
 
-  CSPDisposition should_check_main_world_csp() const {
-    return navigation_request_->common_params()
-        .initiator_csp_info.should_check_main_world_csp;
-  }
-
-  const base::Optional<SourceLocation>& source_location() const {
-    return navigation_request_->common_params().source_location;
-  }
-
  private:
   friend class NavigationRequest;
 
@@ -156,10 +136,6 @@
   // this navigation.
   NavigationHandleImpl(NavigationRequest* navigation_request);
 
-  NavigationRequest::NavigationHandleState state() const {
-    return navigation_request_->handle_state();
-  }
-
   // The NavigationRequest that owns this NavigationHandle.
   NavigationRequest* navigation_request_;
 
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc
index 22dd3c8..ea59a44 100644
--- a/content/browser/frame_host/navigation_request.cc
+++ b/content/browser/frame_host/navigation_request.cc
@@ -3325,39 +3325,39 @@
 
 std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params>
 NavigationRequest::MakeDidCommitProvisionalLoadParamsForBFCache() {
-  // TODO(lowell): Review all of these parameters for completeness.
   std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> params =
       std::make_unique<FrameHostMsg_DidCommitProvisionalLoad_Params>();
+
   params->http_status_code = net::HTTP_OK;
-  params->method = common_params().method;
+  params->url_is_unreachable = false;
   params->intended_as_new_entry = commit_params().intended_as_new_entry;
   params->should_replace_current_entry =
       common_params().should_replace_current_entry;
   params->post_id = -1;
   params->nav_entry_id = commit_params().nav_entry_id;
   params->navigation_token = commit_params().navigation_token;
-  params->transition = common_params().transition;
-
-  // TODO(lowell): Is there a way to get access to the the values needed to set
-  // the insecure_request_policy, etc?
-
-  params->url = common_params().url;
-  params->gesture = common_params().has_user_gesture ? NavigationGestureUser
-                                                     : NavigationGestureAuto;
-  params->page_state = commit_params().page_state;
-
-  params->should_update_history = true;
-
+  params->did_create_new_entry = false;
+  // TODO(crbug.com/1005718): Is origin ever unset?
   if (commit_params().origin_to_commit.has_value()) {
     params->origin = commit_params().origin_to_commit.value();
   }
-
+  // TODO(crbug.com/1005718): Set insecure_request_policy.
+  // TODO(crbug.com/1005718): Set insecure_navigations_set.
+  // TODO(crbug.com/1005718): Set has_potentially_trustworthy_unique_origin.
+  params->url = common_params().url;
+  params->should_update_history = true;
+  params->gesture = common_params().has_user_gesture ? NavigationGestureUser
+                                                     : NavigationGestureAuto;
+  params->page_state = commit_params().page_state;
+  params->method = common_params().method;
   params->item_sequence_number = frame_entry_item_sequence_number_;
   params->document_sequence_number = frame_entry_document_sequence_number_;
-
-  // TODO(lowell): Set the actual response mime type from FrameNavigationEntry.
+  // TODO(crbug.com/1005718): Set the actual mime type.
   params->contents_mime_type = "text/html";
-
+  params->transition = common_params().transition;
+  // TODO(crbug.com/1005718): Set is_overriding_user_agent.
+  // TODO(crbug.com/1005718): Set original_request_url.
+  params->history_list_was_cleared = false;
   params->request_id = GetGlobalRequestID().request_id;
 
   return params;
@@ -3630,4 +3630,8 @@
   return static_cast<NavigationHandleImpl*>(handle)->navigation_request();
 }
 
+bool NavigationRequest::IsNavigationStarted() const {
+  return state_ >= STARTED;
+}
+
 }  // namespace content
diff --git a/content/browser/frame_host/navigation_request.h b/content/browser/frame_host/navigation_request.h
index 5c632547..36f80c02 100644
--- a/content/browser/frame_host/navigation_request.h
+++ b/content/browser/frame_host/navigation_request.h
@@ -490,6 +490,11 @@
     return begin_params_->mixed_content_context_type;
   }
 
+  // Returns true if the navigation was started by the Navigator by calling
+  // BeginNavigation(), or if the request was created at commit time by calling
+  // CreateForCommit().
+  bool IsNavigationStarted() const;
+
  private:
   friend class NavigationRequestTest;
 
diff --git a/content/browser/frame_host/navigation_request_unittest.cc b/content/browser/frame_host/navigation_request_unittest.cc
index 6b6494e..29e0d68 100644
--- a/content/browser/frame_host/navigation_request_unittest.cc
+++ b/content/browser/frame_host/navigation_request_unittest.cc
@@ -250,7 +250,8 @@
       NavigationSimulatorImpl::CreateRendererInitiated(kUrl1, main_rfh());
   navigation->Start();
   EXPECT_EQ(blink::mojom::RequestContextType::HYPERLINK,
-            navigation->GetNavigationHandle()->request_context_type());
+            NavigationRequest::From(navigation->GetNavigationHandle())
+                ->request_context_type());
   EXPECT_EQ(net::HttpResponseInfo::CONNECTION_INFO_UNKNOWN,
             navigation->GetNavigationHandle()->GetConnectionInfo());
 
@@ -258,7 +259,8 @@
       net::HttpResponseInfo::CONNECTION_INFO_HTTP1_1);
   navigation->Redirect(kUrl2);
   EXPECT_EQ(blink::mojom::RequestContextType::HYPERLINK,
-            navigation->GetNavigationHandle()->request_context_type());
+            NavigationRequest::From(navigation->GetNavigationHandle())
+                ->request_context_type());
   EXPECT_EQ(net::HttpResponseInfo::CONNECTION_INFO_HTTP1_1,
             navigation->GetNavigationHandle()->GetConnectionInfo());
 
@@ -266,7 +268,8 @@
       net::HttpResponseInfo::CONNECTION_INFO_QUIC_35);
   navigation->ReadyToCommit();
   EXPECT_EQ(blink::mojom::RequestContextType::HYPERLINK,
-            navigation->GetNavigationHandle()->request_context_type());
+            NavigationRequest::From(navigation->GetNavigationHandle())
+                ->request_context_type());
   EXPECT_EQ(net::HttpResponseInfo::CONNECTION_INFO_QUIC_35,
             navigation->GetNavigationHandle()->GetConnectionInfo());
 }
@@ -292,13 +295,15 @@
       NavigationSimulatorImpl::CreateRendererInitiated(kUrl, main_rfh());
   navigation->Start();
   EXPECT_EQ(blink::mojom::RequestContextType::HYPERLINK,
-            navigation->GetNavigationHandle()->request_context_type());
+            NavigationRequest::From(navigation->GetNavigationHandle())
+                ->request_context_type());
   EXPECT_EQ(net::HttpResponseInfo::CONNECTION_INFO_UNKNOWN,
             navigation->GetNavigationHandle()->GetConnectionInfo());
 
   navigation->Fail(net::ERR_CERT_DATE_INVALID);
   EXPECT_EQ(blink::mojom::RequestContextType::HYPERLINK,
-            navigation->GetNavigationHandle()->request_context_type());
+            NavigationRequest::From(navigation->GetNavigationHandle())
+                ->request_context_type());
   EXPECT_EQ(net::ERR_CERT_DATE_INVALID,
             navigation->GetNavigationHandle()->GetNetErrorCode());
 }
@@ -550,11 +555,12 @@
   navigation->SetAutoAdvance(false);
   navigation->Start();
   navigation->Fail(net::ERR_CERT_DATE_INVALID);
-  EXPECT_EQ(
-      NavigationRequest::PROCESSING_WILL_FAIL_REQUEST,
-      navigation->GetNavigationHandle()->navigation_request()->handle_state());
+  EXPECT_EQ(NavigationRequest::PROCESSING_WILL_FAIL_REQUEST,
+            NavigationRequest::From(navigation->GetNavigationHandle())
+                ->handle_state());
   EXPECT_TRUE(navigation->GetNavigationHandle()->GetRenderFrameHost());
-  navigation->GetNavigationHandle()->CallResumeForTesting();
+  NavigationRequest::From(navigation->GetNavigationHandle())
+      ->CallResumeForTesting();
   EXPECT_TRUE(navigation->GetNavigationHandle()->GetRenderFrameHost());
 
   SetBrowserClientForTesting(old_browser_client);
diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc
index 6a17a0e8..8a700e29a 100644
--- a/content/browser/frame_host/navigator_impl.cc
+++ b/content/browser/frame_host/navigator_impl.cc
@@ -176,10 +176,9 @@
   }
 
   // Discard the pending navigation entry if needed.
+  NavigationRequest* request = render_frame_host->navigation_request();
   int expected_pending_entry_id =
-      render_frame_host->GetNavigationHandle()
-          ? render_frame_host->GetNavigationHandle()->pending_nav_entry_id()
-          : 0;
+      request && request->IsNavigationStarted() ? request->nav_entry_id() : 0;
   DiscardPendingEntryIfNeeded(expected_pending_entry_id);
 }
 
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc
index db4fec7..d9df69d5 100644
--- a/content/browser/frame_host/render_frame_host_impl.cc
+++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -4691,7 +4691,7 @@
     // Cancel any pending navigations, to avoid their navigation commit/fail
     // event from wiping out the is_waiting_for_beforeunload_ack_ state.
     if (frame_tree_node_->navigation_request() &&
-        frame_tree_node_->navigation_request()->navigation_handle()) {
+        frame_tree_node_->navigation_request()->IsNavigationStarted()) {
       frame_tree_node_->navigation_request()->set_net_error(net::ERR_ABORTED);
     }
     frame_tree_node_->ResetNavigationRequest(false, true);
@@ -5527,7 +5527,7 @@
 
   // An error page is expected to commit, hence why is_loading_ is set to true.
   is_loading_ = true;
-  DCHECK(navigation_request && navigation_request->navigation_handle() &&
+  DCHECK(navigation_request && navigation_request->IsNavigationStarted() &&
          navigation_request->GetNetErrorCode() != net::OK);
 }
 
@@ -6906,7 +6906,7 @@
   }
 
   DCHECK(navigation_request);
-  DCHECK(navigation_request->navigation_handle());
+  DCHECK(navigation_request->IsNavigationStarted());
 
   // Update the page transition. For subframe navigations, the renderer process
   // only gives the correct page transition at commit time.
@@ -7133,16 +7133,16 @@
     std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params>
         validated_params,
     mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) {
-  NavigationHandleImpl* navigation_handle;
+  NavigationRequest* request;
   if (committing_navigation_request) {
-    navigation_handle = committing_navigation_request->navigation_handle();
+    request = committing_navigation_request.get();
   } else {
-    navigation_handle = GetNavigationHandle();
+    request = navigation_request();
   }
 
-  if (navigation_handle) {
+  if (request && request->IsNavigationStarted()) {
     main_frame_request_ids_ = {validated_params->request_id,
-                               navigation_handle->GetGlobalRequestID()};
+                               request->GetGlobalRequestID()};
     if (deferred_main_frame_load_info_)
       ResourceLoadComplete(std::move(deferred_main_frame_load_info_));
   }
@@ -7528,27 +7528,26 @@
                                           base::debug::CrashKeySize::Size256),
       last_successful_url().GetOrigin().spec());
 
-  if (navigation_request && navigation_request->navigation_handle()) {
-    NavigationHandleImpl* handle = navigation_request->navigation_handle();
+  if (navigation_request && navigation_request->IsNavigationStarted()) {
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_renderer_initiated",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->IsRendererInitiated()));
+        bool_to_crash_key(navigation_request->IsRendererInitiated()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_server_redirect",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->WasServerRedirect()));
+        bool_to_crash_key(navigation_request->WasServerRedirect()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_form_submission",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->IsFormSubmission()));
+        bool_to_crash_key(navigation_request->IsFormSubmission()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_error_page",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->IsErrorPage()));
+        bool_to_crash_key(navigation_request->IsErrorPage()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("from_begin_navigation",
@@ -7563,14 +7562,14 @@
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("initiator_origin",
                                             base::debug::CrashKeySize::Size64),
-        handle->GetInitiatorOrigin()
-            ? handle->GetInitiatorOrigin()->GetDebugString()
+        navigation_request->GetInitiatorOrigin()
+            ? navigation_request->GetInitiatorOrigin()->GetDebugString()
             : "none");
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("starting_site_instance",
                                             base::debug::CrashKeySize::Size64),
-        handle->GetStartingSiteInstance()->GetSiteURL().spec());
+        navigation_request->GetStartingSiteInstance()->GetSiteURL().spec());
 
     // Recompute the target SiteInstance to see if it matches the current
     // one at commit time.
@@ -7630,39 +7629,38 @@
                                           base::debug::CrashKeySize::Size32),
       bool_to_crash_key(IsCrossProcessSubframe()));
 
-  if (navigation_request && navigation_request->navigation_handle()) {
-    NavigationHandleImpl* handle = navigation_request->navigation_handle();
+  if (navigation_request && navigation_request->IsNavigationStarted()) {
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_renderer_initiated",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->IsRendererInitiated()));
+        bool_to_crash_key(navigation_request->IsRendererInitiated()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_server_redirect",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->WasServerRedirect()));
+        bool_to_crash_key(navigation_request->WasServerRedirect()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_form_submission",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->IsFormSubmission()));
+        bool_to_crash_key(navigation_request->IsFormSubmission()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("is_error_page",
                                             base::debug::CrashKeySize::Size32),
-        bool_to_crash_key(handle->IsErrorPage()));
+        bool_to_crash_key(navigation_request->IsErrorPage()));
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("initiator_origin",
                                             base::debug::CrashKeySize::Size64),
-        handle->GetInitiatorOrigin()
-            ? handle->GetInitiatorOrigin()->GetDebugString()
+        navigation_request->GetInitiatorOrigin()
+            ? navigation_request->GetInitiatorOrigin()->GetDebugString()
             : "none");
 
     base::debug::SetCrashKeyString(
         base::debug::AllocateCrashKeyString("starting_site_instance",
                                             base::debug::CrashKeySize::Size64),
-        handle->GetStartingSiteInstance()->GetSiteURL().spec());
+        navigation_request->GetStartingSiteInstance()->GetSiteURL().spec());
   }
 }
 
diff --git a/content/browser/native_file_system/native_file_system_directory_handle_impl.cc b/content/browser/native_file_system/native_file_system_directory_handle_impl.cc
index 6a55aff5..314ce90 100644
--- a/content/browser/native_file_system/native_file_system_directory_handle_impl.cc
+++ b/content/browser/native_file_system/native_file_system_directory_handle_impl.cc
@@ -22,8 +22,7 @@
 using blink::mojom::NativeFileSystemEntryPtr;
 using blink::mojom::NativeFileSystemHandle;
 using blink::mojom::NativeFileSystemStatus;
-using blink::mojom::NativeFileSystemTransferTokenPtr;
-using blink::mojom::NativeFileSystemTransferTokenRequest;
+using blink::mojom::NativeFileSystemTransferToken;
 
 namespace content {
 
@@ -205,7 +204,7 @@
 }
 
 void NativeFileSystemDirectoryHandleImpl::Transfer(
-    NativeFileSystemTransferTokenRequest token) {
+    mojo::PendingReceiver<NativeFileSystemTransferToken> token) {
   DCHECK_CURRENTLY_ON(BrowserThread::IO);
 
   manager()->CreateTransferToken(*this, std::move(token));
diff --git a/content/browser/native_file_system/native_file_system_directory_handle_impl.h b/content/browser/native_file_system/native_file_system_directory_handle_impl.h
index e1e0885..3e63dac 100644
--- a/content/browser/native_file_system/native_file_system_directory_handle_impl.h
+++ b/content/browser/native_file_system/native_file_system_directory_handle_impl.h
@@ -10,6 +10,7 @@
 #include "base/memory/weak_ptr.h"
 #include "components/services/filesystem/public/mojom/types.mojom.h"
 #include "content/browser/native_file_system/native_file_system_handle_base.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
 #include "storage/browser/fileapi/file_system_url.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom.h"
 
@@ -47,7 +48,8 @@
                    bool recurse,
                    RemoveEntryCallback callback) override;
   void Transfer(
-      blink::mojom::NativeFileSystemTransferTokenRequest token) override;
+      mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken> token)
+      override;
 
  private:
   // State that is kept for the duration of a GetEntries/ReadDirectory call.
diff --git a/content/browser/native_file_system/native_file_system_file_handle_impl.cc b/content/browser/native_file_system/native_file_system_file_handle_impl.cc
index 3752720..f4e0c98 100644
--- a/content/browser/native_file_system/native_file_system_file_handle_impl.cc
+++ b/content/browser/native_file_system/native_file_system_file_handle_impl.cc
@@ -89,7 +89,7 @@
 }
 
 void NativeFileSystemFileHandleImpl::Transfer(
-    blink::mojom::NativeFileSystemTransferTokenRequest token) {
+    mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken> token) {
   DCHECK_CURRENTLY_ON(BrowserThread::IO);
 
   manager()->CreateTransferToken(*this, std::move(token));
diff --git a/content/browser/native_file_system/native_file_system_file_handle_impl.h b/content/browser/native_file_system/native_file_system_file_handle_impl.h
index ed2e3f9..b4a90ec3 100644
--- a/content/browser/native_file_system/native_file_system_file_handle_impl.h
+++ b/content/browser/native_file_system/native_file_system_file_handle_impl.h
@@ -10,6 +10,7 @@
 #include "content/browser/native_file_system/native_file_system_handle_base.h"
 #include "content/browser/native_file_system/native_file_system_manager_impl.h"
 #include "content/common/content_export.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
 #include "storage/browser/fileapi/file_system_url.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_file_handle.mojom.h"
 
@@ -46,7 +47,8 @@
   void CreateFileWriter(bool keep_existing_data,
                         CreateFileWriterCallback callback) override;
   void Transfer(
-      blink::mojom::NativeFileSystemTransferTokenRequest token) override;
+      mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken> token)
+      override;
 
   void set_max_swap_files_for_testing(int max) { max_swap_files_ = max; }
 
diff --git a/content/browser/native_file_system/native_file_system_manager_impl.cc b/content/browser/native_file_system/native_file_system_manager_impl.cc
index 2aa20b7..9c3e605 100644
--- a/content/browser/native_file_system/native_file_system_manager_impl.cc
+++ b/content/browser/native_file_system/native_file_system_manager_impl.cc
@@ -351,27 +351,31 @@
 
 void NativeFileSystemManagerImpl::CreateTransferToken(
     const NativeFileSystemFileHandleImpl& file,
-    blink::mojom::NativeFileSystemTransferTokenRequest request) {
+    mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken>
+        receiver) {
   return CreateTransferTokenImpl(file.url(), file.handle_state(),
-                                 /*is_directory=*/false, std::move(request));
+                                 /*is_directory=*/false, std::move(receiver));
 }
 
 void NativeFileSystemManagerImpl::CreateTransferToken(
     const NativeFileSystemDirectoryHandleImpl& directory,
-    blink::mojom::NativeFileSystemTransferTokenRequest request) {
+    mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken>
+        receiver) {
   return CreateTransferTokenImpl(directory.url(), directory.handle_state(),
-                                 /*is_directory=*/true, std::move(request));
+                                 /*is_directory=*/true, std::move(receiver));
 }
 
 void NativeFileSystemManagerImpl::ResolveTransferToken(
-    blink::mojom::NativeFileSystemTransferTokenPtr token,
+    mojo::PendingRemote<blink::mojom::NativeFileSystemTransferToken> token,
     ResolvedTokenCallback callback) {
   DCHECK_CURRENTLY_ON(BrowserThread::IO);
 
-  auto* raw_token = token.get();
+  mojo::Remote<blink::mojom::NativeFileSystemTransferToken> token_remote(
+      std::move(token));
+  auto* raw_token = token_remote.get();
   raw_token->GetInternalID(mojo::WrapCallbackWithDefaultInvokeIfNotRun(
       base::BindOnce(&NativeFileSystemManagerImpl::DoResolveTransferToken,
-                     weak_factory_.GetWeakPtr(), std::move(token),
+                     weak_factory_.GetWeakPtr(), std::move(token_remote),
                      std::move(callback)),
       base::UnguessableToken()));
 }
@@ -554,25 +558,20 @@
     const storage::FileSystemURL& url,
     const SharedHandleState& handle_state,
     bool is_directory,
-    blink::mojom::NativeFileSystemTransferTokenRequest request) {
+    mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken>
+        receiver) {
   DCHECK_CURRENTLY_ON(BrowserThread::IO);
 
   auto token_impl = std::make_unique<NativeFileSystemTransferTokenImpl>(
       url, handle_state,
       is_directory ? NativeFileSystemTransferTokenImpl::HandleType::kDirectory
-                   : NativeFileSystemTransferTokenImpl::HandleType::kFile);
+                   : NativeFileSystemTransferTokenImpl::HandleType::kFile,
+      this, std::move(receiver));
   auto token = token_impl->token();
-  blink::mojom::NativeFileSystemTransferTokenPtr result;
-  auto emplace_result = transfer_tokens_.emplace(
-      std::piecewise_construct, std::forward_as_tuple(token),
-      std::forward_as_tuple(std::move(token_impl), std::move(request)));
-  DCHECK(emplace_result.second);
-  emplace_result.first->second.set_connection_error_handler(base::BindOnce(
-      &NativeFileSystemManagerImpl::TransferTokenConnectionErrorHandler,
-      base::Unretained(this), token));
+  transfer_tokens_.emplace(token, std::move(token_impl));
 }
 
-void NativeFileSystemManagerImpl::TransferTokenConnectionErrorHandler(
+void NativeFileSystemManagerImpl::RemoveToken(
     const base::UnguessableToken& token) {
   DCHECK_CURRENTLY_ON(BrowserThread::IO);
 
@@ -581,7 +580,7 @@
 }
 
 void NativeFileSystemManagerImpl::DoResolveTransferToken(
-    blink::mojom::NativeFileSystemTransferTokenPtr,
+    mojo::Remote<blink::mojom::NativeFileSystemTransferToken>,
     ResolvedTokenCallback callback,
     const base::UnguessableToken& token) {
   DCHECK_CURRENTLY_ON(BrowserThread::IO);
@@ -590,8 +589,7 @@
   if (it == transfer_tokens_.end()) {
     std::move(callback).Run(nullptr);
   } else {
-    std::move(callback).Run(
-        static_cast<NativeFileSystemTransferTokenImpl*>(it->second.impl()));
+    std::move(callback).Run(it->second.get());
   }
 }
 
diff --git a/content/browser/native_file_system/native_file_system_manager_impl.h b/content/browser/native_file_system/native_file_system_manager_impl.h
index eed954b..b4454d7 100644
--- a/content/browser/native_file_system/native_file_system_manager_impl.h
+++ b/content/browser/native_file_system/native_file_system_manager_impl.h
@@ -13,8 +13,11 @@
 #include "content/public/browser/browser_thread.h"
 #include "content/public/browser/native_file_system_entry_factory.h"
 #include "content/public/browser/native_file_system_permission_context.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 #include "mojo/public/cpp/bindings/receiver_set.h"
-#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "mojo/public/cpp/bindings/remote.h"
 #include "mojo/public/cpp/bindings/strong_binding_set.h"
 #include "mojo/public/cpp/bindings/unique_receiver_set.h"
 #include "storage/browser/fileapi/file_system_url.h"
@@ -136,10 +139,12 @@
   // Create a transfer token for a specific file or directory.
   void CreateTransferToken(
       const NativeFileSystemFileHandleImpl& file,
-      blink::mojom::NativeFileSystemTransferTokenRequest request);
+      mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken>
+          receiver);
   void CreateTransferToken(
       const NativeFileSystemDirectoryHandleImpl& directory,
-      blink::mojom::NativeFileSystemTransferTokenRequest request);
+      mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken>
+          receiver);
 
   // Given a mojom transfer token, looks up the token in our internal list of
   // valid tokens. Calls the callback with the found token, or nullptr if no
@@ -147,7 +152,7 @@
   using ResolvedTokenCallback =
       base::OnceCallback<void(NativeFileSystemTransferTokenImpl*)>;
   void ResolveTransferToken(
-      blink::mojom::NativeFileSystemTransferTokenPtr token,
+      mojo::PendingRemote<blink::mojom::NativeFileSystemTransferToken> token,
       ResolvedTokenCallback callback);
 
   storage::FileSystemContext* context() {
@@ -170,6 +175,10 @@
     permission_context_ = permission_context;
   }
 
+  // Remove |token| from |transfer_tokens_|. It is an error to try to remove a
+  // token that doesn't exist.
+  void RemoveToken(const base::UnguessableToken& token);
+
  private:
   friend class NativeFileSystemFileHandleImpl;
 
@@ -205,11 +214,12 @@
       const storage::FileSystemURL& url,
       const SharedHandleState& handle_state,
       bool is_directory,
-      blink::mojom::NativeFileSystemTransferTokenRequest request);
-  void TransferTokenConnectionErrorHandler(const base::UnguessableToken& token);
-  void DoResolveTransferToken(blink::mojom::NativeFileSystemTransferTokenPtr,
-                              ResolvedTokenCallback callback,
-                              const base::UnguessableToken& token);
+      mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken>
+          receiver);
+  void DoResolveTransferToken(
+      mojo::Remote<blink::mojom::NativeFileSystemTransferToken>,
+      ResolvedTokenCallback callback,
+      const base::UnguessableToken& token);
 
   // Creates a FileSystemURL which corresponds to a FilePath and Origin.
   struct FileSystemURLAndFSHandle {
@@ -258,14 +268,11 @@
 
   bool off_the_record_;
 
-  // Transfer token bindings are stored in what is effectively a
-  // StrongBindingMap. The Binding instances own the implementation, and tokens
-  // are removed from this map when the mojo connection is closed.
-  using TransferTokenBinding =
-      mojo::Binding<blink::mojom::NativeFileSystemTransferToken,
-                    mojo::UniquePtrImplRefTraits<
-                        blink::mojom::NativeFileSystemTransferToken>>;
-  std::map<base::UnguessableToken, TransferTokenBinding> transfer_tokens_;
+  // NativeFileSystemTransferTokenImpl owns a Transfer token receiver and is
+  // removed from this map when the mojo connection is closed.
+  std::map<base::UnguessableToken,
+           std::unique_ptr<NativeFileSystemTransferTokenImpl>>
+      transfer_tokens_;
 
   base::WeakPtrFactory<NativeFileSystemManagerImpl> weak_factory_{this};
   DISALLOW_COPY_AND_ASSIGN(NativeFileSystemManagerImpl);
diff --git a/content/browser/native_file_system/native_file_system_transfer_token_impl.cc b/content/browser/native_file_system/native_file_system_transfer_token_impl.cc
index 8dd98bb..d0066bd 100644
--- a/content/browser/native_file_system/native_file_system_transfer_token_impl.cc
+++ b/content/browser/native_file_system/native_file_system_transfer_token_impl.cc
@@ -9,19 +9,34 @@
 NativeFileSystemTransferTokenImpl::NativeFileSystemTransferTokenImpl(
     const storage::FileSystemURL& url,
     const SharedHandleState& handle_state,
-    HandleType type)
+    HandleType type,
+    NativeFileSystemManagerImpl* manager,
+    mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken> receiver)
     : token_(base::UnguessableToken::Create()),
       url_(url),
       handle_state_(handle_state),
-      type_(type) {
+      type_(type),
+      manager_(manager),
+      receiver_(this, std::move(receiver)) {
+  DCHECK(manager_);
   DCHECK_EQ(url_.mount_type() == storage::kFileSystemTypeIsolated,
             handle_state_.file_system.is_valid())
       << url_.mount_type();
+  receiver_.set_disconnect_handler(
+      base::BindOnce(&NativeFileSystemTransferTokenImpl::OnMojoDisconnect,
+                     base::Unretained(this)));
 }
 
+NativeFileSystemTransferTokenImpl::~NativeFileSystemTransferTokenImpl() =
+    default;
+
 void NativeFileSystemTransferTokenImpl::GetInternalID(
     GetInternalIDCallback callback) {
   std::move(callback).Run(token_);
 }
 
+void NativeFileSystemTransferTokenImpl::OnMojoDisconnect() {
+  manager_->RemoveToken(token_);
+}
+
 }  // namespace content
diff --git a/content/browser/native_file_system/native_file_system_transfer_token_impl.h b/content/browser/native_file_system/native_file_system_transfer_token_impl.h
index 0c1e3a3..31649d8 100644
--- a/content/browser/native_file_system/native_file_system_transfer_token_impl.h
+++ b/content/browser/native_file_system/native_file_system_transfer_token_impl.h
@@ -6,6 +6,8 @@
 #define CONTENT_BROWSER_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_TRANSFER_TOKEN_IMPL_H_
 
 #include "content/browser/native_file_system/native_file_system_manager_impl.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 #include "storage/browser/fileapi/file_system_url.h"
 #include "storage/browser/fileapi/isolated_context.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_transfer_token.mojom.h"
@@ -24,9 +26,14 @@
 
   enum class HandleType { kFile, kDirectory };
 
-  NativeFileSystemTransferTokenImpl(const storage::FileSystemURL& url,
-                                    const SharedHandleState& handle_state,
-                                    HandleType type);
+  NativeFileSystemTransferTokenImpl(
+      const storage::FileSystemURL& url,
+      const SharedHandleState& handle_state,
+      HandleType type,
+      NativeFileSystemManagerImpl* manager,
+      mojo::PendingReceiver<blink::mojom::NativeFileSystemTransferToken>
+          receiver);
+  ~NativeFileSystemTransferTokenImpl() override;
 
   const base::UnguessableToken& token() const { return token_; }
   const storage::FileSystemURL& url() const { return url_; }
@@ -36,10 +43,15 @@
   void GetInternalID(GetInternalIDCallback callback) override;
 
  private:
+  void OnMojoDisconnect();
+
   const base::UnguessableToken token_;
   const storage::FileSystemURL url_;
   const SharedHandleState handle_state_;
   const HandleType type_;
+  // Raw pointer since NativeFileSystemManagerImpl owns |this|.
+  NativeFileSystemManagerImpl* const manager_;
+  mojo::Receiver<blink::mojom::NativeFileSystemTransferToken> receiver_;
 
   DISALLOW_COPY_AND_ASSIGN(NativeFileSystemTransferTokenImpl);
 };
diff --git a/content/browser/navigation_browsertest.cc b/content/browser/navigation_browsertest.cc
index 6452bc82..03310531 100644
--- a/content/browser/navigation_browsertest.cc
+++ b/content/browser/navigation_browsertest.cc
@@ -320,6 +320,34 @@
                          NetworkIsolationNavigationBrowserTest,
                          ::testing::Bool());
 
+class NavigationBrowserTestReferrerPolicy
+    : public ContentBrowserTest,
+      public ::testing::WithParamInterface<network::mojom::ReferrerPolicy> {
+ protected:
+  void SetUpOnMainThread() override {
+    ASSERT_TRUE(embedded_test_server()->Start());
+    ContentBrowserTest::SetUpOnMainThread();
+  }
+
+  network::mojom::ReferrerPolicy GetReferrerPolicy() const {
+    return GetParam();
+  }
+};
+
+INSTANTIATE_TEST_SUITE_P(
+    /* no prefix */,
+    NavigationBrowserTestReferrerPolicy,
+    ::testing::Values(network::mojom::ReferrerPolicy::kAlways,
+                      network::mojom::ReferrerPolicy::kDefault,
+                      network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade,
+                      network::mojom::ReferrerPolicy::kNever,
+                      network::mojom::ReferrerPolicy::kOrigin,
+                      network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin,
+                      network::mojom::ReferrerPolicy::
+                          kNoReferrerWhenDowngradeOriginWhenCrossOrigin,
+                      network::mojom::ReferrerPolicy::kSameOrigin,
+                      network::mojom::ReferrerPolicy::kStrictOrigin));
+
 // Ensure that browser initiated basic navigations work.
 IN_PROC_BROWSER_TEST_P(NavigationBrowserTest, BrowserInitiatedNavigations) {
   // Perform a navigation with no live renderer.
@@ -607,6 +635,62 @@
   EXPECT_EQ(kInsecureUrl, shell()->web_contents()->GetLastCommittedURL());
 }
 
+// Ensure the correctness of a navigation request's referrer. This is a
+// regression test for https://crbug.com/1004083.
+IN_PROC_BROWSER_TEST_P(NavigationBrowserTestReferrerPolicy, ReferrerPolicy) {
+  const GURL kDestination(embedded_test_server()->GetURL("/title1.html"));
+  const GURL kReferrerURL(embedded_test_server()->GetURL("/referrer-page"));
+  const url::Origin kReferrerOrigin = url::Origin::Create(kReferrerURL);
+
+  // It is possible that the referrer URL does not match what the policy
+  // demands (e.g., non-empty URL and kNever policy), so we'll test that the
+  // correct referrer is generated, and that the navigation succeeds.
+  const Referrer referrer(kReferrerURL, GetReferrerPolicy());
+
+  // Navigate to a resource whose destination URL is same-origin with the
+  // navigation's referrer. The final referrer should be generated correctly.
+  NavigationController::LoadURLParams load_params(kDestination);
+  load_params.referrer = referrer;
+  TestNavigationManager manager(shell()->web_contents(), kDestination);
+  shell()->web_contents()->GetController().LoadURLWithParams(load_params);
+  EXPECT_TRUE(manager.WaitForRequestStart());
+
+  // The referrer should have been sanitized.
+  FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents())
+                            ->GetMainFrame()
+                            ->frame_tree_node();
+  ASSERT_TRUE(root->navigation_request());
+  switch (GetReferrerPolicy()) {
+    case network::mojom::ReferrerPolicy::kAlways:
+    case network::mojom::ReferrerPolicy::kDefault:
+    case network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade:
+    case network::mojom::ReferrerPolicy::kOriginWhenCrossOrigin:
+    case network::mojom::ReferrerPolicy::
+        kNoReferrerWhenDowngradeOriginWhenCrossOrigin:
+    case network::mojom::ReferrerPolicy::kSameOrigin:
+      EXPECT_EQ(
+          kReferrerURL,
+          root->navigation_request()->navigation_handle()->GetReferrer().url);
+      break;
+    case network::mojom::ReferrerPolicy::kNever:
+      EXPECT_EQ(
+          GURL(),
+          root->navigation_request()->navigation_handle()->GetReferrer().url);
+      break;
+    case network::mojom::ReferrerPolicy::kOrigin:
+    case network::mojom::ReferrerPolicy::kStrictOrigin:
+      EXPECT_EQ(
+          kReferrerOrigin.GetURL(),
+          root->navigation_request()->navigation_handle()->GetReferrer().url);
+      break;
+  }
+
+  // The navigation should commit without being blocked.
+  EXPECT_TRUE(manager.WaitForResponse());
+  manager.WaitForNavigationFinished();
+  EXPECT_EQ(kDestination, shell()->web_contents()->GetLastCommittedURL());
+}
+
 // Test to verify that an exploited renderer process trying to upload a file
 // it hasn't been explicitly granted permissions to is correctly terminated.
 IN_PROC_BROWSER_TEST_P(NavigationBrowserTest, PostUploadIllegalFilePath) {
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc
index 7718d40..65b6d31 100644
--- a/content/browser/renderer_host/render_process_host_impl.cc
+++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -2964,6 +2964,7 @@
     switches::kDisableMediaSuspend,
     switches::kDisableNotifications,
     switches::kDisableOopRasterization,
+    switches::kEnableDeJelly,
     switches::kDisableOriginTrialControlledBlinkFeatures,
     switches::kDisablePepper3DImageChromium,
     switches::kDisablePerfetto,
diff --git a/content/browser/webauth/authenticator_common.cc b/content/browser/webauth/authenticator_common.cc
index 7fb7b06..0143c2f 100644
--- a/content/browser/webauth/authenticator_common.cc
+++ b/content/browser/webauth/authenticator_common.cc
@@ -558,11 +558,17 @@
   }
 
   if (base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport)) {
+    std::vector<device::CableDiscoveryData> cable_pairings =
+        request_delegate_->GetCablePairings();
+    const bool have_paired_phones = !cable_pairings.empty();
+
     device::QRGeneratorKey qr_generator_key(
         device::CableDiscoveryData::NewQRKey());
     if (request_delegate_->SetCableTransportInfo(
-            /*cable_extension_provided=*/false, qr_generator_key)) {
-      discovery_factory_->set_cable_data({}, std::move(qr_generator_key));
+            /*cable_extension_provided=*/false, have_paired_phones,
+            qr_generator_key)) {
+      discovery_factory_->set_cable_data(cable_pairings,
+                                         std::move(qr_generator_key));
     }
   }
 
@@ -603,7 +609,7 @@
   }
 
   std::vector<device::CableDiscoveryData> cable_pairings;
-  bool have_cable_extension;
+  bool have_cable_extension = false;
   if (ctap_get_assertion_request_->cable_extension &&
       request_delegate_->ShouldPermitCableExtension(caller_origin_) &&
       IsFocused()) {
@@ -612,14 +618,18 @@
   }
 
   base::Optional<device::QRGeneratorKey> qr_generator_key;
+  bool have_paired_phones = false;
   if (base::FeatureList::IsEnabled(device::kWebAuthPhoneSupport)) {
     qr_generator_key.emplace(device::CableDiscoveryData::NewQRKey());
-    request_delegate_->AppendCablePairings(&cable_pairings);
+    auto paired_phones = request_delegate_->GetCablePairings();
+    have_paired_phones = !paired_phones.empty();
+    cable_pairings.insert(cable_pairings.end(), paired_phones.begin(),
+                          paired_phones.end());
   }
 
   if ((!cable_pairings.empty() || qr_generator_key.has_value()) &&
-      request_delegate_->SetCableTransportInfo(have_cable_extension,
-                                               qr_generator_key)) {
+      request_delegate_->SetCableTransportInfo(
+          have_cable_extension, have_paired_phones, qr_generator_key)) {
     discovery_factory_->set_cable_data(std::move(cable_pairings),
                                        std::move(qr_generator_key));
   }
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc
index d7faf3a..486c86f 100644
--- a/content/child/runtime_features.cc
+++ b/content/child/runtime_features.cc
@@ -453,9 +453,9 @@
   }
 
   if (base::FeatureList::IsEnabled(
-          blink::features::kForbidSyncXHRInPageDismissal) &&
-      !command_line.HasSwitch(switches::kAllowSyncXHRInPageDismissal)) {
-    WebRuntimeFeatures::EnableForbidSyncXHRInPageDismissal(true);
+          blink::features::kAllowSyncXHRInPageDismissal) ||
+      command_line.HasSwitch(switches::kAllowSyncXHRInPageDismissal)) {
+    WebRuntimeFeatures::EnableAllowSyncXHRInPageDismissal(true);
   }
 
   WebRuntimeFeatures::EnableAutoplayIgnoresWebAudio(
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn
index 03e7f4a0..2c949bb 100644
--- a/content/public/android/BUILD.gn
+++ b/content/public/android/BUILD.gn
@@ -295,6 +295,7 @@
     "java/src/org/chromium/content_public/common/ScreenOrientationConstants.java",
     "java/src/org/chromium/content_public/common/ServiceManagerConnection.java",
     "java/src/org/chromium/content_public/common/UseZoomForDSFPolicy.java",
+    "java/src/org/chromium/content_public/app/ChildProcessServiceFactory.java",
   ]
   annotation_processor_deps = [ "//base/android/jni_generator:jni_processor" ]
 }
diff --git a/content/public/android/generate_child_service.py b/content/public/android/generate_child_service.py
index f29047b..ebe07f2d 100755
--- a/content/public/android/generate_child_service.py
+++ b/content/public/android/generate_child_service.py
@@ -20,10 +20,13 @@
 
 package org.chromium.content.app;
 
+import org.chromium.base.annotations.MainDex;
+
 /**
  * This is needed to register multiple SandboxedProcess services so that we
  * can have more than one sandboxed process.
  */
+@MainDex
 public class SandboxedProcessService{0} extends SandboxedProcessService {{
 }}"""
   return template.format(str(i))
diff --git a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessService.java b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessService.java
index 301b95f..5e3230c 100644
--- a/content/public/android/java/src/org/chromium/content/app/ContentChildProcessService.java
+++ b/content/public/android/java/src/org/chromium/content/app/ContentChildProcessService.java
@@ -4,10 +4,16 @@
 
 package org.chromium.content.app;
 
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+
 import org.chromium.base.process_launcher.ChildProcessService;
+import org.chromium.content_public.app.ChildProcessServiceFactory;
 
 /**
- * Implementation of ChildProcessService that uses the content specific delegate.
+ * Service implementation which calls through to a ChildProcessService that uses the content
+ * specific delegate.
  * The [Sandboxed|Privileged]ProcessService0, 1.. etc classes are the subclasses for sandboxed/non
  * sandboxed child processes.
  * The embedding application must declare these service instances in the application section
@@ -20,8 +26,27 @@
  *     <service android:name="org.chromium.content.app.[Sandboxed|Privileged]ProcessServiceX"
  *              android:process=":[sandboxed|privileged]_processX" />
  */
-public class ContentChildProcessService extends ChildProcessService {
-    public ContentChildProcessService() {
-        super(new ContentChildProcessServiceDelegate());
+public class ContentChildProcessService extends Service {
+    private ChildProcessService mService;
+
+    public ContentChildProcessService() {}
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mService = ChildProcessServiceFactory.create(this, getApplicationContext());
+        mService.onCreate();
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        mService.onDestroy();
+        mService = null;
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return mService.onBind(intent);
     }
 }
diff --git a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService0.java b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService0.java
index 8c54a6b..4ecfc4e 100644
--- a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService0.java
+++ b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService0.java
@@ -4,10 +4,11 @@
 
 package org.chromium.content.app;
 
+import org.chromium.base.annotations.MainDex;
+
 /**
  * This is needed to register multiple PrivilegedProcess services so that we can have
  * more than one unsandboxed process.
  */
-public class PrivilegedProcessService0 extends PrivilegedProcessService {
-
-}
+@MainDex
+public class PrivilegedProcessService0 extends PrivilegedProcessService {}
diff --git a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService1.java b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService1.java
index 95239a2c..dbca899f 100644
--- a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService1.java
+++ b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService1.java
@@ -4,10 +4,11 @@
 
 package org.chromium.content.app;
 
+import org.chromium.base.annotations.MainDex;
+
 /**
  * This is needed to register multiple PrivilegedProcess services so that we can have
  * more than one unsandboxed process.
  */
-public class PrivilegedProcessService1 extends PrivilegedProcessService {
-
-}
+@MainDex
+public class PrivilegedProcessService1 extends PrivilegedProcessService {}
diff --git a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService2.java b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService2.java
index dadfb1c..83a27f1 100644
--- a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService2.java
+++ b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService2.java
@@ -4,10 +4,11 @@
 
 package org.chromium.content.app;
 
+import org.chromium.base.annotations.MainDex;
+
 /**
  * This is needed to register multiple PrivilegedProcess services so that we can have
  * more than one unsandboxed process.
  */
-public class PrivilegedProcessService2 extends PrivilegedProcessService {
-
-}
+@MainDex
+public class PrivilegedProcessService2 extends PrivilegedProcessService {}
diff --git a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService3.java b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService3.java
index 1105301..4093d5f 100644
--- a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService3.java
+++ b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService3.java
@@ -4,8 +4,11 @@
 
 package org.chromium.content.app;
 
+import org.chromium.base.annotations.MainDex;
+
 /**
  * This is needed to register multiple PrivilegedProcess services so that we can have
  * more than one unsandboxed process.
  */
+@MainDex
 public class PrivilegedProcessService3 extends PrivilegedProcessService {}
diff --git a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService4.java b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService4.java
index 28b09eb8..347c4c1 100644
--- a/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService4.java
+++ b/content/public/android/java/src/org/chromium/content/app/PrivilegedProcessService4.java
@@ -4,8 +4,11 @@
 
 package org.chromium.content.app;
 
+import org.chromium.base.annotations.MainDex;
+
 /**
  * This is needed to register multiple PrivilegedProcess services so that we can have
  * more than one unsandboxed process.
  */
+@MainDex
 public class PrivilegedProcessService4 extends PrivilegedProcessService {}
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessCreationParamsImpl.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessCreationParamsImpl.java
index 802b916..b549919 100644
--- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessCreationParamsImpl.java
+++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessCreationParamsImpl.java
@@ -15,6 +15,10 @@
 public class ChildProcessCreationParamsImpl {
     private static final String EXTRA_LIBRARY_PROCESS_TYPE =
             "org.chromium.content.common.child_service_params.library_process_type";
+    private static final String PRIVILEGED_SERVICES_NAME =
+            "org.chromium.content.app.PrivilegedProcessService";
+    private static final String SANDBOXED_SERVICES_NAME =
+            "org.chromium.content.app.SandboxedProcessService";
 
     // Members should all be immutable to avoid worrying about thread safety.
     private static String sPackageNameForService;
@@ -24,6 +28,8 @@
     // Use only the explicit WebContents.setImportance signal, and ignore other implicit
     // signals in content.
     private static boolean sIgnoreVisibilityForImportance;
+    private static String sPrivilegedServicesName;
+    private static String sSandboxedServicesName;
 
     private static boolean sInitialized;
 
@@ -32,13 +38,18 @@
     /** Set params. This should be called once on start up. */
     public static void set(String packageNameForService, boolean isExternalSandboxedService,
             int libraryProcessType, boolean bindToCallerCheck,
-            boolean ignoreVisibilityForImportance) {
+            boolean ignoreVisibilityForImportance, String privilegedServicesName,
+            String sandboxedServicesName) {
         assert !sInitialized;
         sPackageNameForService = packageNameForService;
         sIsSandboxedServiceExternal = isExternalSandboxedService;
         sLibraryProcessType = libraryProcessType;
         sBindToCallerCheck = bindToCallerCheck;
         sIgnoreVisibilityForImportance = ignoreVisibilityForImportance;
+        sPrivilegedServicesName =
+                privilegedServicesName == null ? PRIVILEGED_SERVICES_NAME : privilegedServicesName;
+        sSandboxedServicesName =
+                sandboxedServicesName == null ? SANDBOXED_SERVICES_NAME : sandboxedServicesName;
         sInitialized = true;
     }
 
@@ -66,4 +77,12 @@
     public static int getLibraryProcessType(Bundle extras) {
         return extras.getInt(EXTRA_LIBRARY_PROCESS_TYPE, LibraryProcessType.PROCESS_CHILD);
     }
+
+    public static String getPrivilegedServicesName() {
+        return sInitialized ? sPrivilegedServicesName : PRIVILEGED_SERVICES_NAME;
+    }
+
+    public static String getSandboxedServicesName() {
+        return sInitialized ? sSandboxedServicesName : SANDBOXED_SERVICES_NAME;
+    }
 }
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java
index 615bd78f4..263fb42 100644
--- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java
+++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelperImpl.java
@@ -56,12 +56,8 @@
     // Manifest values used to specify the service names.
     private static final String NUM_SANDBOXED_SERVICES_KEY =
             "org.chromium.content.browser.NUM_SANDBOXED_SERVICES";
-    private static final String SANDBOXED_SERVICES_NAME =
-            "org.chromium.content.app.SandboxedProcessService";
     private static final String NUM_PRIVILEGED_SERVICES_KEY =
             "org.chromium.content.browser.NUM_PRIVILEGED_SERVICES";
-    private static final String PRIVILEGED_SERVICES_NAME =
-            "org.chromium.content.app.PrivilegedProcessService";
 
     // Flag to check features after native is initialized.
     private static boolean sCheckedFeatures;
@@ -354,10 +350,11 @@
 
         if (!sandboxed) {
             if (sPrivilegedChildConnectionAllocator == null) {
-                sPrivilegedChildConnectionAllocator =
-                        ChildConnectionAllocator.create(context, LauncherThread.getHandler(), null,
-                                packageName, PRIVILEGED_SERVICES_NAME, NUM_PRIVILEGED_SERVICES_KEY,
-                                bindToCaller, bindAsExternalService, true /* useStrongBinding */);
+                sPrivilegedChildConnectionAllocator = ChildConnectionAllocator.create(context,
+                        LauncherThread.getHandler(), null, packageName,
+                        ChildProcessCreationParamsImpl.getPrivilegedServicesName(),
+                        NUM_PRIVILEGED_SERVICES_KEY, bindToCaller, bindAsExternalService,
+                        true /* useStrongBinding */);
             }
             return sPrivilegedChildConnectionAllocator;
         }
@@ -387,13 +384,15 @@
                                 bindToCaller, bindAsExternalService, false /* useStrongBinding */);
             } else if (ChildProcessConnection.supportVariableConnections()) {
                 connectionAllocator = ChildConnectionAllocator.createVariableSize(context,
-                        LauncherThread.getHandler(), packageName, SANDBOXED_SERVICES_NAME,
-                        bindToCaller, bindAsExternalService, false /* useStrongBinding */);
+                        LauncherThread.getHandler(), packageName,
+                        ChildProcessCreationParamsImpl.getSandboxedServicesName(), bindToCaller,
+                        bindAsExternalService, false /* useStrongBinding */);
             } else {
                 connectionAllocator = ChildConnectionAllocator.create(context,
                         LauncherThread.getHandler(), freeSlotRunnable, packageName,
-                        SANDBOXED_SERVICES_NAME, NUM_SANDBOXED_SERVICES_KEY, bindToCaller,
-                        bindAsExternalService, false /* useStrongBinding */);
+                        ChildProcessCreationParamsImpl.getSandboxedServicesName(),
+                        NUM_SANDBOXED_SERVICES_KEY, bindToCaller, bindAsExternalService,
+                        false /* useStrongBinding */);
             }
             if (sSandboxedServiceFactoryForTesting != null) {
                 connectionAllocator.setConnectionFactoryForTesting(
diff --git a/content/public/android/java/src/org/chromium/content_public/app/ChildProcessServiceFactory.java b/content/public/android/java/src/org/chromium/content_public/app/ChildProcessServiceFactory.java
new file mode 100644
index 0000000..c724ced
--- /dev/null
+++ b/content/public/android/java/src/org/chromium/content_public/app/ChildProcessServiceFactory.java
@@ -0,0 +1,20 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.content_public.app;
+
+import android.app.Service;
+import android.content.Context;
+
+import org.chromium.base.process_launcher.ChildProcessService;
+import org.chromium.content.app.ContentChildProcessServiceDelegate;
+
+/** Factory to create a service class that can call through to the content implementation. */
+public class ChildProcessServiceFactory {
+    public static ChildProcessService create(Service service, Context context) {
+        return new ChildProcessService(new ContentChildProcessServiceDelegate(), service, context);
+    }
+
+    private ChildProcessServiceFactory() {}
+}
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/ChildProcessCreationParams.java b/content/public/android/java/src/org/chromium/content_public/browser/ChildProcessCreationParams.java
index 29ebb4f0..c4ff203 100644
--- a/content/public/android/java/src/org/chromium/content_public/browser/ChildProcessCreationParams.java
+++ b/content/public/android/java/src/org/chromium/content_public/browser/ChildProcessCreationParams.java
@@ -13,11 +13,16 @@
  * child service binging flags.
  */
 public final class ChildProcessCreationParams {
-    /** Set params. This should be called once on start up. */
+    /**
+     * Set params. This should be called once on start up. If null is passed for
+     * privilegedServicesName or sandboxedServicesName, the default service names will be used.
+     */
     public static void set(String packageNameForService, boolean isExternalSandboxedService,
             int libraryProcessType, boolean bindToCallerCheck,
-            boolean ignoreVisibilityForImportance) {
+            boolean ignoreVisibilityForImportance, String privilegedServicesName,
+            String sandboxedServicesName) {
         ChildProcessCreationParamsImpl.set(packageNameForService, isExternalSandboxedService,
-                libraryProcessType, bindToCallerCheck, ignoreVisibilityForImportance);
+                libraryProcessType, bindToCallerCheck, ignoreVisibilityForImportance,
+                privilegedServicesName, sandboxedServicesName);
     }
 }
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherHelperTest.java b/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherHelperTest.java
index e8d2afb1..b733563 100644
--- a/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherHelperTest.java
+++ b/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherHelperTest.java
@@ -151,7 +151,8 @@
         // will fail to start and the ChildProcessLauncher will retry and use the slot 1.
         ChildProcessCreationParamsImpl.set(context.getPackageName(), false /* isExternalService */,
                 LibraryProcessType.PROCESS_CHILD, true /* bindToCallerCheck */,
-                false /* ignoreVisibilityForImportance */);
+                false /* ignoreVisibilityForImportance */, null /* privilegedServicesName */,
+                null /* sandboxedServicesName */);
         ChildProcessLauncherHelperImpl launcher =
                 startSandboxedChildProcess(BLOCK_UNTIL_SETUP, true /* doSetupConnection */);
 
@@ -257,7 +258,8 @@
         Context context = InstrumentationRegistry.getTargetContext();
         ChildProcessCreationParamsImpl.set(context.getPackageName(), false /* isExternalService */,
                 LibraryProcessType.PROCESS_CHILD, true /* bindToCallerCheck */,
-                false /* ignoreVisibilityForImportance */);
+                false /* ignoreVisibilityForImportance */, null /* privilegedServicesName */,
+                null /* sandboxedServicesName */);
         testWarmUpImpl();
     }
 
diff --git a/content/public/browser/authenticator_request_client_delegate.cc b/content/public/browser/authenticator_request_client_delegate.cc
index f30c751..6d7028f 100644
--- a/content/public/browser/authenticator_request_client_delegate.cc
+++ b/content/public/browser/authenticator_request_client_delegate.cc
@@ -61,12 +61,15 @@
 
 bool AuthenticatorRequestClientDelegate::SetCableTransportInfo(
     bool cable_extension_provided,
+    bool have_paired_phones,
     base::Optional<device::QRGeneratorKey> qr_generator_key) {
   return false;
 }
 
-void AuthenticatorRequestClientDelegate::AppendCablePairings(
-    std::vector<device::CableDiscoveryData>* pairings) {}
+std::vector<device::CableDiscoveryData>
+AuthenticatorRequestClientDelegate::GetCablePairings() {
+  return {};
+}
 
 void AuthenticatorRequestClientDelegate::SelectAccount(
     std::vector<device::AuthenticatorGetAssertionResponse> responses,
diff --git a/content/public/browser/authenticator_request_client_delegate.h b/content/public/browser/authenticator_request_client_delegate.h
index c560cd14..1882015 100644
--- a/content/public/browser/authenticator_request_client_delegate.h
+++ b/content/public/browser/authenticator_request_client_delegate.h
@@ -125,6 +125,9 @@
   // to advance to directly to guiding the user to check their phone as the site
   // is strongly indicating that it will work.
   //
+  // have_paired_phones is true if a previous call to |GetCablePairings|
+  // returned one or more caBLE pairings.
+  //
   // |qr_generator_key| is a random AES-256 key that can be used to
   // encrypt a coarse timestamp with |CableDiscoveryData::DeriveQRKeyMaterial|.
   // The UI may display a QR code with the resulting secret which, if
@@ -137,15 +140,15 @@
   // handshakes is irrelevant if the UI is not displaying the QR codes.
   virtual bool SetCableTransportInfo(
       bool cable_extension_provided,
+      bool have_paired_phones,
       base::Optional<device::QRGeneratorKey> qr_generator_key);
 
-  // AppendCablePairings appends any known caBLE pairing data to |discoveries|.
-  // For example, the embedder may know of pairings because it configured the
+  // GetCablePairings returns any known caBLE pairing data. For example, the
+  // embedder may know of pairings because it configured the
   // |FidoDiscoveryFactory| (using |CustomizeDiscoveryFactory|) to make a
   // callback when a phone offered long-term pairing data. Additionally, it may
   // know of pairings via some cloud-based service or sync feature.
-  virtual void AppendCablePairings(
-      std::vector<device::CableDiscoveryData>* pairings);
+  virtual std::vector<device::CableDiscoveryData> GetCablePairings();
 
   // SelectAccount is called to allow the embedder to select between one or more
   // accounts. This is triggered when the web page requests an unspecified
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc
index baf8d4bd8..ee197275 100644
--- a/content/public/common/content_features.cc
+++ b/content/public/common/content_features.cc
@@ -90,7 +90,7 @@
 // Enables support for parallel cache_storage operations via the
 // "max_shared_ops" fieldtrial parameter.
 const base::Feature kCacheStorageParallelOps{"CacheStorageParallelOps",
-                                             base::FEATURE_DISABLED_BY_DEFAULT};
+                                             base::FEATURE_ENABLED_BY_DEFAULT};
 
 // If Canvas2D Image Chromium is allowed, this feature controls whether it is
 // enabled.
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn
index 9f364b97..e9f1f2f1 100644
--- a/content/renderer/BUILD.gn
+++ b/content/renderer/BUILD.gn
@@ -202,6 +202,8 @@
     "media/webrtc/media_stream_track_metrics.h",
     "media/webrtc/media_stream_video_webrtc_sink.cc",
     "media/webrtc/media_stream_video_webrtc_sink.h",
+    "media/webrtc/peer_connection_dependency_factory.cc",
+    "media/webrtc/peer_connection_dependency_factory.h",
     "media/webrtc/peer_connection_tracker.cc",
     "media/webrtc/peer_connection_tracker.h",
     "media/webrtc/rtc_certificate_generator.cc",
@@ -236,6 +238,18 @@
     "navigation_state.h",
     "net_info_helper.cc",
     "net_info_helper.h",
+    "p2p/host_address_request.cc",
+    "p2p/host_address_request.h",
+    "p2p/ipc_socket_factory.cc",
+    "p2p/ipc_socket_factory.h",
+    "p2p/mdns_responder_adapter.cc",
+    "p2p/mdns_responder_adapter.h",
+    "p2p/port_allocator.cc",
+    "p2p/port_allocator.h",
+    "p2p/socket_client_impl.cc",
+    "p2p/socket_client_impl.h",
+    "p2p/socket_dispatcher.cc",
+    "p2p/socket_dispatcher.h",
     "page_properties.cc",
     "page_properties.h",
     "peripheral_content_heuristic.cc",
@@ -392,6 +406,7 @@
     "//gpu/command_buffer/client:gles2_interface",
     "//gpu/command_buffer/client:raster_interface",
     "//gpu/command_buffer/client:webgpu_interface",
+    "//jingle:webrtc_glue",
     "//media",
     "//media:media_buildflags",
     "//media/blink",
@@ -446,6 +461,7 @@
     "//third_party/webrtc/api/audio:aec3_config_json",
     "//third_party/webrtc/api/audio:aec3_factory",
     "//third_party/webrtc/api/audio_codecs:audio_codecs_api",
+    "//third_party/webrtc/api/rtc_event_log:rtc_event_log_factory",
     "//third_party/webrtc/api/video:video_bitrate_allocation",
     "//third_party/webrtc/api/video:video_frame",
     "//third_party/webrtc/api/video:video_frame_i420",
@@ -454,6 +470,7 @@
     "//third_party/webrtc/api/video_codecs:video_codecs_api",
     "//third_party/webrtc/common_video:common_video",
     "//third_party/webrtc/media:rtc_audio_video",
+    "//third_party/webrtc/media:rtc_internal_video_codecs",
     "//third_party/webrtc/media:rtc_media",
     "//third_party/webrtc/media:rtc_media_base",
     "//third_party/webrtc/media:rtc_simulcast_encoder_adapter",
@@ -463,6 +480,7 @@
     "//third_party/webrtc/modules/audio_processing:api",
     "//third_party/webrtc/modules/audio_processing:audio_processing_statistics",
     "//third_party/webrtc/modules/audio_processing/aec_dump",
+    "//third_party/webrtc/modules/video_coding:webrtc_h264",
     "//third_party/webrtc/p2p:libstunprober",
     "//third_party/webrtc/p2p:rtc_p2p",
     "//third_party/webrtc/pc:libjingle_peerconnection",
@@ -479,6 +497,7 @@
     "//third_party/webrtc/stats",
     "//third_party/webrtc/system_wrappers",
     "//third_party/webrtc_overrides:init_webrtc",
+    "//third_party/webrtc_overrides:task_queue_factory",
     "//third_party/widevine/cdm:headers",
     "//ui/accessibility",
     "//ui/base",
diff --git a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc
index 6d0569f..6eb6571 100644
--- a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc
+++ b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.cc
@@ -17,12 +17,12 @@
 #include "base/synchronization/lock.h"
 #include "base/timer/timer.h"
 #include "content/public/common/content_features.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "media/base/limits.h"
 #include "third_party/blink/public/platform/modules/peerconnection/webrtc_video_track_source.h"
 #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util.h"
 #include "third_party/blink/public/web/modules/mediastream/media_stream_video_track.h"
 #include "third_party/blink/public/web/modules/mediastream/web_media_stream_utils.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
 #include "third_party/webrtc/api/video_track_source_proxy.h"
 
 namespace content {
@@ -210,7 +210,7 @@
 
 MediaStreamVideoWebRtcSink::MediaStreamVideoWebRtcSink(
     const blink::WebMediaStreamTrack& track,
-    blink::PeerConnectionDependencyFactory* factory,
+    PeerConnectionDependencyFactory* factory,
     scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
   blink::MediaStreamVideoTrack* video_track =
       blink::MediaStreamVideoTrack::GetVideoTrack(track);
diff --git a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h
index a0f560ad..e253aa0 100644
--- a/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h
+++ b/content/renderer/media/webrtc/media_stream_video_webrtc_sink.h
@@ -19,12 +19,13 @@
 
 namespace blink {
 class MediaStreamVideoTrack;
-class PeerConnectionDependencyFactory;
 class WebRtcVideoTrackSource;
 }
 
 namespace content {
 
+class PeerConnectionDependencyFactory;
+
 // MediaStreamVideoWebRtcSink is an adapter between a
 // blink::MediaStreamVideoTrack object and a webrtc VideoTrack that is
 // currently sent on a PeerConnection.
@@ -39,7 +40,7 @@
  public:
   MediaStreamVideoWebRtcSink(
       const blink::WebMediaStreamTrack& track,
-      blink::PeerConnectionDependencyFactory* factory,
+      PeerConnectionDependencyFactory* factory,
       scoped_refptr<base::SingleThreadTaskRunner> task_runner);
   ~MediaStreamVideoWebRtcSink() override;
 
diff --git a/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc b/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc
index 60269a0c..008c53a8 100644
--- a/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc
+++ b/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.cc
@@ -326,8 +326,7 @@
 };
 
 MockPeerConnectionDependencyFactory::MockPeerConnectionDependencyFactory()
-    : blink::PeerConnectionDependencyFactory(
-          /*create_p2p_socket_dispatcher =*/false),
+    : PeerConnectionDependencyFactory(/*create_p2p_socket_dispatcher =*/false),
       signaling_thread_("MockPCFactory WebRtc Signaling Thread") {
   EnsureWebRtcAudioDeviceImpl();
   CHECK(signaling_thread_.Start());
diff --git a/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h b/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h
index dfc03efd..61e25246 100644
--- a/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h
+++ b/content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h
@@ -12,7 +12,7 @@
 #include "base/compiler_specific.h"
 #include "base/macros.h"
 #include "base/single_thread_task_runner.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "third_party/webrtc/api/media_stream_interface.h"
 
 namespace content {
@@ -130,7 +130,7 @@
 // A mock factory for creating different objects for
 // RTC PeerConnections.
 class MockPeerConnectionDependencyFactory
-    : public blink::PeerConnectionDependencyFactory {
+     : public PeerConnectionDependencyFactory {
  public:
   MockPeerConnectionDependencyFactory();
   ~MockPeerConnectionDependencyFactory() override;
diff --git a/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc b/content/renderer/media/webrtc/peer_connection_dependency_factory.cc
similarity index 93%
rename from third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc
rename to content/renderer/media/webrtc/peer_connection_dependency_factory.cc
index 2f2b590..124f3579 100644
--- a/third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc
+++ b/content/renderer/media/webrtc/peer_connection_dependency_factory.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 
 #include <stddef.h>
 
@@ -15,8 +15,15 @@
 #include "base/location.h"
 #include "base/logging.h"
 #include "base/macros.h"
+#include "base/strings/string_util.h"
+#include "base/strings/utf_string_conversions.h"
 #include "base/synchronization/waitable_event.h"
+#include "base/threading/thread_task_runner_handle.h"
 #include "build/build_config.h"
+#include "content/renderer/p2p/ipc_socket_factory.h"
+#include "content/renderer/p2p/mdns_responder_adapter.h"
+#include "content/renderer/p2p/port_allocator.h"
+#include "content/renderer/p2p/socket_dispatcher.h"
 #include "crypto/openssl_util.h"
 #include "jingle/glue/thread_wrapper.h"
 #include "media/base/media_permission.h"
@@ -24,7 +31,11 @@
 #include "media/video/gpu_video_accelerator_factories.h"
 #include "third_party/blink/public/common/features.h"
 #include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h"
+#include "third_party/blink/public/platform/modules/p2p/empty_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/filtering_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/ipc_network_manager.h"
 #include "third_party/blink/public/platform/modules/peerconnection/audio_codec_factory.h"
+#include "third_party/blink/public/platform/modules/peerconnection/video_codec_factory.h"
 #include "third_party/blink/public/platform/modules/webrtc/webrtc_logging.h"
 #include "third_party/blink/public/platform/platform.h"
 #include "third_party/blink/public/platform/web_media_constraints.h"
@@ -38,15 +49,6 @@
 #include "third_party/blink/public/web/modules/webrtc/webrtc_audio_device_impl.h"
 #include "third_party/blink/public/web/web_document.h"
 #include "third_party/blink/public/web/web_local_frame.h"
-#include "third_party/blink/renderer/platform/p2p/empty_network_manager.h"
-#include "third_party/blink/renderer/platform/p2p/filtering_network_manager.h"
-#include "third_party/blink/renderer/platform/p2p/ipc_network_manager.h"
-#include "third_party/blink/renderer/platform/p2p/ipc_socket_factory.h"
-#include "third_party/blink/renderer/platform/p2p/mdns_responder_adapter.h"
-#include "third_party/blink/renderer/platform/p2p/port_allocator.h"
-#include "third_party/blink/renderer/platform/p2p/socket_dispatcher.h"
-#include "third_party/blink/renderer/platform/peerconnection/stun_field_trial.h"
-#include "third_party/blink/renderer/platform/peerconnection/video_codec_factory.h"
 #include "third_party/webrtc/api/call/call_factory_interface.h"
 #include "third_party/webrtc/api/peer_connection_interface.h"
 #include "third_party/webrtc/api/rtc_event_log/rtc_event_log_factory.h"
@@ -60,7 +62,7 @@
 #include "third_party/webrtc/rtc_base/ssl_adapter.h"
 #include "third_party/webrtc_overrides/task_queue_factory.h"
 
-namespace blink {
+namespace content {
 
 namespace {
 
@@ -126,13 +128,6 @@
   DCHECK(!pc_factory_);
 }
 
-PeerConnectionDependencyFactory*
-PeerConnectionDependencyFactory::GetInstance() {
-  DEFINE_STATIC_LOCAL(PeerConnectionDependencyFactory, instance,
-                      (/*create_p2p_socket_dispatcher= */ true));
-  return &instance;
-}
-
 std::unique_ptr<blink::WebRTCPeerConnectionHandler>
 PeerConnectionDependencyFactory::CreateRTCPeerConnectionHandler(
     blink::WebRTCPeerConnectionHandlerClient* client,
@@ -339,7 +334,7 @@
 }
 
 bool PeerConnectionDependencyFactory::PeerConnectionFactoryCreated() {
-  return !!pc_factory_;
+  return pc_factory_.get() != nullptr;
 }
 
 scoped_refptr<webrtc::PeerConnectionInterface>
@@ -436,14 +431,8 @@
     }
   }
 
-  // Now that this file is within Blink, it can not rely on WebURL's
-  // GURL() operator directly. Hence, as per the comment on gurl.h, the
-  // following GURL ctor is used instead.
-  WebURL document_url = web_frame->GetDocument().Url();
   const GURL& requesting_origin =
-      GURL(document_url.GetString().Utf8(), document_url.GetParsed(),
-           document_url.IsValid())
-          .GetOrigin();
+      GURL(web_frame->GetDocument().Url()).GetOrigin();
 
   std::unique_ptr<rtc::NetworkManager> network_manager;
   if (port_config.enable_multiple_routes) {
@@ -502,9 +491,10 @@
 }
 
 webrtc::IceCandidateInterface*
-PeerConnectionDependencyFactory::CreateIceCandidate(const std::string& sdp_mid,
-                                                    int sdp_mline_index,
-                                                    const std::string& sdp) {
+PeerConnectionDependencyFactory::CreateIceCandidate(
+    const std::string& sdp_mid,
+    int sdp_mline_index,
+    const std::string& sdp) {
   return webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, sdp, nullptr);
 }
 
@@ -644,4 +634,4 @@
   return nullptr;
 }
 
-}  // namespace blink
+}  // namespace content
diff --git a/third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h b/content/renderer/media/webrtc/peer_connection_dependency_factory.h
similarity index 86%
rename from third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h
rename to content/renderer/media/webrtc/peer_connection_dependency_factory.h
index 2e97405..11e112c 100644
--- a/third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h
+++ b/content/renderer/media/webrtc/peer_connection_dependency_factory.h
@@ -2,17 +2,20 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_PEERCONNECTION_PEER_CONNECTION_DEPENDENCY_FACTORY_H_
-#define THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_PEERCONNECTION_PEER_CONNECTION_DEPENDENCY_FACTORY_H_
+#ifndef CONTENT_RENDERER_MEDIA_WEBRTC_PEER_CONNECTION_DEPENDENCY_FACTORY_H_
+#define CONTENT_RENDERER_MEDIA_WEBRTC_PEER_CONNECTION_DEPENDENCY_FACTORY_H_
 
 #include <string>
 
+#include "base/files/file.h"
 #include "base/macros.h"
 #include "base/message_loop/message_loop_current.h"
 #include "base/sequence_checker.h"
 #include "base/single_thread_task_runner.h"
 #include "base/threading/thread.h"
-#include "third_party/blink/public/platform/web_common.h"
+#include "content/common/content_export.h"
+#include "ipc/ipc_platform_file.h"
+#include "third_party/blink/public/platform/modules/peerconnection/stun_field_trial.h"
 #include "third_party/webrtc/api/peer_connection_interface.h"
 #include "third_party/webrtc/p2p/stunprober/stun_prober.h"
 
@@ -33,29 +36,26 @@
 }
 
 namespace blink {
-
 class IpcNetworkManager;
-class IpcPacketSocketFactory;
-class MdnsResponderAdapter;
-class P2PSocketDispatcher;
-class StunProberTrial;
 class WebLocalFrame;
 class WebRTCPeerConnectionHandler;
 class WebRTCPeerConnectionHandlerClient;
 class WebRtcAudioDeviceImpl;
+}
+
+namespace content {
+
+class IpcPacketSocketFactory;
+class MdnsResponderAdapter;
+class P2PSocketDispatcher;
 
 // Object factory for RTC PeerConnections.
-class BLINK_MODULES_EXPORT PeerConnectionDependencyFactory
+class CONTENT_EXPORT PeerConnectionDependencyFactory
     : base::MessageLoopCurrent::DestructionObserver {
  public:
-  // TODO(crbug.com/787254): Make this constructor private, when
-  // MockPeerConnectionDependencyFactory gets moved to blink.
-  // (friend class declaration will be needed).
   PeerConnectionDependencyFactory(bool create_p2p_socket_dispatcher);
   ~PeerConnectionDependencyFactory() override;
 
-  static PeerConnectionDependencyFactory* GetInstance();
-
   // Create a RTCPeerConnectionHandler object that implements the
   // WebKit WebRTCPeerConnectionHandler interface.
   std::unique_ptr<blink::WebRTCPeerConnectionHandler>
@@ -69,8 +69,8 @@
   CreateVideoTrackSourceProxy(webrtc::VideoTrackSourceInterface* source);
 
   // Asks the PeerConnection factory to create a Local MediaStream object.
-  virtual scoped_refptr<webrtc::MediaStreamInterface> CreateLocalMediaStream(
-      const std::string& label);
+  virtual scoped_refptr<webrtc::MediaStreamInterface>
+      CreateLocalMediaStream(const std::string& label);
 
   // Asks the PeerConnection factory to create a Local VideoTrack object.
   virtual scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack(
@@ -125,7 +125,7 @@
 
  protected:
   virtual const scoped_refptr<webrtc::PeerConnectionFactoryInterface>&
-  GetPcFactory();
+      GetPcFactory();
   virtual bool PeerConnectionFactoryCreated();
 
   // Helper method to create a WebRtcAudioDeviceImpl.
@@ -150,7 +150,8 @@
       media::GpuVideoAcceleratorFactories* gpu_factories,
       base::WaitableEvent* event);
 
-  void InitializeWorkerThread(rtc::Thread** thread, base::WaitableEvent* event);
+  void InitializeWorkerThread(rtc::Thread** thread,
+                              base::WaitableEvent* event);
 
   void CreateIpcNetworkManagerOnWorkerThread(
       base::WaitableEvent* event,
@@ -184,6 +185,6 @@
   DISALLOW_COPY_AND_ASSIGN(PeerConnectionDependencyFactory);
 };
 
-}  // namespace blink
+}  // namespace content
 
-#endif  // THIRD_PARTY_BLINK_PUBLIC_WEB_MODULES_PEERCONNECTION_PEER_CONNECTION_DEPENDENCY_FACTORY_H_
+#endif  // CONTENT_RENDERER_MEDIA_WEBRTC_PEER_CONNECTION_DEPENDENCY_FACTORY_H_
diff --git a/content/renderer/media/webrtc/rtc_certificate_generator.cc b/content/renderer/media/webrtc/rtc_certificate_generator.cc
index 27295e85..a57e278 100644
--- a/content/renderer/media/webrtc/rtc_certificate_generator.cc
+++ b/content/renderer/media/webrtc/rtc_certificate_generator.cc
@@ -12,8 +12,9 @@
 #include "base/memory/ref_counted.h"
 #include "base/single_thread_task_runner.h"
 #include "base/threading/thread_task_runner_handle.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
+#include "content/renderer/render_thread_impl.h"
 #include "media/media_buildflags.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
 #include "third_party/webrtc/api/scoped_refptr.h"
 #include "third_party/webrtc/rtc_base/rtc_certificate.h"
 #include "third_party/webrtc/rtc_base/rtc_certificate_generator.h"
@@ -107,8 +108,8 @@
     blink::WebRTCCertificateCallback completion_callback,
     scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
   DCHECK(WebRTCKeyParamsToKeyParams(key_params).IsValid());
-  auto* pc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  PeerConnectionDependencyFactory* pc_dependency_factory =
+      RenderThreadImpl::current()->GetPeerConnectionDependencyFactory();
   pc_dependency_factory->EnsureInitialized();
 
   scoped_refptr<RTCCertificateGeneratorRequest> request =
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
index 7bfb83f..3af1701 100644
--- a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
+++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -29,6 +29,7 @@
 #include "base/unguessable_token.h"
 #include "content/public/common/content_features.h"
 #include "content/public/common/content_switches.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "content/renderer/media/webrtc/peer_connection_tracker.h"
 #include "content/renderer/media/webrtc/webrtc_set_description_observer.h"
 #include "content/renderer/render_thread_impl.h"
@@ -52,7 +53,6 @@
 #include "third_party/blink/public/platform/web_string.h"
 #include "third_party/blink/public/platform/web_url.h"
 #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
 #include "third_party/blink/public/web/modules/webrtc/webrtc_audio_device_impl.h"
 #include "third_party/webrtc/api/rtc_event_log_output.h"
 #include "third_party/webrtc/pc/media_session.h"
@@ -973,7 +973,7 @@
 
 RTCPeerConnectionHandler::RTCPeerConnectionHandler(
     blink::WebRTCPeerConnectionHandlerClient* client,
-    blink::PeerConnectionDependencyFactory* dependency_factory,
+    PeerConnectionDependencyFactory* dependency_factory,
     scoped_refptr<base::SingleThreadTaskRunner> task_runner)
     : initialize_called_(false),
       client_(client),
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.h b/content/renderer/media/webrtc/rtc_peer_connection_handler.h
index 64a7156..e8861b12 100644
--- a/content/renderer/media/webrtc/rtc_peer_connection_handler.h
+++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.h
@@ -34,7 +34,6 @@
 #include "third_party/webrtc/api/stats/rtc_stats_collector_callback.h"
 
 namespace blink {
-class PeerConnectionDependencyFactory;
 class WebLocalFrame;
 class WebRTCAnswerOptions;
 class WebRTCLegacyStats;
@@ -44,6 +43,7 @@
 
 namespace content {
 
+class PeerConnectionDependencyFactory;
 class PeerConnectionTracker;
 class SetLocalDescriptionRequest;
 
@@ -95,7 +95,7 @@
  public:
   RTCPeerConnectionHandler(
       blink::WebRTCPeerConnectionHandlerClient* client,
-      blink::PeerConnectionDependencyFactory* dependency_factory,
+      PeerConnectionDependencyFactory* dependency_factory,
       scoped_refptr<base::SingleThreadTaskRunner> task_runner);
   ~RTCPeerConnectionHandler() override;
 
@@ -352,7 +352,7 @@
 
   // |dependency_factory_| is a raw pointer, and is valid for the lifetime of
   // RenderThreadImpl.
-  blink::PeerConnectionDependencyFactory* const dependency_factory_;
+  PeerConnectionDependencyFactory* const dependency_factory_;
 
   blink::WebLocalFrame* frame_ = nullptr;
 
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc
index 58ccdff..786fd539 100644
--- a/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc
+++ b/content/renderer/media/webrtc/rtc_peer_connection_handler_unittest.cc
@@ -83,12 +83,20 @@
 }
 
 // Test blink::Platform implementation that overrides the known methods needed
-// by the tests, including creation of AudioCapturerSource instances.
+// by the tests, including creation of WebRtcAudioDevice and
+// AudioCapturerSource instances.
 //
 // TODO(crbug.com/704136): When this test moves to blink/renderer/ it should
 // inherit from TestingPlatformSupport and use ScopedTestingPlatformSupport.
-class AudioCapturerSourceTestingPlatformSupport : public blink::Platform {
+class WebRtcAudioDeviceTestingPlatformSupport : public blink::Platform {
  public:
+  WebRtcAudioDeviceTestingPlatformSupport(
+      MockPeerConnectionDependencyFactory* pc_factory)
+      : pc_factory_(pc_factory) {}
+  blink::WebRtcAudioDeviceImpl* GetWebRtcAudioDevice() override {
+    return pc_factory_->GetWebRtcAudioDevice();
+  }
+
   scoped_refptr<base::SingleThreadTaskRunner> GetIOTaskRunner() const override {
     return ChildProcess::current() ? ChildProcess::current()->io_task_runner()
                                    : nullptr;
@@ -101,6 +109,9 @@
     EXPECT_EQ(nullptr, web_frame);
     return AudioDeviceFactory::NewAudioCapturerSource(MSG_ROUTING_NONE, params);
   }
+
+ private:
+  MockPeerConnectionDependencyFactory* pc_factory_;
 };
 
 class MockRTCStatsResponse : public LocalRTCStatsResponse {
@@ -268,7 +279,7 @@
  public:
   RTCPeerConnectionHandlerUnderTest(
       WebRTCPeerConnectionHandlerClient* client,
-      blink::PeerConnectionDependencyFactory* dependency_factory)
+      PeerConnectionDependencyFactory* dependency_factory)
       : RTCPeerConnectionHandler(
             client,
             dependency_factory,
@@ -293,8 +304,9 @@
     mock_dependency_factory_.reset(new MockPeerConnectionDependencyFactory());
 
     platform_original_ = blink::Platform::Current();
-    webrtc_audio_device_platform_support_ =
-        std::make_unique<AudioCapturerSourceTestingPlatformSupport>();
+    webrtc_audio_device_platform_support_.reset(
+        new WebRtcAudioDeviceTestingPlatformSupport(
+            mock_dependency_factory_.get()));
     blink::Platform::SetCurrentPlatformForTesting(
         webrtc_audio_device_platform_support_.get());
 
@@ -584,7 +596,7 @@
   // ThreadPool.
   base::test::TaskEnvironment task_environment_;
   ChildProcess child_process_;
-  std::unique_ptr<AudioCapturerSourceTestingPlatformSupport>
+  std::unique_ptr<WebRtcAudioDeviceTestingPlatformSupport>
       webrtc_audio_device_platform_support_;
   blink::Platform* platform_original_ = nullptr;
   std::unique_ptr<MockWebRTCPeerConnectionHandlerClient> mock_client_;
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc
index 48ee044..70c2325e 100644
--- a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc
+++ b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.cc
@@ -6,16 +6,16 @@
 
 #include "base/bind.h"
 #include "content/renderer/media/webrtc/media_stream_video_webrtc_sink.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "third_party/blink/public/platform/modules/mediastream/media_stream_audio_track.h"
 #include "third_party/blink/public/web/modules/mediastream/processed_local_audio_source.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
 
 namespace content {
 
 // static
 scoped_refptr<WebRtcMediaStreamTrackAdapter>
 WebRtcMediaStreamTrackAdapter::CreateLocalTrackAdapter(
-    blink::PeerConnectionDependencyFactory* factory,
+    PeerConnectionDependencyFactory* factory,
     const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
     const blink::WebMediaStreamTrack& web_track) {
   DCHECK(factory);
@@ -36,7 +36,7 @@
 // static
 scoped_refptr<WebRtcMediaStreamTrackAdapter>
 WebRtcMediaStreamTrackAdapter::CreateRemoteTrackAdapter(
-    blink::PeerConnectionDependencyFactory* factory,
+    PeerConnectionDependencyFactory* factory,
     const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
     const scoped_refptr<webrtc::MediaStreamTrackInterface>& webrtc_track) {
   DCHECK(factory);
@@ -57,7 +57,7 @@
 }
 
 WebRtcMediaStreamTrackAdapter::WebRtcMediaStreamTrackAdapter(
-    blink::PeerConnectionDependencyFactory* factory,
+    PeerConnectionDependencyFactory* factory,
     const scoped_refptr<base::SingleThreadTaskRunner>& main_thread)
     : factory_(factory),
       main_thread_(main_thread),
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h
index badb679..d14c01c 100644
--- a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h
+++ b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter.h
@@ -18,12 +18,9 @@
 #include "third_party/blink/public/web/modules/mediastream/remote_media_stream_track_adapter.h"
 #include "third_party/webrtc/api/media_stream_interface.h"
 
-namespace blink {
-class PeerConnectionDependencyFactory;
-}
-
 namespace content {
 
+class PeerConnectionDependencyFactory;
 struct WebRtcMediaStreamTrackAdapterTraits;
 
 // This is a mapping between a webrtc and blink media stream track. It takes
@@ -39,7 +36,7 @@
   // Invoke on the main thread. The returned adapter is fully initialized, see
   // |is_initialized|. The adapter will keep a reference to the |main_thread|.
   static scoped_refptr<WebRtcMediaStreamTrackAdapter> CreateLocalTrackAdapter(
-      blink::PeerConnectionDependencyFactory* factory,
+      PeerConnectionDependencyFactory* factory,
       const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
       const blink::WebMediaStreamTrack& web_track);
   // Invoke on the webrtc signaling thread. Initialization finishes on the main
@@ -47,7 +44,7 @@
   // in posts to the main thread, see |is_initialized|. The adapter will keep
   // references to the |main_thread| and |webrtc_track|.
   static scoped_refptr<WebRtcMediaStreamTrackAdapter> CreateRemoteTrackAdapter(
-      blink::PeerConnectionDependencyFactory* factory,
+      PeerConnectionDependencyFactory* factory,
       const scoped_refptr<base::SingleThreadTaskRunner>& main_thread,
       const scoped_refptr<webrtc::MediaStreamTrackInterface>& webrtc_track);
   // Must be called before all external references are released (i.e. before
@@ -86,7 +83,7 @@
   friend struct WebRtcMediaStreamTrackAdapterTraits;
 
   WebRtcMediaStreamTrackAdapter(
-      blink::PeerConnectionDependencyFactory* factory,
+      PeerConnectionDependencyFactory* factory,
       const scoped_refptr<base::SingleThreadTaskRunner>& main_thread);
   virtual ~WebRtcMediaStreamTrackAdapter();
 
@@ -115,7 +112,7 @@
 
   // Pointer to a |PeerConnectionDependencyFactory| owned by the |RenderThread|.
   // It's valid for the lifetime of |RenderThread|.
-  blink::PeerConnectionDependencyFactory* const factory_;
+  PeerConnectionDependencyFactory* const factory_;
   scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
 
   // Part of the initialization of remote tracks occurs on the signaling thread.
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.cc b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.cc
index 53941f18..db6b0c604 100644
--- a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.cc
+++ b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.cc
@@ -7,7 +7,7 @@
 #include <utility>
 
 #include "base/bind.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 
 namespace content {
 
@@ -72,7 +72,7 @@
 }
 
 WebRtcMediaStreamTrackAdapterMap::WebRtcMediaStreamTrackAdapterMap(
-    blink::PeerConnectionDependencyFactory* const factory,
+    PeerConnectionDependencyFactory* const factory,
     scoped_refptr<base::SingleThreadTaskRunner> main_thread)
     : factory_(factory), main_thread_(std::move(main_thread)) {
   DCHECK(factory_);
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h
index 2c25e103..024e8fc 100644
--- a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h
+++ b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h
@@ -16,12 +16,10 @@
 #include "third_party/blink/public/platform/web_media_stream_track.h"
 #include "third_party/webrtc/api/media_stream_interface.h"
 
-namespace blink {
-class PeerConnectionDependencyFactory;
-}
-
 namespace content {
 
+class PeerConnectionDependencyFactory;
+
 // A map and owner of |WebRtcMediaStreamTrackAdapter|s. It takes care of
 // creating, initializing and disposing track adapters independently of media
 // streams. Adapters are accessed via |AdapterRef|s, when all references to an
@@ -74,7 +72,7 @@
 
   // Must be invoked on the main thread.
   WebRtcMediaStreamTrackAdapterMap(
-      blink::PeerConnectionDependencyFactory* const factory,
+      PeerConnectionDependencyFactory* const factory,
       scoped_refptr<base::SingleThreadTaskRunner> main_thread);
 
   // Gets a new reference to the local track adapter, or null if no such adapter
@@ -142,7 +140,7 @@
 
   // Pointer to a |PeerConnectionDependencyFactory| owned by the |RenderThread|.
   // It's valid for the lifetime of |RenderThread|.
-  blink::PeerConnectionDependencyFactory* const factory_;
+  PeerConnectionDependencyFactory* const factory_;
   scoped_refptr<base::SingleThreadTaskRunner> main_thread_;
 
   mutable base::Lock lock_;
diff --git a/content/renderer/p2p/OWNERS b/content/renderer/p2p/OWNERS
new file mode 100644
index 0000000..70573c4
--- /dev/null
+++ b/content/renderer/p2p/OWNERS
@@ -0,0 +1,4 @@
+sergeyu@chromium.org
+juberti@chromium.org
+
+# COMPONENT: Blink>WebRTC
diff --git a/third_party/blink/renderer/platform/p2p/host_address_request.cc b/content/renderer/p2p/host_address_request.cc
similarity index 79%
rename from third_party/blink/renderer/platform/p2p/host_address_request.cc
rename to content/renderer/p2p/host_address_request.cc
index c2ecba2..64581e0 100644
--- a/third_party/blink/renderer/platform/p2p/host_address_request.cc
+++ b/content/renderer/p2p/host_address_request.cc
@@ -2,19 +2,18 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/host_address_request.h"
+#include "content/renderer/p2p/host_address_request.h"
 
 #include <utility>
 
 #include "base/bind.h"
 #include "base/feature_list.h"
 #include "base/location.h"
+#include "content/renderer/p2p/socket_dispatcher.h"
 #include "jingle/glue/utils.h"
 #include "third_party/blink/public/common/features.h"
-#include "third_party/blink/renderer/platform/p2p/socket_dispatcher.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
 
-namespace blink {
+namespace content {
 
 P2PAsyncAddressResolver::P2PAsyncAddressResolver(
     P2PSocketDispatcher* dispatcher)
@@ -36,7 +35,7 @@
   bool enable_mdns = base::FeatureList::IsEnabled(
       blink::features::kWebRtcHideLocalIpsWithMdns);
   dispatcher_->GetP2PSocketManager()->get()->GetHostAddress(
-      String(host_name.hostname().data()), enable_mdns,
+      host_name.hostname(), enable_mdns,
       base::BindOnce(&P2PAsyncAddressResolver::OnResponse,
                      base::Unretained(this)));
 }
@@ -50,8 +49,7 @@
   done_callback_.Reset();
 }
 
-void P2PAsyncAddressResolver::OnResponse(
-    const Vector<net::IPAddress>& addresses) {
+void P2PAsyncAddressResolver::OnResponse(const net::IPAddressList& addresses) {
   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
   if (state_ == STATE_SENT) {
     state_ = STATE_FINISHED;
@@ -59,4 +57,4 @@
   }
 }
 
-}  // namespace blink
+}  // namespace content
diff --git a/third_party/blink/renderer/platform/p2p/host_address_request.h b/content/renderer/p2p/host_address_request.h
similarity index 75%
rename from third_party/blink/renderer/platform/p2p/host_address_request.h
rename to content/renderer/p2p/host_address_request.h
index 9bb5ccf..f130dce6 100644
--- a/third_party/blink/renderer/platform/p2p/host_address_request.h
+++ b/content/renderer/p2p/host_address_request.h
@@ -2,20 +2,22 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_HOST_ADDRESS_REQUEST_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_HOST_ADDRESS_REQUEST_H_
+#ifndef CONTENT_RENDERER_P2P_HOST_ADDRESS_REQUEST_H_
+#define CONTENT_RENDERER_P2P_HOST_ADDRESS_REQUEST_H_
 
 #include <stdint.h>
 
+#include <string>
+
 #include "base/callback.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
 #include "base/threading/thread_checker.h"
+#include "content/common/content_export.h"
 #include "net/base/ip_address.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
 #include "third_party/webrtc/rtc_base/async_resolver_interface.h"
 
-namespace blink {
+namespace content {
 
 class P2PSocketDispatcher;
 
@@ -24,7 +26,7 @@
 class P2PAsyncAddressResolver
     : public base::RefCountedThreadSafe<P2PAsyncAddressResolver> {
  public:
-  using DoneCallback = base::OnceCallback<void(const Vector<net::IPAddress>&)>;
+  using DoneCallback = base::OnceCallback<void(const net::IPAddressList&)>;
 
   P2PAsyncAddressResolver(P2PSocketDispatcher* dispatcher);
   // Start address resolve process.
@@ -45,7 +47,7 @@
 
   virtual ~P2PAsyncAddressResolver();
 
-  void OnResponse(const Vector<net::IPAddress>& address);
+  void OnResponse(const net::IPAddressList& address);
 
   P2PSocketDispatcher* dispatcher_;
   THREAD_CHECKER(thread_checker_);
@@ -57,6 +59,6 @@
   DISALLOW_COPY_AND_ASSIGN(P2PAsyncAddressResolver);
 };
 
-}  // namespace blink
+}  // namespace content
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_HOST_ADDRESS_REQUEST_H_
+#endif  // CONTENT_RENDERER_P2P_HOST_ADDRESS_REQUEST_H_
diff --git a/third_party/blink/renderer/platform/p2p/ipc_socket_factory.cc b/content/renderer/p2p/ipc_socket_factory.cc
similarity index 93%
rename from third_party/blink/renderer/platform/p2p/ipc_socket_factory.cc
rename to content/renderer/p2p/ipc_socket_factory.cc
index a28777e..57342f1 100644
--- a/third_party/blink/renderer/platform/p2p/ipc_socket_factory.cc
+++ b/content/renderer/p2p/ipc_socket_factory.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/ipc_socket_factory.h"
+#include "content/renderer/p2p/ipc_socket_factory.h"
 
 #include <stddef.h>
 
@@ -18,17 +18,16 @@
 #include "base/strings/stringprintf.h"
 #include "base/threading/thread_checker.h"
 #include "base/trace_event/trace_event.h"
+#include "content/renderer/p2p/host_address_request.h"
+#include "content/renderer/p2p/socket_client_impl.h"
+#include "content/renderer/p2p/socket_dispatcher.h"
 #include "jingle/glue/utils.h"
 #include "net/base/ip_address.h"
+#include "third_party/blink/public/platform/modules/p2p/socket_client_delegate.h"
 #include "third_party/blink/public/platform/modules/webrtc/webrtc_logging.h"
-#include "third_party/blink/renderer/platform/p2p/host_address_request.h"
-#include "third_party/blink/renderer/platform/p2p/socket_client_delegate.h"
-#include "third_party/blink/renderer/platform/p2p/socket_client_impl.h"
-#include "third_party/blink/renderer/platform/p2p/socket_dispatcher.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
 #include "third_party/webrtc/rtc_base/async_packet_socket.h"
 
-namespace blink {
+namespace content {
 
 namespace {
 
@@ -126,7 +125,7 @@
       const network::P2PSendPacketMetrics& send_metrics) override;
   void OnError() override;
   void OnDataReceived(const net::IPEndPoint& address,
-                      const Vector<int8_t>& data,
+                      const std::vector<int8_t>& data,
                       const base::TimeTicks& timestamp) override;
 
  private:
@@ -222,7 +221,7 @@
   void Destroy(bool wait) override;
 
  private:
-  virtual void OnAddressResolved(const Vector<net::IPAddress>& addresses);
+  virtual void OnAddressResolved(const net::IPAddressList& addresses);
 
   scoped_refptr<P2PAsyncAddressResolver> resolver_;
 
@@ -248,7 +247,8 @@
 }
 
 IpcPacketSocket::~IpcPacketSocket() {
-  if (state_ == IS_OPENING || state_ == IS_OPEN || state_ == IS_ERROR) {
+  if (state_ == IS_OPENING || state_ == IS_OPEN ||
+      state_ == IS_ERROR) {
     Close();
   }
 
@@ -293,7 +293,8 @@
   state_ = IS_OPENING;
 
   net::IPEndPoint local_endpoint;
-  if (!jingle_glue::SocketAddressToIPEndPoint(local_address, &local_endpoint)) {
+  if (!jingle_glue::SocketAddressToIPEndPoint(
+          local_address, &local_endpoint)) {
     return false;
   }
 
@@ -349,15 +350,13 @@
   return remote_address_;
 }
 
-int IpcPacketSocket::Send(const void* data,
-                          size_t data_size,
+int IpcPacketSocket::Send(const void *data, size_t data_size,
                           const rtc::PacketOptions& options) {
   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
   return SendTo(data, data_size, remote_address_, options);
 }
 
-int IpcPacketSocket::SendTo(const void* data,
-                            size_t data_size,
+int IpcPacketSocket::SendTo(const void *data, size_t data_size,
                             const rtc::SocketAddress& address,
                             const rtc::PacketOptions& options) {
   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
@@ -389,7 +388,8 @@
 
   if (data_size > send_bytes_available_) {
     TRACE_EVENT_INSTANT1("p2p", "MaxPendingBytesWouldBlock",
-                         TRACE_EVENT_SCOPE_THREAD, "id",
+                         TRACE_EVENT_SCOPE_THREAD,
+                         "id",
                          client_->GetSocketID());
     if (!writable_signal_expected_) {
       blink::WebRtcLogMessage(base::StringPrintf(
@@ -424,8 +424,7 @@
   send_bytes_available_ -= data_size;
 
   const int8_t* data_char = reinterpret_cast<const int8_t*>(data);
-  Vector<int8_t> data_vector;
-  data_vector.AppendRange(data_char, data_char + data_size);
+  std::vector<int8_t> data_vector(data_char, data_char + data_size);
   uint64_t packet_id = client_->Send(address_chrome, data_vector, options);
 
   // Ensure packet_id is not 0. It can't be the case according to
@@ -553,8 +552,8 @@
       // |remote_address| could be unresolved if the connection is behind a
       // proxy.
       if (!remote_address.address().empty() &&
-          jingle_glue::IPEndPointToSocketAddress(remote_address,
-                                                 &jingle_socket_address)) {
+          jingle_glue::IPEndPointToSocketAddress(
+              remote_address, &jingle_socket_address)) {
         // Set only the IP address.
         remote_address_.SetResolvedIP(jingle_socket_address.ipaddr());
       }
@@ -626,7 +625,7 @@
 }
 
 void IpcPacketSocket::OnDataReceived(const net::IPEndPoint& address,
-                                     const Vector<int8_t>& data,
+                                     const std::vector<int8_t>& data,
                                      const base::TimeTicks& timestamp) {
   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
 
@@ -651,7 +650,8 @@
 
 AsyncAddressResolverImpl::AsyncAddressResolverImpl(
     P2PSocketDispatcher* dispatcher)
-    : resolver_(new P2PAsyncAddressResolver(dispatcher)) {}
+    : resolver_(new P2PAsyncAddressResolver(dispatcher)) {
+}
 
 AsyncAddressResolverImpl::~AsyncAddressResolverImpl() {
   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
@@ -669,12 +669,11 @@
 }
 
 bool AsyncAddressResolverImpl::GetResolvedAddress(
-    int family,
-    rtc::SocketAddress* addr) const {
+    int family, rtc::SocketAddress* addr) const {
   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 
   if (addresses_.empty())
-    return false;
+   return false;
 
   for (size_t i = 0; i < addresses_.size(); ++i) {
     if (family == addresses_[i].family()) {
@@ -700,7 +699,7 @@
 }
 
 void AsyncAddressResolverImpl::OnAddressResolved(
-    const Vector<net::IPAddress>& addresses) {
+    const net::IPAddressList& addresses) {
   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
   for (size_t i = 0; i < addresses.size(); ++i) {
     rtc::SocketAddress socket_address;
@@ -721,7 +720,8 @@
     : socket_dispatcher_(socket_dispatcher),
       traffic_annotation_(traffic_annotation) {}
 
-IpcPacketSocketFactory::~IpcPacketSocketFactory() {}
+IpcPacketSocketFactory::~IpcPacketSocketFactory() {
+}
 
 rtc::AsyncPacketSocket* IpcPacketSocketFactory::CreateUdpSocket(
     const rtc::SocketAddress& local_address,
@@ -788,10 +788,11 @@
   return socket.release();
 }
 
-rtc::AsyncResolverInterface* IpcPacketSocketFactory::CreateAsyncResolver() {
+rtc::AsyncResolverInterface*
+IpcPacketSocketFactory::CreateAsyncResolver() {
   std::unique_ptr<AsyncAddressResolverImpl> resolver(
       new AsyncAddressResolverImpl(socket_dispatcher_));
   return resolver.release();
 }
 
-}  // namespace blink
+}  // namespace content
diff --git a/third_party/blink/renderer/platform/p2p/ipc_socket_factory.h b/content/renderer/p2p/ipc_socket_factory.h
similarity index 82%
rename from third_party/blink/renderer/platform/p2p/ipc_socket_factory.h
rename to content/renderer/p2p/ipc_socket_factory.h
index 21a0a25..10237540 100644
--- a/third_party/blink/renderer/platform/p2p/ipc_socket_factory.h
+++ b/content/renderer/p2p/ipc_socket_factory.h
@@ -2,18 +2,18 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_IPC_SOCKET_FACTORY_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_IPC_SOCKET_FACTORY_H_
+#ifndef CONTENT_RENDERER_P2P_IPC_SOCKET_FACTORY_H_
+#define CONTENT_RENDERER_P2P_IPC_SOCKET_FACTORY_H_
 
 #include <stdint.h>
 
 #include "base/compiler_specific.h"
 #include "base/macros.h"
+#include "content/common/content_export.h"
 #include "net/traffic_annotation/network_traffic_annotation.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
 #include "third_party/webrtc/api/packet_socket_factory.h"
 
-namespace blink {
+namespace content {
 
 class P2PSocketDispatcher;
 
@@ -25,7 +25,7 @@
 // created on.
 class IpcPacketSocketFactory : public rtc::PacketSocketFactory {
  public:
-  PLATFORM_EXPORT explicit IpcPacketSocketFactory(
+  CONTENT_EXPORT explicit IpcPacketSocketFactory(
       P2PSocketDispatcher* socket_dispatcher,
       const net::NetworkTrafficAnnotationTag& traffic_annotation);
   ~IpcPacketSocketFactory() override;
@@ -54,6 +54,6 @@
   DISALLOW_COPY_AND_ASSIGN(IpcPacketSocketFactory);
 };
 
-}  // namespace blink
+}  // namespace content
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_IPC_SOCKET_FACTORY_H_
+#endif  // CONTENT_RENDERER_P2P_IPC_SOCKET_FACTORY_H_
diff --git a/third_party/blink/renderer/platform/p2p/mdns_responder_adapter.cc b/content/renderer/p2p/mdns_responder_adapter.cc
similarity index 83%
rename from third_party/blink/renderer/platform/p2p/mdns_responder_adapter.cc
rename to content/renderer/p2p/mdns_responder_adapter.cc
index 70a2730a..f75ff6c 100644
--- a/third_party/blink/renderer/platform/p2p/mdns_responder_adapter.cc
+++ b/content/renderer/p2p/mdns_responder_adapter.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/mdns_responder_adapter.h"
+#include "content/renderer/p2p/mdns_responder_adapter.h"
 
 #include <string>
 
@@ -12,20 +12,19 @@
 #include "net/base/ip_endpoint.h"
 #include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
 #include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
 #include "third_party/webrtc/rtc_base/ip_address.h"
 
-namespace blink {
+namespace content {
 
 namespace {
 
 void OnNameCreatedForAddress(
     webrtc::MdnsResponderInterface::NameCreatedCallback callback,
     const rtc::IPAddress& addr,
-    const String& name,
+    const std::string& name,
     bool announcement_scheduled) {
   // We currently ignore whether there is an announcement sent for the name.
-  callback(addr, name.Utf8());
+  callback(addr, name);
 }
 
 void OnNameRemovedForAddress(
@@ -39,11 +38,10 @@
 }  // namespace
 
 MdnsResponderAdapter::MdnsResponderAdapter() {
-  network::mojom::blink::MdnsResponderPtr client;
+  network::mojom::MdnsResponderPtr client;
   auto request = mojo::MakeRequest(&client);
   thread_safe_client_ =
-      network::mojom::blink::ThreadSafeMdnsResponderPtr::Create(
-          std::move(client));
+      network::mojom::ThreadSafeMdnsResponderPtr::Create(std::move(client));
   blink::Platform::Current()->GetBrowserInterfaceBrokerProxy()->GetInterface(
       std::move(request));
 }
@@ -64,4 +62,4 @@
       base::BindOnce(&OnNameRemovedForAddress, callback));
 }
 
-}  // namespace blink
+}  // namespace content
diff --git a/third_party/blink/renderer/platform/p2p/mdns_responder_adapter.h b/content/renderer/p2p/mdns_responder_adapter.h
similarity index 66%
rename from third_party/blink/renderer/platform/p2p/mdns_responder_adapter.h
rename to content/renderer/p2p/mdns_responder_adapter.h
index b829832fc..3e532a5 100644
--- a/third_party/blink/renderer/platform/p2p/mdns_responder_adapter.h
+++ b/content/renderer/p2p/mdns_responder_adapter.h
@@ -2,25 +2,23 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_MDNS_RESPONDER_ADAPTER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_MDNS_RESPONDER_ADAPTER_H_
+#ifndef CONTENT_RENDERER_P2P_MDNS_RESPONDER_ADAPTER_H_
+#define CONTENT_RENDERER_P2P_MDNS_RESPONDER_ADAPTER_H_
 
-#include "services/network/public/mojom/mdns_responder.mojom-blink.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
+#include "services/network/public/mojom/mdns_responder.mojom.h"
 #include "third_party/webrtc/rtc_base/mdns_responder_interface.h"
 
 namespace rtc {
 class IPAddress;
 }  // namespace rtc
 
-namespace blink {
+namespace content {
 
 // This class is created on the main thread but is used only on the WebRTC
 // worker threads. The MdnsResponderAdapter implements the WebRTC mDNS responder
 // interface via the MdnsResponder service in Chromium, and is used to register
 // and resolve mDNS hostnames to conceal local IP addresses.
-class PLATFORM_EXPORT MdnsResponderAdapter
-    : public webrtc::MdnsResponderInterface {
+class MdnsResponderAdapter : public webrtc::MdnsResponderInterface {
  public:
   // The adapter should be created on the main thread to have access to the
   // connector to the service manager.
@@ -34,12 +32,11 @@
                             NameRemovedCallback callback) override;
 
  private:
-  scoped_refptr<network::mojom::blink::ThreadSafeMdnsResponderPtr>
-      thread_safe_client_;
+  scoped_refptr<network::mojom::ThreadSafeMdnsResponderPtr> thread_safe_client_;
 
   DISALLOW_COPY_AND_ASSIGN(MdnsResponderAdapter);
 };
 
-}  // namespace blink
+}  // namespace content
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_MDNS_RESPONDER_ADAPTER_H_
+#endif  // CONTENT_RENDERER_P2P_MDNS_RESPONDER_ADAPTER_H_
diff --git a/third_party/blink/renderer/platform/p2p/port_allocator.cc b/content/renderer/p2p/port_allocator.cc
similarity index 80%
rename from third_party/blink/renderer/platform/p2p/port_allocator.cc
rename to content/renderer/p2p/port_allocator.cc
index fe49220..00ee3bed 100644
--- a/third_party/blink/renderer/platform/p2p/port_allocator.cc
+++ b/content/renderer/p2p/port_allocator.cc
@@ -2,18 +2,19 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/port_allocator.h"
+#include "content/renderer/p2p/port_allocator.h"
 
 #include <stdint.h>
 
 #include <memory>
 #include <utility>
 
+#include "base/command_line.h"
 #include "base/logging.h"
-#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/renderer/platform/p2p/socket_dispatcher.h"
+#include "content/public/common/content_switches.h"
+#include "content/renderer/p2p/socket_dispatcher.h"
 
-namespace blink {
+namespace content {
 
 P2PPortAllocator::P2PPortAllocator(
     const scoped_refptr<P2PSocketDispatcher>& socket_dispatcher,
@@ -43,8 +44,9 @@
   }
   set_flags(flags);
   set_allow_tcp_listen(false);
+  const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
   bool enable_webrtc_stun_origin =
-      Platform::Current()->IsWebRtcStunOriginEnabled();
+      cmd_line->HasSwitch(switches::kEnableWebRtcStunOrigin);
   if (enable_webrtc_stun_origin) {
     set_origin(origin_.spec());
   }
@@ -57,4 +59,4 @@
   network_manager_->Initialize();
 }
 
-}  // namespace blink
+}  // namespace content
diff --git a/third_party/blink/renderer/platform/p2p/port_allocator.h b/content/renderer/p2p/port_allocator.h
similarity index 83%
rename from third_party/blink/renderer/platform/p2p/port_allocator.h
rename to content/renderer/p2p/port_allocator.h
index 1703c2303..ba335f72 100644
--- a/third_party/blink/renderer/platform/p2p/port_allocator.h
+++ b/content/renderer/p2p/port_allocator.h
@@ -2,22 +2,21 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_PORT_ALLOCATOR_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_PORT_ALLOCATOR_H_
+#ifndef CONTENT_RENDERER_P2P_PORT_ALLOCATOR_H_
+#define CONTENT_RENDERER_P2P_PORT_ALLOCATOR_H_
 
 #include <memory>
 
 #include "base/macros.h"
 #include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
 #include "third_party/webrtc/p2p/client/basic_port_allocator.h"
 #include "url/gurl.h"
 
-namespace blink {
+namespace content {
 
 class P2PSocketDispatcher;
 
-class PLATFORM_EXPORT P2PPortAllocator : public cricket::BasicPortAllocator {
+class P2PPortAllocator : public cricket::BasicPortAllocator {
  public:
   struct Config {
     // Enable non-proxied UDP-based transport when set to true. When set to
@@ -57,6 +56,6 @@
   DISALLOW_COPY_AND_ASSIGN(P2PPortAllocator);
 };
 
-}  // namespace blink
+}  // namespace content
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_PORT_ALLOCATOR_H_
+#endif  // CONTENT_RENDERER_P2P_PORT_ALLOCATOR_H_
diff --git a/third_party/blink/renderer/platform/p2p/socket_client_impl.cc b/content/renderer/p2p/socket_client_impl.cc
similarity index 87%
rename from third_party/blink/renderer/platform/p2p/socket_client_impl.cc
rename to content/renderer/p2p/socket_client_impl.cc
index 65a8945..1f4c585 100644
--- a/third_party/blink/renderer/platform/p2p/socket_client_impl.cc
+++ b/content/renderer/p2p/socket_client_impl.cc
@@ -2,15 +2,15 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/socket_client_impl.h"
+#include "content/renderer/p2p/socket_client_impl.h"
 
 #include "base/bind.h"
 #include "base/location.h"
 #include "base/time/time.h"
+#include "content/renderer/p2p/socket_dispatcher.h"
 #include "crypto/random.h"
 #include "services/network/public/cpp/p2p_param_traits.h"
-#include "third_party/blink/renderer/platform/p2p/socket_client_delegate.h"
-#include "third_party/blink/renderer/platform/p2p/socket_dispatcher.h"
+#include "third_party/blink/public/platform/modules/p2p/socket_client_delegate.h"
 
 namespace {
 
@@ -23,7 +23,7 @@
 
 }  // namespace
 
-namespace blink {
+namespace content {
 
 P2PSocketClientImpl::P2PSocketClientImpl(
     P2PSocketDispatcher* dispatcher,
@@ -57,7 +57,7 @@
 
   DCHECK_EQ(state_, STATE_UNINITIALIZED);
   state_ = STATE_OPENING;
-  network::mojom::blink::P2PSocketClientPtr socket_client;
+  network::mojom::P2PSocketClientPtr socket_client;
   binding_.Bind(mojo::MakeRequest(&socket_client));
   binding_.set_connection_error_handler(base::BindOnce(
       &P2PSocketClientImpl::OnConnectionError, base::Unretained(this)));
@@ -67,7 +67,7 @@
 }
 
 uint64_t P2PSocketClientImpl::Send(const net::IPEndPoint& address,
-                                   const Vector<int8_t>& data,
+                                   const std::vector<int8_t>& data,
                                    const rtc::PacketOptions& options) {
   uint64_t unique_id = GetUniqueId(random_socket_id_, ++next_packet_id_);
 
@@ -81,7 +81,7 @@
 }
 
 void P2PSocketClientImpl::SendWithPacketId(const net::IPEndPoint& address,
-                                           const Vector<int8_t>& data,
+                                           const std::vector<int8_t>& data,
                                            const rtc::PacketOptions& options,
                                            uint64_t packet_id) {
   TRACE_EVENT_ASYNC_BEGIN0("p2p", "Send", packet_id);
@@ -134,15 +134,15 @@
 
 void P2PSocketClientImpl::IncomingTcpConnection(
     const net::IPEndPoint& socket_address,
-    network::mojom::blink::P2PSocketPtr socket,
-    network::mojom::blink::P2PSocketClientRequest client_request) {
+    network::mojom::P2PSocketPtr socket,
+    network::mojom::P2PSocketClientRequest client_request) {
   DCHECK_EQ(state_, STATE_OPEN);
 
   auto new_client =
       std::make_unique<P2PSocketClientImpl>(dispatcher_, traffic_annotation_);
   new_client->state_ = STATE_OPEN;
 
-  network::mojom::blink::P2PSocketClientPtr socket_client;
+  network::mojom::P2PSocketClientPtr socket_client;
   new_client->socket_ = std::move(socket);
   new_client->binding_.Bind(std::move(client_request));
   new_client->binding_.set_connection_error_handler(base::BindOnce(
@@ -158,7 +158,7 @@
 }
 
 void P2PSocketClientImpl::DataReceived(const net::IPEndPoint& socket_address,
-                                       const Vector<int8_t>& data,
+                                       const std::vector<int8_t>& data,
                                        base::TimeTicks timestamp) {
   DCHECK_EQ(STATE_OPEN, state_);
   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
@@ -172,4 +172,4 @@
     delegate_->OnError();
 }
 
-}  // namespace blink
+}  // namespace content
diff --git a/third_party/blink/renderer/platform/p2p/socket_client_impl.h b/content/renderer/p2p/socket_client_impl.h
similarity index 77%
rename from third_party/blink/renderer/platform/p2p/socket_client_impl.h
rename to content/renderer/p2p/socket_client_impl.h
index 080c3fa5..4bcd5a9 100644
--- a/third_party/blink/renderer/platform/p2p/socket_client_impl.h
+++ b/content/renderer/p2p/socket_client_impl.h
@@ -2,11 +2,13 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_IMPL_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_IMPL_H_
+#ifndef CONTENT_RENDERER_P2P_SOCKET_CLIENT_IMPL_H_
+#define CONTENT_RENDERER_P2P_SOCKET_CLIENT_IMPL_H_
 
 #include <stdint.h>
 
+#include <vector>
+
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
 #include "base/threading/thread_checker.h"
@@ -14,15 +16,14 @@
 #include "net/base/ip_endpoint.h"
 #include "net/traffic_annotation/network_traffic_annotation.h"
 #include "services/network/public/cpp/p2p_socket_type.h"
-#include "services/network/public/mojom/p2p.mojom-blink.h"
-#include "third_party/blink/renderer/platform/p2p/socket_client.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
+#include "services/network/public/mojom/p2p.mojom.h"
+#include "third_party/blink/public/platform/modules/p2p/socket_client.h"
 
 namespace base {
 class TimeTicks;
 }  // namespace base
 
-namespace blink {
+namespace content {
 
 class P2PSocketDispatcher;
 
@@ -30,7 +31,7 @@
 //
 // The object runs on the WebRTC worker thread.
 class P2PSocketClientImpl : public blink::P2PSocketClient,
-                            public network::mojom::blink::P2PSocketClient {
+                            public network::mojom::P2PSocketClient {
  public:
   P2PSocketClientImpl(
       P2PSocketDispatcher* dispatcher,
@@ -50,7 +51,7 @@
   // Send the |data| to the |address| using Differentiated Services Code Point
   // |dscp|. Return value is the unique packet_id for this packet.
   uint64_t Send(const net::IPEndPoint& address,
-                const Vector<int8_t>& data,
+                const std::vector<int8_t>& data,
                 const rtc::PacketOptions& options) override;
 
   // Setting socket options.
@@ -78,20 +79,20 @@
   // Helper function to be called by Send to handle different threading
   // condition.
   void SendWithPacketId(const net::IPEndPoint& address,
-                        const Vector<int8_t>& data,
+                        const std::vector<int8_t>& data,
                         const rtc::PacketOptions& options,
                         uint64_t packet_id);
 
-  // network::mojom::blink::P2PSocketClient interface.
+  // network::mojom::P2PSocketClient interface.
   void SocketCreated(const net::IPEndPoint& local_address,
                      const net::IPEndPoint& remote_address) override;
   void SendComplete(const network::P2PSendPacketMetrics& send_metrics) override;
   void IncomingTcpConnection(
       const net::IPEndPoint& socket_address,
-      network::mojom::blink::P2PSocketPtr socket,
-      network::mojom::blink::P2PSocketClientRequest client_request) override;
+      network::mojom::P2PSocketPtr socket,
+      network::mojom::P2PSocketClientRequest client_request) override;
   void DataReceived(const net::IPEndPoint& socket_address,
-                    const Vector<int8_t>& data,
+                    const std::vector<int8_t>& data,
                     base::TimeTicks timestamp) override;
 
   void OnConnectionError();
@@ -107,12 +108,12 @@
   uint32_t random_socket_id_;
   uint32_t next_packet_id_;
 
-  network::mojom::blink::P2PSocketPtr socket_;
-  mojo::Binding<network::mojom::blink::P2PSocketClient> binding_;
+  network::mojom::P2PSocketPtr socket_;
+  mojo::Binding<network::mojom::P2PSocketClient> binding_;
 
   DISALLOW_COPY_AND_ASSIGN(P2PSocketClientImpl);
 };
 
-}  // namespace blink
+}  // namespace content
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_IMPL_H_
+#endif  // CONTENT_RENDERER_P2P_SOCKET_CLIENT_IMPL_H_
diff --git a/third_party/blink/renderer/platform/p2p/socket_dispatcher.cc b/content/renderer/p2p/socket_dispatcher.cc
similarity index 68%
rename from third_party/blink/renderer/platform/p2p/socket_dispatcher.cc
rename to content/renderer/p2p/socket_dispatcher.cc
index c82473ef..24e91869 100644
--- a/third_party/blink/renderer/platform/p2p/socket_dispatcher.cc
+++ b/content/renderer/p2p/socket_dispatcher.cc
@@ -2,24 +2,25 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/socket_dispatcher.h"
+#include "content/renderer/p2p/socket_dispatcher.h"
 
 #include "base/bind.h"
 #include "base/memory/scoped_refptr.h"
+#include "content/renderer/p2p/socket_client_impl.h"
 #include "services/network/public/cpp/p2p_param_traits.h"
 #include "third_party/blink/public/common/thread_safe_browser_interface_broker_proxy.h"
+#include "third_party/blink/public/platform/modules/p2p/network_list_observer.h"
 #include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/renderer/platform/p2p/network_list_observer.h"
-#include "third_party/blink/renderer/platform/p2p/socket_client_impl.h"
 
-namespace blink {
+namespace content {
 
 P2PSocketDispatcher::P2PSocketDispatcher()
     : main_task_runner_(base::ThreadTaskRunnerHandle::Get()),
       network_list_observers_(
           new base::ObserverListThreadSafe<blink::NetworkListObserver>()) {}
 
-P2PSocketDispatcher::~P2PSocketDispatcher() {}
+P2PSocketDispatcher::~P2PSocketDispatcher() {
+}
 
 void P2PSocketDispatcher::AddNetworkListObserver(
     blink::NetworkListObserver* network_list_observer) {
@@ -35,16 +36,16 @@
   network_list_observers_->RemoveObserver(network_list_observer);
 }
 
-scoped_refptr<network::mojom::blink::ThreadSafeP2PSocketManagerPtr>
+scoped_refptr<network::mojom::ThreadSafeP2PSocketManagerPtr>
 P2PSocketDispatcher::GetP2PSocketManager() {
   base::AutoLock lock(p2p_socket_manager_lock_);
   if (!thread_safe_p2p_socket_manager_) {
-    network::mojom::blink::P2PSocketManagerPtr p2p_socket_manager;
+    network::mojom::P2PSocketManagerPtr p2p_socket_manager;
     p2p_socket_manager_request_ = mojo::MakeRequest(&p2p_socket_manager);
     p2p_socket_manager.set_connection_error_handler(base::BindOnce(
         &P2PSocketDispatcher::OnConnectionError, base::Unretained(this)));
     thread_safe_p2p_socket_manager_ =
-        network::mojom::blink::ThreadSafeP2PSocketManagerPtr::Create(
+        network::mojom::ThreadSafeP2PSocketManagerPtr::Create(
             std::move(p2p_socket_manager));
   }
   main_task_runner_->PostTask(
@@ -54,24 +55,16 @@
 }
 
 void P2PSocketDispatcher::NetworkListChanged(
-    const Vector<net::NetworkInterface>& networks,
+    const std::vector<net::NetworkInterface>& networks,
     const net::IPAddress& default_ipv4_local_address,
     const net::IPAddress& default_ipv6_local_address) {
   DCHECK(main_task_runner_->BelongsToCurrentThread());
   networks_ = networks;
   default_ipv4_local_address_ = default_ipv4_local_address;
   default_ipv6_local_address_ = default_ipv6_local_address;
-
-  // TODO(crbug.com/787254): Remove this helper when network_list_observer.h
-  // gets moved from blink/public to blink/renderer, and operate over
-  // WTF::Vector.
-  std::vector<net::NetworkInterface> copy(networks.size());
-  for (size_t i = 0; i < networks.size(); i++)
-    copy[i] = networks[i];
-
   network_list_observers_->Notify(
-      FROM_HERE, &blink::NetworkListObserver::OnNetworkListChanged,
-      std::move(copy), default_ipv4_local_address, default_ipv6_local_address);
+      FROM_HERE, &blink::NetworkListObserver::OnNetworkListChanged, networks,
+      default_ipv4_local_address, default_ipv6_local_address);
 }
 
 void P2PSocketDispatcher::RequestInterfaceIfNecessary() {
@@ -84,17 +77,9 @@
 
 void P2PSocketDispatcher::RequestNetworkEventsIfNecessary() {
   if (network_notification_client_receiver_.is_bound()) {
-    // TODO(crbug.com/787254): Remove this helper when network_list_observer.h
-    // gets moved from blink/public to blink/renderer, and operate over
-    // WTF::Vector.
-    std::vector<net::NetworkInterface> copy(networks_.size());
-    for (size_t i = 0; i < networks_.size(); i++)
-      copy[i] = networks_[i];
-
     network_list_observers_->Notify(
-        FROM_HERE, &blink::NetworkListObserver::OnNetworkListChanged,
-        std::move(copy), default_ipv4_local_address_,
-        default_ipv6_local_address_);
+        FROM_HERE, &blink::NetworkListObserver::OnNetworkListChanged, networks_,
+        default_ipv4_local_address_, default_ipv6_local_address_);
   } else {
     GetP2PSocketManager()->get()->StartNetworkNotifications(
         network_notification_client_receiver_.BindNewPipeAndPassRemote());
@@ -106,4 +91,4 @@
   thread_safe_p2p_socket_manager_.reset();
 }
 
-}  // namespace blink
+}  // namespace content
diff --git a/third_party/blink/renderer/platform/p2p/socket_dispatcher.h b/content/renderer/p2p/socket_dispatcher.h
similarity index 70%
rename from third_party/blink/renderer/platform/p2p/socket_dispatcher.h
rename to content/renderer/p2p/socket_dispatcher.h
index 5342377..1d05550a 100644
--- a/third_party/blink/renderer/platform/p2p/socket_dispatcher.h
+++ b/content/renderer/p2p/socket_dispatcher.h
@@ -18,26 +18,27 @@
 // P2PSocketDispatcher receives and dispatches messages on the
 // IO thread.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_DISPATCHER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_DISPATCHER_H_
+#ifndef CONTENT_RENDERER_P2P_SOCKET_DISPATCHER_H_
+#define CONTENT_RENDERER_P2P_SOCKET_DISPATCHER_H_
 
 #include <stdint.h>
 
+#include <vector>
+
 #include "base/callback_forward.h"
 #include "base/compiler_specific.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
 #include "base/observer_list_threadsafe.h"
 #include "base/synchronization/lock.h"
+#include "content/common/content_export.h"
 #include "mojo/public/cpp/bindings/receiver.h"
 #include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
 #include "net/base/ip_address.h"
 #include "net/base/network_interfaces.h"
 #include "services/network/public/cpp/p2p_socket_type.h"
-#include "services/network/public/mojom/p2p.mojom-blink.h"
-#include "third_party/blink/renderer/platform/p2p/network_list_manager.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
+#include "services/network/public/mojom/p2p.mojom.h"
+#include "third_party/blink/public/platform/modules/p2p/network_list_manager.h"
 
 namespace base {
 class SingleThreadTaskRunner;
@@ -47,14 +48,14 @@
 class NetworkListObserver;
 }
 
-namespace blink {
+namespace content {
 
 // This class is created on the main thread, but is used primarily on the
 // WebRTC worker threads.
-class PLATFORM_EXPORT P2PSocketDispatcher
+class CONTENT_EXPORT P2PSocketDispatcher
     : public base::RefCountedThreadSafe<P2PSocketDispatcher>,
       public blink::NetworkListManager,
-      public network::mojom::blink::P2PNetworkNotificationClient {
+      public network::mojom::P2PNetworkNotificationClient {
  public:
   P2PSocketDispatcher();
 
@@ -64,7 +65,7 @@
   void RemoveNetworkListObserver(
       blink::NetworkListObserver* network_list_observer) override;
 
-  scoped_refptr<network::mojom::blink::ThreadSafeP2PSocketManagerPtr>
+  scoped_refptr<network::mojom::ThreadSafeP2PSocketManagerPtr>
   GetP2PSocketManager();
 
  private:
@@ -72,9 +73,9 @@
 
   ~P2PSocketDispatcher() override;
 
-  // network::mojom::blink::P2PNetworkNotificationClient interface.
+  // network::mojom::P2PNetworkNotificationClient interface.
   void NetworkListChanged(
-      const Vector<net::NetworkInterface>& networks,
+      const std::vector<net::NetworkInterface>& networks,
       const net::IPAddress& default_ipv4_local_address,
       const net::IPAddress& default_ipv6_local_address) override;
 
@@ -85,27 +86,25 @@
 
   scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
 
-  // TODO(crbug.com/787254): When moving NetworkListObserver to Oilpan,
-  // thread-safety needs to be taken into account.
   scoped_refptr<base::ObserverListThreadSafe<blink::NetworkListObserver>>
       network_list_observers_;
 
-  network::mojom::blink::P2PSocketManagerRequest p2p_socket_manager_request_;
-  scoped_refptr<network::mojom::blink::ThreadSafeP2PSocketManagerPtr>
+  network::mojom::P2PSocketManagerRequest p2p_socket_manager_request_;
+  scoped_refptr<network::mojom::ThreadSafeP2PSocketManagerPtr>
       thread_safe_p2p_socket_manager_;
   base::Lock p2p_socket_manager_lock_;
 
   // Cached from last |NetworkListChanged| call.
-  Vector<net::NetworkInterface> networks_;
+  std::vector<net::NetworkInterface> networks_;
   net::IPAddress default_ipv4_local_address_;
   net::IPAddress default_ipv6_local_address_;
 
-  mojo::Receiver<network::mojom::blink::P2PNetworkNotificationClient>
+  mojo::Receiver<network::mojom::P2PNetworkNotificationClient>
       network_notification_client_receiver_{this};
 
   DISALLOW_COPY_AND_ASSIGN(P2PSocketDispatcher);
 };
 
-}  // namespace blink
+}  // namespace content
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_DISPATCHER_H_
+#endif  // CONTENT_RENDERER_P2P_SOCKET_DISPATCHER_H_
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.cc b/content/renderer/pepper/pepper_plugin_instance_impl.cc
index f45103b..0a6a982 100644
--- a/content/renderer/pepper/pepper_plugin_instance_impl.cc
+++ b/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -293,6 +293,8 @@
                    PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA);
 STATIC_ASSERT_ENUM(blink::kWebPrintScalingOptionSourceSize,
                    PP_PRINTSCALINGOPTION_SOURCE_SIZE);
+STATIC_ASSERT_ENUM(blink::kWebPrintScalingOptionFitToPaper,
+                   PP_PRINTSCALINGOPTION_FIT_TO_PAPER);
 
 #undef STATIC_ASSERT_ENUM
 
@@ -1959,6 +1961,11 @@
     num_pages = plugin_pdf_interface_->PrintBegin(
         pp_instance(), &print_settings, &pdf_print_settings);
   } else {
+    // If the content is not from the PDF plugin, "fit to paper" should have
+    // never been a scaling option for the user to begin with.
+    DCHECK_NE(print_settings.print_scaling_option,
+              PP_PRINTSCALINGOPTION_FIT_TO_PAPER);
+
     num_pages = plugin_print_interface_->Begin(pp_instance(), &print_settings);
   }
   if (!num_pages)
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc
index 815bc3c..6e78950 100644
--- a/content/renderer/render_thread_impl.cc
+++ b/content/renderer/render_thread_impl.cc
@@ -91,7 +91,9 @@
 #include "content/renderer/media/audio/audio_renderer_mixer_manager.h"
 #include "content/renderer/media/gpu/gpu_video_accelerator_factories_impl.h"
 #include "content/renderer/media/render_media_client.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "content/renderer/media/webrtc/peer_connection_tracker.h"
+#include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
 #include "content/renderer/net_info_helper.h"
 #include "content/renderer/render_frame_proxy.h"
 #include "content/renderer/render_process_impl.h"
@@ -744,6 +746,9 @@
       new PeerConnectionTracker(main_thread_runner()));
   AddObserver(peer_connection_tracker_.get());
 
+  peer_connection_factory_.reset(new PeerConnectionDependencyFactory(
+      /*create_p2p_socket_dispatcher =*/true));
+
   unfreezable_message_filter_ = new UnfreezableMessageFilter(this);
   AddFilter(unfreezable_message_filter_.get());
 
@@ -1994,6 +1999,11 @@
   return &associated_interfaces_;
 }
 
+PeerConnectionDependencyFactory*
+RenderThreadImpl::GetPeerConnectionDependencyFactory() {
+  return peer_connection_factory_.get();
+}
+
 mojom::RenderMessageFilter* RenderThreadImpl::render_message_filter() {
   if (!render_message_filter_)
     GetChannel()->GetRemoteAssociatedInterface(&render_message_filter_);
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h
index 8e05e39..1832cee 100644
--- a/content/renderer/render_thread_impl.h
+++ b/content/renderer/render_thread_impl.h
@@ -120,6 +120,7 @@
 class CategorizedWorkerPool;
 class GpuVideoAcceleratorFactoriesImpl;
 class LowMemoryModeController;
+class PeerConnectionDependencyFactory;
 class PeerConnectionTracker;
 class RenderThreadObserver;
 class RendererBlinkPlatformImpl;
@@ -307,6 +308,9 @@
     return browser_plugin_manager_.get();
   }
 
+  // Returns a factory used for creating RTC PeerConnection objects.
+  PeerConnectionDependencyFactory* GetPeerConnectionDependencyFactory();
+
   PeerConnectionTracker* peer_connection_tracker() {
     return peer_connection_tracker_.get();
   }
@@ -573,6 +577,8 @@
 
   std::unique_ptr<BrowserPluginManager> browser_plugin_manager_;
 
+  std::unique_ptr<PeerConnectionDependencyFactory> peer_connection_factory_;
+
   // This is used to communicate to the browser process the status
   // of all the peer connections created in the renderer.
   std::unique_ptr<PeerConnectionTracker> peer_connection_tracker_;
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc
index 4b7df6e3..7a82aca3 100644
--- a/content/renderer/render_view_impl.cc
+++ b/content/renderer/render_view_impl.cc
@@ -74,6 +74,7 @@
 #include "content/renderer/internal_document_state_data.h"
 #include "content/renderer/loader/request_extra_data.h"
 #include "content/renderer/media/audio/audio_device_factory.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
 #include "content/renderer/render_frame_impl.h"
 #include "content/renderer/render_frame_proxy.h"
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc
index 20a7f24..a0740f4 100644
--- a/content/renderer/render_widget.cc
+++ b/content/renderer/render_widget.cc
@@ -33,6 +33,7 @@
 #include "cc/trees/layer_tree_frame_sink.h"
 #include "cc/trees/layer_tree_host.h"
 #include "cc/trees/ukm_manager.h"
+#include "components/viz/common/display/de_jelly.h"
 #include "components/viz/common/features.h"
 #include "components/viz/common/frame_sinks/begin_frame_source.h"
 #include "components/viz/common/frame_sinks/copy_output_request.h"
@@ -3208,6 +3209,15 @@
 
   settings.send_compositor_frame_ack = false;
 
+  // Renderer can de-jelly, browser UI can not. We do not know whether we are
+  // going to apply de-jelly until we draw a frame in the Viz process. Because
+  // of this, all changes in the renderer are based on whether de-jelly may be
+  // active (viz::DeJellyEnabled) vs whether it is currently active
+  // (viz::DeJellyActive).
+  settings.allow_de_jelly_effect = viz::DeJellyEnabled();
+  // Disable occlusion if de-jelly effect is enabled.
+  settings.enable_occlusion &= !settings.allow_de_jelly_effect;
+
   return settings;
 }
 
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc
index 5cbfd85..7f3c8fbb 100644
--- a/content/renderer/renderer_blink_platform_impl.cc
+++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -47,8 +47,10 @@
 #include "content/renderer/media/audio/audio_device_factory.h"
 #include "content/renderer/media/audio_decoder.h"
 #include "content/renderer/media/renderer_webaudiodevice_impl.h"
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "content/renderer/media/webrtc/peer_connection_tracker.h"
 #include "content/renderer/media/webrtc/rtc_peer_connection_handler.h"
+#include "content/renderer/p2p/port_allocator.h"
 #include "content/renderer/render_frame_impl.h"
 #include "content/renderer/render_thread_impl.h"
 #include "content/renderer/storage_util.h"
@@ -94,7 +96,6 @@
 #include "third_party/blink/public/platform/web_url_loader_factory.h"
 #include "third_party/blink/public/platform/web_url_request.h"
 #include "third_party/blink/public/platform/web_vector.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
 #include "third_party/blink/public/web/web_local_frame.h"
 #include "third_party/blink/public/web/web_user_media_request.h"
 #include "third_party/sqlite/sqlite3.h"
@@ -115,6 +116,7 @@
 #include "base/win/windows_version.h"
 #endif
 
+#include "content/renderer/media/webrtc/peer_connection_dependency_factory.h"
 #include "content/renderer/media/webrtc/rtc_certificate_generator.h"
 #include "third_party/blink/public/platform/modules/mediastream/webrtc_uma_histograms.h"
 
@@ -542,13 +544,18 @@
   // PeerConnectionDependencyFactory::CreateRTCPeerConnectionHandler
   // when it the file gets Onion soup'ed.
 
+  RenderThreadImpl* render_thread = RenderThreadImpl::current();
+  DCHECK(render_thread);
+  if (!render_thread)
+    return nullptr;
+
   // Save histogram data so we can see how much PeerConnection is used.
   // The histogram counts the number of calls to the JS API
   // RTCPeerConnection.
   UpdateWebRTCMethodCount(blink::WebRTCAPIName::kRTCPeerConnection);
 
-  auto* rtc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  PeerConnectionDependencyFactory* rtc_dependency_factory =
+      render_thread->GetPeerConnectionDependencyFactory();
   return std::make_unique<RTCPeerConnectionHandler>(
       client, rtc_dependency_factory, task_runner);
 }
@@ -564,23 +571,29 @@
 
 scoped_refptr<base::SingleThreadTaskRunner>
 RendererBlinkPlatformImpl::GetWebRtcWorkerThread() {
-  auto* rtc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  RenderThreadImpl* render_thread = RenderThreadImpl::current();
+  DCHECK(render_thread);
+  PeerConnectionDependencyFactory* rtc_dependency_factory =
+      render_thread->GetPeerConnectionDependencyFactory();
   rtc_dependency_factory->EnsureInitialized();
   return rtc_dependency_factory->GetWebRtcWorkerThread();
 }
 
 rtc::Thread* RendererBlinkPlatformImpl::GetWebRtcWorkerThreadRtcThread() {
-  auto* rtc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  RenderThreadImpl* render_thread = RenderThreadImpl::current();
+  DCHECK(render_thread);
+  PeerConnectionDependencyFactory* rtc_dependency_factory =
+      render_thread->GetPeerConnectionDependencyFactory();
   rtc_dependency_factory->EnsureInitialized();
   return rtc_dependency_factory->GetWebRtcWorkerThreadRtcThread();
 }
 
 scoped_refptr<base::SingleThreadTaskRunner>
 RendererBlinkPlatformImpl::GetWebRtcSignalingTaskRunner() {
-  auto* rtc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  RenderThreadImpl* render_thread = RenderThreadImpl::current();
+  DCHECK(render_thread);
+  PeerConnectionDependencyFactory* rtc_dependency_factory =
+      render_thread->GetPeerConnectionDependencyFactory();
   rtc_dependency_factory->EnsureInitialized();
   return rtc_dependency_factory->GetWebRtcSignalingThread();
 }
@@ -588,16 +601,20 @@
 std::unique_ptr<cricket::PortAllocator>
 RendererBlinkPlatformImpl::CreateWebRtcPortAllocator(
     blink::WebLocalFrame* frame) {
-  auto* rtc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  RenderThreadImpl* render_thread = RenderThreadImpl::current();
+  DCHECK(render_thread);
+  PeerConnectionDependencyFactory* rtc_dependency_factory =
+      render_thread->GetPeerConnectionDependencyFactory();
   rtc_dependency_factory->EnsureInitialized();
   return rtc_dependency_factory->CreatePortAllocator(frame);
 }
 
 std::unique_ptr<webrtc::AsyncResolverFactory>
 RendererBlinkPlatformImpl::CreateWebRtcAsyncResolverFactory() {
-  auto* rtc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  RenderThreadImpl* render_thread = RenderThreadImpl::current();
+  DCHECK(render_thread);
+  PeerConnectionDependencyFactory* rtc_dependency_factory =
+      render_thread->GetPeerConnectionDependencyFactory();
   rtc_dependency_factory->EnsureInitialized();
   return rtc_dependency_factory->CreateAsyncResolverFactory();
 }
@@ -607,8 +624,8 @@
 std::unique_ptr<webrtc::RtpCapabilities>
 RendererBlinkPlatformImpl::GetRtpSenderCapabilities(
     const blink::WebString& kind) {
-  auto* pc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  PeerConnectionDependencyFactory* pc_dependency_factory =
+      RenderThreadImpl::current()->GetPeerConnectionDependencyFactory();
   pc_dependency_factory->EnsureInitialized();
   return pc_dependency_factory->GetSenderCapabilities(kind.Utf8());
 }
@@ -616,8 +633,8 @@
 std::unique_ptr<webrtc::RtpCapabilities>
 RendererBlinkPlatformImpl::GetRtpReceiverCapabilities(
     const blink::WebString& kind) {
-  auto* pc_dependency_factory =
-      blink::PeerConnectionDependencyFactory::GetInstance();
+  PeerConnectionDependencyFactory* pc_dependency_factory =
+      RenderThreadImpl::current()->GetPeerConnectionDependencyFactory();
   pc_dependency_factory->EnsureInitialized();
   return pc_dependency_factory->GetReceiverCapabilities(kind.Utf8());
 }
@@ -652,6 +669,13 @@
   return AudioDeviceFactory::GetSourceLatencyType(source_type);
 }
 
+blink::WebRtcAudioDeviceImpl*
+RendererBlinkPlatformImpl::GetWebRtcAudioDevice() {
+  PeerConnectionDependencyFactory* pc_dependency_factory =
+      RenderThreadImpl::current()->GetPeerConnectionDependencyFactory();
+  return pc_dependency_factory->GetWebRtcAudioDevice();
+}
+
 base::Optional<std::string>
 RendererBlinkPlatformImpl::GetWebRTCAudioProcessingConfiguration() {
   return GetContentClient()
@@ -675,11 +699,6 @@
       switches::kDisableWebRtcEncryption);
 }
 
-bool RendererBlinkPlatformImpl::IsWebRtcStunOriginEnabled() {
-  return base::CommandLine::ForCurrentProcess()->HasSwitch(
-      switches::kEnableWebRtcStunOrigin);
-}
-
 base::Optional<std::string>
 RendererBlinkPlatformImpl::WebRtcStunProbeTrialParameter() {
   const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h
index 16d420e5..b183977 100644
--- a/content/renderer/renderer_blink_platform_impl.h
+++ b/content/renderer/renderer_blink_platform_impl.h
@@ -151,11 +151,11 @@
       const media::AudioSinkParameters& params) override;
   media::AudioLatency::LatencyType GetAudioSourceLatencyType(
       blink::WebAudioDeviceSourceType source_type) override;
+  blink::WebRtcAudioDeviceImpl* GetWebRtcAudioDevice() override;
   base::Optional<std::string> GetWebRTCAudioProcessingConfiguration() override;
   bool ShouldEnforceWebRTCRoutingPreferences() override;
   bool UsesFakeCodecForPeerConnection() override;
   bool IsWebRtcEncryptionEnabled() override;
-  bool IsWebRtcStunOriginEnabled() override;
   base::Optional<std::string> WebRtcStunProbeTrialParameter() override;
   media::MediaPermission* GetWebRTCMediaPermission(
       blink::WebLocalFrame* web_frame) override;
diff --git a/content/renderer/service_worker/embedded_worker_instance_client_impl.cc b/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
index 1e99f6b..15d7a09 100644
--- a/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
+++ b/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
@@ -116,12 +116,12 @@
   }
 
   auto worker = blink::WebEmbeddedWorker::Create(
-      service_worker_context_client_.get(),
-      std::move(installed_scripts_manager_params),
-      params->content_settings_proxy.PassHandle(), cache_storage.PassPipe(),
+      service_worker_context_client_.get(), cache_storage.PassPipe(),
       interface_provider.PassHandle(), browser_interface_broker.PassPipe());
   service_worker_context_client_->StartWorkerContextOnInitiatorThread(
-      std::move(worker), start_data);
+      std::move(worker), start_data,
+      std::move(installed_scripts_manager_params),
+      params->content_settings_proxy.PassHandle());
 }
 
 void EmbeddedWorkerInstanceClientImpl::StopWorker() {
diff --git a/content/renderer/service_worker/service_worker_context_client.cc b/content/renderer/service_worker/service_worker_context_client.cc
index 11b0575..cd93266 100644
--- a/content/renderer/service_worker/service_worker_context_client.cc
+++ b/content/renderer/service_worker/service_worker_context_client.cc
@@ -171,10 +171,15 @@
 
 void ServiceWorkerContextClient::StartWorkerContextOnInitiatorThread(
     std::unique_ptr<blink::WebEmbeddedWorker> worker,
-    const blink::WebEmbeddedWorkerStartData& start_data) {
+    const blink::WebEmbeddedWorkerStartData& start_data,
+    std::unique_ptr<blink::WebServiceWorkerInstalledScriptsManagerParams>
+        installed_scripts_manager_params,
+    mojo::ScopedMessagePipeHandle content_settings_handle) {
   DCHECK(initiator_thread_task_runner_->RunsTasksInCurrentSequence());
   worker_ = std::move(worker);
-  worker_->StartWorkerContext(start_data, initiator_thread_task_runner_);
+  worker_->StartWorkerContext(
+      start_data, std::move(installed_scripts_manager_params),
+      std::move(content_settings_handle), initiator_thread_task_runner_);
 }
 
 blink::WebEmbeddedWorker& ServiceWorkerContextClient::worker() {
diff --git a/content/renderer/service_worker/service_worker_context_client.h b/content/renderer/service_worker/service_worker_context_client.h
index fb78255..645c59f 100644
--- a/content/renderer/service_worker/service_worker_context_client.h
+++ b/content/renderer/service_worker/service_worker_context_client.h
@@ -49,6 +49,7 @@
 namespace blink {
 class WebServiceWorkerContextProxy;
 class WebURLResponse;
+struct WebServiceWorkerInstalledScriptsManagerParams;
 }
 
 namespace content {
@@ -114,7 +115,9 @@
   // Called on the initiator thread.
   void StartWorkerContextOnInitiatorThread(
       std::unique_ptr<blink::WebEmbeddedWorker> worker,
-      const blink::WebEmbeddedWorkerStartData& start_data);
+      const blink::WebEmbeddedWorkerStartData& start_data,
+      std::unique_ptr<blink::WebServiceWorkerInstalledScriptsManagerParams>,
+      mojo::ScopedMessagePipeHandle content_settings_handle);
   // Called on the initiator thread.
   blink::WebEmbeddedWorker& worker();
 
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java
index b141095..20da39a2 100644
--- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java
+++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/ChildProcessLauncherTestHelperService.java
@@ -78,7 +78,8 @@
         String[] commandLine = { "_", "--" + BaseSwitches.RENDERER_WAIT_FOR_JAVA_DEBUGGER };
         final boolean bindToCaller = true;
         ChildProcessCreationParams.set(getPackageName(), false, LibraryProcessType.PROCESS_CHILD,
-                bindToCaller, false /* ignoreVisibilityForImportance */);
+                bindToCaller, false /* ignoreVisibilityForImportance */,
+                null /* privilegedServicesName */, null /* sandboxedServicesName */);
         mProcessLauncher = ChildProcessLauncherTestUtils.startForTesting(true /* sandboxed */,
                 commandLine, new FileDescriptorInfo[0], true /* doSetupConnection */);
 
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java
index 7736c6d..885d3b31 100644
--- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java
+++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService.java
@@ -4,6 +4,7 @@
 
 package org.chromium.content_shell_apk;
 
+import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
@@ -28,7 +29,7 @@
 /**
  * Child service started by ChildProcessLauncherTest.
  */
-public class TestChildProcessService extends ChildProcessService {
+public class TestChildProcessService extends Service {
     private static final String TAG = "TestProcessService";
 
     private static final long MAIN_BLOCKING_DURATION_MS = 5000;
@@ -146,7 +147,27 @@
         }
     };
 
-    public TestChildProcessService() {
-        super(new TestChildProcessServiceDelegate());
+    private ChildProcessService mService;
+
+    public TestChildProcessService() {}
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        mService = new ChildProcessService(
+                new TestChildProcessServiceDelegate(), this, getApplicationContext());
+        mService.onCreate();
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        mService.onDestroy();
+        mService = null;
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return mService.onBind(intent);
     }
 }
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService0.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService0.java
index 90fb3336..cc2af2c9 100644
--- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService0.java
+++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService0.java
@@ -4,5 +4,8 @@
 
 package org.chromium.content_shell_apk;
 
+import org.chromium.base.annotations.MainDex;
+
 /** One of the TestChildProcessService defined in the AndroidManifest.xml. */
+@MainDex
 public class TestChildProcessService0 extends TestChildProcessService {}
diff --git a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService1.java b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService1.java
index e7429bac..16fd1be 100644
--- a/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService1.java
+++ b/content/shell/android/shell_apk/src/org/chromium/content_shell_apk/TestChildProcessService1.java
@@ -4,5 +4,8 @@
 
 package org.chromium.content_shell_apk;
 
+import org.chromium.base.annotations.MainDex;
+
 /** One of the TestChildProcessService defined in the AndroidManifest.xml. */
+@MainDex
 public class TestChildProcessService1 extends TestChildProcessService {}
diff --git a/content/test/data/accessibility/aria/aria-searchbox.html b/content/test/data/accessibility/aria/aria-searchbox.html
index 525d61dd..95239da1 100644
--- a/content/test/data/accessibility/aria/aria-searchbox.html
+++ b/content/test/data/accessibility/aria/aria-searchbox.html
@@ -9,6 +9,9 @@
 @WIN-ALLOW:selection_end*
 @WIN-ALLOW:xml-roles*
 @AURALINUX-ALLOW:xml-roles*
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/aria/aria-textbox-with-rich-text-expected-auralinux.txt b/content/test/data/accessibility/aria/aria-textbox-with-rich-text-expected-auralinux.txt
index 9e9f3cd..529e41b 100644
--- a/content/test/data/accessibility/aria/aria-textbox-with-rich-text-expected-auralinux.txt
+++ b/content/test/data/accessibility/aria/aria-textbox-with-rich-text-expected-auralinux.txt
@@ -1,5 +1,5 @@
-[document web]
-++[entry] editable single-line selectable-text xml-roles:textbox
+[document web] caret_offset=0
+++[entry] editable single-line selectable-text xml-roles:textbox caret_offset=0
 ++++[heading] name='TextBox1' editable xml-roles:heading
 ++++++[text] name='TextBox1' editable
 ++[entry] editable multi-line selectable-text xml-roles:textbox
diff --git a/content/test/data/accessibility/aria/aria-textbox-with-rich-text.html b/content/test/data/accessibility/aria/aria-textbox-with-rich-text.html
index 23f6b77..0834c08e 100644
--- a/content/test/data/accessibility/aria/aria-textbox-with-rich-text.html
+++ b/content/test/data/accessibility/aria/aria-textbox-with-rich-text.html
@@ -13,6 +13,9 @@
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:single-line
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/aria/aria-textbox.html b/content/test/data/accessibility/aria/aria-textbox.html
index 9011c68..15279761 100644
--- a/content/test/data/accessibility/aria/aria-textbox.html
+++ b/content/test/data/accessibility/aria/aria-textbox.html
@@ -12,6 +12,9 @@
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:single-line
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/css/color-expected-auralinux.txt b/content/test/data/accessibility/css/color-expected-auralinux.txt
new file mode 100644
index 0000000..ddf681c
--- /dev/null
+++ b/content/test/data/accessibility/css/color-expected-auralinux.txt
@@ -0,0 +1,10 @@
+[document web] offset=0 fg-color=255,0,0 bg-color=0,0,255 offset=1 fg-color=0,0,0 bg-color=255,255,255
+++[paragraph] offset=0 fg-color=255,0,0 bg-color=0,0,255
+++++[text] name='Red on blue.' offset=0 fg-color=255,0,0 bg-color=0,0,255
+++[section] selectable-text offset=0 fg-color=0,0,0 bg-color=255,255,255 offset=9 fg-color=0,0,0 bg-color=0,0,255 offset=25 fg-color=0,0,0 bg-color=255,255,255 offset=26 fg-color=0,255,0 bg-color=255,255,255
+++++[text] name='Default.' offset=0 fg-color=0,0,0 bg-color=255,255,255
+++++[text] name=' ' offset=0 fg-color=0,0,0 bg-color=255,255,255
+++++[text] name='Blue background.' offset=0 fg-color=0,0,0 bg-color=0,0,255
+++++[text] name=' ' offset=0 fg-color=0,0,0 bg-color=255,255,255
+++++[text] name='Green text.' offset=0 fg-color=0,255,0 bg-color=255,255,255
+
diff --git a/content/test/data/accessibility/css/color.html b/content/test/data/accessibility/css/color.html
index fa3f55d0..5e76ab0c 100644
--- a/content/test/data/accessibility/css/color.html
+++ b/content/test/data/accessibility/css/color.html
@@ -5,6 +5,9 @@
 @WIN-ALLOW:color:*
 @WIN-ALLOW:ia2_hypertext=*
 @WIN-ALLOW:offset:*
+@AURALINUX-ALLOW:bg-color=*
+@AURALINUX-ALLOW:fg-color=*
+@AURALINUX-ALLOW:offset=*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/css/font-family-expected-auralinux.txt b/content/test/data/accessibility/css/font-family-expected-auralinux.txt
new file mode 100644
index 0000000..85c62f2
--- /dev/null
+++ b/content/test/data/accessibility/css/font-family-expected-auralinux.txt
@@ -0,0 +1,6 @@
+[document web] offset=0 family-name=Times New Roman
+++[landmark] offset=0 family-name=-webkit-monospace offset=1 family-name=Times New Roman
+++++[paragraph] offset=0 family-name=-webkit-monospace
+++++++[text] name='Monospace' offset=0 family-name=-webkit-monospace
+++++[text] name='Sans serif' offset=0 family-name=Times New Roman
+
diff --git a/content/test/data/accessibility/css/font-family.html b/content/test/data/accessibility/css/font-family.html
index da60143..60fe3d0f 100644
--- a/content/test/data/accessibility/css/font-family.html
+++ b/content/test/data/accessibility/css/font-family.html
@@ -2,6 +2,8 @@
 @BLINK-ALLOW:fontFamily=*
 @WIN-ALLOW:font-family:*
 @WIN-ALLOW:offset:*
+@AURALINUX-ALLOW:family-name=*
+@AURALINUX-ALLOW:offset=*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/css/font-style-expected-auralinux.txt b/content/test/data/accessibility/css/font-style-expected-auralinux.txt
new file mode 100644
index 0000000..332a101
--- /dev/null
+++ b/content/test/data/accessibility/css/font-style-expected-auralinux.txt
@@ -0,0 +1,29 @@
+[document web] offset=0
+++[paragraph] offset=0 offset=4 weight=700 offset=9 offset=10 style=italic offset=15 offset=16 underline=single offset=19 offset=20 style=italic weight=700 offset=26 offset=27 underline=single style=italic offset=31 offset=32 underline=single style=italic weight=700
+++++[text] name='The ' offset=0
+++++[text] name='quick' offset=0 weight=700
+++++[text] name=' ' offset=0
+++++[text] name='brown' offset=0 style=italic
+++++[text] name=' ' offset=0
+++++[text] name='fox' offset=0 underline=single
+++++[text] name=' ' offset=0
+++++[text] name='jumped' offset=0 style=italic weight=700
+++++[text] name=' ' offset=0
+++++[text] name='over' offset=0 underline=single style=italic
+++++[text] name=' ' offset=0
+++++[text] name='dog' offset=0 underline=single style=italic weight=700
+++[section] selectable-text offset=0 offset=7 weight=700 offset=11 offset=12 style=italic offset=18 offset=19 underline=single offset=28 offset=29 offset=41
+++++[text] name='Normal' offset=0
+++++[text] name=' ' offset=0
+++++[text] name='bold' offset=0 weight=700
+++++[text] name=' ' offset=0
+++++[text] name='italic' offset=0 style=italic
+++++[text] name=' ' offset=0
+++++[text] name='underline' offset=0 underline=single
+++++[text] name=' ' offset=0
+++++[text] name='line-through' offset=0
+++++[text] name=' ' offset=0
+++++[subscript] name='subscript' offset=0
+++++[text] name=' ' offset=0
+++++[superscript] name='superscript' offset=0
+
diff --git a/content/test/data/accessibility/css/font-style.html b/content/test/data/accessibility/css/font-style.html
index 69cd061..8de79cb 100644
--- a/content/test/data/accessibility/css/font-style.html
+++ b/content/test/data/accessibility/css/font-style.html
@@ -7,6 +7,11 @@
 @WIN-ALLOW:ia2_hypertext=*
 @WIN-ALLOW:offset:*
 @WIN-ALLOW:text*
+@AURALINUX-ALLOW:weight=*
+@AURALINUX-ALLOW:style=*
+@AURALINUX-ALLOW:underline=*
+@AURALINUX-ALLOW:hypertext=*
+@AURALINUX-ALLOW:offset=*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/css/language-expected-auralinux.txt b/content/test/data/accessibility/css/language-expected-auralinux.txt
new file mode 100644
index 0000000..9d23747
--- /dev/null
+++ b/content/test/data/accessibility/css/language-expected-auralinux.txt
@@ -0,0 +1,5 @@
+[document web] offset=0 language=es-ES offset=1 language=fr-FR
+++[paragraph] offset=0 language=es-ES
+++++[text] name='Espanyol' offset=0 language=es-ES
+++[text] name='Comment allez-vous?' offset=0 language=fr-FR
+
diff --git a/content/test/data/accessibility/css/language.html b/content/test/data/accessibility/css/language.html
index 75671dc..0475a838 100644
--- a/content/test/data/accessibility/css/language.html
+++ b/content/test/data/accessibility/css/language.html
@@ -4,6 +4,8 @@
 @WIN-ALLOW:language:*
 @WIN-ALLOW:offset:*
 @MAC-ALLOW:AXLang*
+@AURALINUX-ALLOW:language=*
+@AURALINUX-ALLOW:offset=*
 -->
 <!DOCTYPE html>
 <html lang="en-US">
diff --git a/content/test/data/accessibility/html/contenteditable-descendants-with-selection-expected-auralinux.txt b/content/test/data/accessibility/html/contenteditable-descendants-with-selection-expected-auralinux.txt
index c7d2535..d9dabe0 100644
--- a/content/test/data/accessibility/html/contenteditable-descendants-with-selection-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/contenteditable-descendants-with-selection-expected-auralinux.txt
@@ -1,19 +1,19 @@
-[document web]
-++[section] editable multi-line selectable-text
-++++[paragraph] editable
-++++++[text] name='A contenteditable with a ' editable
-++++++[link] name='link' editable
-++++++++[text] name='link' editable
-++++++[text] name=' and an ' editable
-++++++[image] name='Image' editable
-++++++[text] name=' and a ' editable
-++++++[push button] name='Button' editable
-++++++[text] name='.' editable
-++++[table] editable cols=1 headers=(NONE); rows=1 headers=(NONE); caption=false; spans=(all: 1x1)
-++++++[table row] editable
-++++++++[table cell] name='Always expose editable tables as tables.' editable (row=0, col=0, row_span=1, col_span=1, n_row_headers=0, n_col_headers=0)
-++++++++++[text] name='Always expose editable tables as tables.' editable
-++++[list] editable
-++++++[list item] editable
-++++++++[static] name='1. ' editable
-++++++++[text] name='Editable list item.' editable
+[document web] caret_offset=1 selection_start=0 selection_end=1
+++[section] editable multi-line selectable-text caret_offset=3 selection_start=0 selection_end=3
+++++[paragraph] editable selection_start=0 selection_end=3
+++++++[text] name='A contenteditable with a ' editable selection_start=0 selection_end=3
+++++++[link] name='link' editable selection_start=0 selection_end=3
+++++++++[text] name='link' editable selection_start=0 selection_end=3
+++++++[text] name=' and an ' editable selection_start=0 selection_end=3
+++++++[image] name='Image' editable selection_start=0 selection_end=3
+++++++[text] name=' and a ' editable selection_start=0 selection_end=3
+++++++[push button] name='Button' editable selection_start=0 selection_end=3
+++++++[text] name='.' editable selection_start=0 selection_end=3
+++++[table] editable cols=1 headers=(NONE); rows=1 headers=(NONE); caption=false; spans=(all: 1x1) selection_start=0 selection_end=3
+++++++[table row] editable selection_start=0 selection_end=3
+++++++++[table cell] name='Always expose editable tables as tables.' editable (row=0, col=0, row_span=1, col_span=1, n_row_headers=0, n_col_headers=0) selection_start=0 selection_end=3
+++++++++++[text] name='Always expose editable tables as tables.' editable selection_start=0 selection_end=3
+++++[list] editable selection_start=0 selection_end=3
+++++++[list item] editable selection_start=0 selection_end=3
+++++++++[static] name='1. ' editable selection_start=0 selection_end=3
+++++++++[text] name='Editable list item.' editable selection_start=0 selection_end=3
diff --git a/content/test/data/accessibility/html/contenteditable-descendants-with-selection.html b/content/test/data/accessibility/html/contenteditable-descendants-with-selection.html
index 3f91d75..c92572e 100644
--- a/content/test/data/accessibility/html/contenteditable-descendants-with-selection.html
+++ b/content/test/data/accessibility/html/contenteditable-descendants-with-selection.html
@@ -13,6 +13,9 @@
 @BLINK-ALLOW:*textSel*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <div id="contenteditable" tabindex="0" contenteditable>
   <p>A contenteditable with a
diff --git a/content/test/data/accessibility/html/contenteditable-descendants.html b/content/test/data/accessibility/html/contenteditable-descendants.html
index c95f25d..9ee48d6 100644
--- a/content/test/data/accessibility/html/contenteditable-descendants.html
+++ b/content/test/data/accessibility/html/contenteditable-descendants.html
@@ -16,6 +16,8 @@
 @BLINK-ALLOW:textSel*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <div contenteditable>
   <p>A contenteditable with a
diff --git a/content/test/data/accessibility/html/contenteditable-with-embedded-contenteditables.html b/content/test/data/accessibility/html/contenteditable-with-embedded-contenteditables.html
index aaa3c91..aad7347f 100644
--- a/content/test/data/accessibility/html/contenteditable-with-embedded-contenteditables.html
+++ b/content/test/data/accessibility/html/contenteditable-with-embedded-contenteditables.html
@@ -10,6 +10,9 @@
 @BLINK-ALLOW:textSel*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <div contenteditable>
   <p>This is editable.</p>
diff --git a/content/test/data/accessibility/html/ignored-selection-between-text-expected-auralinux.txt b/content/test/data/accessibility/html/ignored-selection-between-text-expected-auralinux.txt
index 58f9e0d..ce518f5 100644
--- a/content/test/data/accessibility/html/ignored-selection-between-text-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/ignored-selection-between-text-expected-auralinux.txt
@@ -1,8 +1,8 @@
-[document web]
+[document web] caret_offset=2 selection_start=0 selection_end=2
 ++[section]
 ++++[text] name='before selection'
-++[section]
-++++[text] name='this text is not ignored'
-++[section]
-++++[text] name='after selection'
-++[text] name='Done'
\ No newline at end of file
+++[section] selection_start=0 selection_end=24
+++++[text] name='this text is not ignored' selection_start=0 selection_end=24
+++[section] caret_offset=0
+++++[text] name='after selection' caret_offset=0
+++[text] name='Done'
diff --git a/content/test/data/accessibility/html/ignored-selection-between-text.html b/content/test/data/accessibility/html/ignored-selection-between-text.html
index 83a33c1..dd07d84 100644
--- a/content/test/data/accessibility/html/ignored-selection-between-text.html
+++ b/content/test/data/accessibility/html/ignored-selection-between-text.html
@@ -9,6 +9,9 @@
 @BLINK-ALLOW:id*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 @WAIT-FOR:Done
 -->
 
diff --git a/content/test/data/accessibility/html/ignored-selection-expected-auralinux.txt b/content/test/data/accessibility/html/ignored-selection-expected-auralinux.txt
index 351725f..1581150 100644
--- a/content/test/data/accessibility/html/ignored-selection-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/ignored-selection-expected-auralinux.txt
@@ -1,5 +1,5 @@
-[document web]
-++[text] name='this text is not ignored'
-++[section]
-++++[text] name='after selection'
-++[text] name='Done'
\ No newline at end of file
+[document web] caret_offset=24 selection_start=0 selection_end=24
+++[text] name='this text is not ignored' selection_start=0 selection_end=24
+++[section] caret_offset=0
+++++[text] name='after selection' caret_offset=0
+++[text] name='Done'
diff --git a/content/test/data/accessibility/html/ignored-selection-no-unignored-expected-auralinux.txt b/content/test/data/accessibility/html/ignored-selection-no-unignored-expected-auralinux.txt
index 67d89a3..5d01d2c 100644
--- a/content/test/data/accessibility/html/ignored-selection-no-unignored-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/ignored-selection-no-unignored-expected-auralinux.txt
@@ -1,2 +1,2 @@
-[document web]
-++[text] name='Done'
\ No newline at end of file
+[document web] caret_offset=0
+++[text] name='Done' caret_offset=0
diff --git a/content/test/data/accessibility/html/ignored-selection-no-unignored.html b/content/test/data/accessibility/html/ignored-selection-no-unignored.html
index 34a10d40..283d9cff 100644
--- a/content/test/data/accessibility/html/ignored-selection-no-unignored.html
+++ b/content/test/data/accessibility/html/ignored-selection-no-unignored.html
@@ -9,6 +9,9 @@
 @BLINK-ALLOW:id*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 @WAIT-FOR:Done
 -->
 
diff --git a/content/test/data/accessibility/html/ignored-selection.html b/content/test/data/accessibility/html/ignored-selection.html
index 7c4490de..bd7325d4d0 100644
--- a/content/test/data/accessibility/html/ignored-selection.html
+++ b/content/test/data/accessibility/html/ignored-selection.html
@@ -9,6 +9,9 @@
 @BLINK-ALLOW:id*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:multi-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 @WAIT-FOR:Done
 -->
 
diff --git a/content/test/data/accessibility/html/input-email-expected-auralinux.txt b/content/test/data/accessibility/html/input-email-expected-auralinux.txt
index 7c3849cb..5f89fc79 100644
--- a/content/test/data/accessibility/html/input-email-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-email-expected-auralinux.txt
@@ -1,3 +1,3 @@
 [document web] focusable focused
 ++[section]
-++++[entry] editable focusable selectable-text text-input-type:email
+++++[entry] editable focusable selectable-text text-input-type:email caret_offset=0
diff --git a/content/test/data/accessibility/html/input-email.html b/content/test/data/accessibility/html/input-email.html
index efd6f9d..0c4950ae 100644
--- a/content/test/data/accessibility/html/input-email.html
+++ b/content/test/data/accessibility/html/input-email.html
@@ -14,6 +14,9 @@
 @AURALINUX-ALLOW:text-input-type:*
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:editable
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/html/input-password-expected-auralinux.txt b/content/test/data/accessibility/html/input-password-expected-auralinux.txt
index d482f55d..3c84d27 100644
--- a/content/test/data/accessibility/html/input-password-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-password-expected-auralinux.txt
@@ -1,4 +1,4 @@
-[document web] focusable
-++[section]
-++++[password text] editable focusable focused selectable-text
+[document web] focusable caret_offset=0
+++[section] caret_offset=0
+++++[password text] editable focusable focused selectable-text caret_offset=6
 
diff --git a/content/test/data/accessibility/html/input-password.html b/content/test/data/accessibility/html/input-password.html
index c9ec012..9a893b77 100644
--- a/content/test/data/accessibility/html/input-password.html
+++ b/content/test/data/accessibility/html/input-password.html
@@ -13,6 +13,9 @@
 @WIN-ALLOW:selection_end*
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:editable
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/html/input-search-expected-auralinux.txt b/content/test/data/accessibility/html/input-search-expected-auralinux.txt
index 6ff961eb..e199093 100644
--- a/content/test/data/accessibility/html/input-search-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-search-expected-auralinux.txt
@@ -1,3 +1,3 @@
 [document web] focusable focused
 ++[section]
-++++[entry] editable focusable selectable-text text-input-type:search
+++++[entry] editable focusable selectable-text text-input-type:search caret_offset=0
diff --git a/content/test/data/accessibility/html/input-search.html b/content/test/data/accessibility/html/input-search.html
index 962e186..7a44bd7 100644
--- a/content/test/data/accessibility/html/input-search.html
+++ b/content/test/data/accessibility/html/input-search.html
@@ -11,6 +11,9 @@
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:text-input-type*
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/html/input-tel-expected-auralinux.txt b/content/test/data/accessibility/html/input-tel-expected-auralinux.txt
index c488983..f9625fe 100644
--- a/content/test/data/accessibility/html/input-tel-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-tel-expected-auralinux.txt
@@ -1,3 +1,3 @@
 [document web] focusable focused
 ++[section]
-++++[entry] editable focusable selectable-text text-input-type:tel
+++++[entry] editable focusable selectable-text text-input-type:tel caret_offset=0
diff --git a/content/test/data/accessibility/html/input-tel.html b/content/test/data/accessibility/html/input-tel.html
index c95c882..b6ccfb6 100644
--- a/content/test/data/accessibility/html/input-tel.html
+++ b/content/test/data/accessibility/html/input-tel.html
@@ -12,6 +12,9 @@
 @AURALINUX-ALLOW:text-input-type*
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:focus*
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/html/input-text-expected-auralinux.txt b/content/test/data/accessibility/html/input-text-expected-auralinux.txt
index 0b64ce28..8bf5585 100644
--- a/content/test/data/accessibility/html/input-text-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-text-expected-auralinux.txt
@@ -1,3 +1,3 @@
-[document web] focusable
-++[section]
-++++[entry] name='Name' editable focusable focused single-line selectable-text text-input-type:text
+[document web] focusable caret_offset=0
+++[section] caret_offset=0
+++++[entry] name='Name' editable focusable focused single-line selectable-text text-input-type:text caret_offset=0
diff --git a/content/test/data/accessibility/html/input-text-read-only-expected-auralinux.txt b/content/test/data/accessibility/html/input-text-read-only-expected-auralinux.txt
index 0fa1ad2..e76a15a 100644
--- a/content/test/data/accessibility/html/input-text-read-only-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-text-read-only-expected-auralinux.txt
@@ -1,3 +1,3 @@
-[document web] focusable
-++[section]
-++++[entry] name='Name' focusable focused single-line text-input-type:text
+[document web] focusable caret_offset=0
+++[section] caret_offset=0
+++++[entry] name='Name' focusable focused single-line text-input-type:text caret_offset=0
diff --git a/content/test/data/accessibility/html/input-text-read-only.html b/content/test/data/accessibility/html/input-text-read-only.html
index cc3b662..09e3b36 100644
--- a/content/test/data/accessibility/html/input-text-read-only.html
+++ b/content/test/data/accessibility/html/input-text-read-only.html
@@ -14,6 +14,9 @@
 @AURALINUX-ALLOW:*-line
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:focus*
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 @AURALINUX-DENY:read-only
 @AURALINUX-DENY:selectable-text
 -->
diff --git a/content/test/data/accessibility/html/input-text-with-selection-expected-auralinux.txt b/content/test/data/accessibility/html/input-text-with-selection-expected-auralinux.txt
index a09dae2..733246e 100644
--- a/content/test/data/accessibility/html/input-text-with-selection-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-text-with-selection-expected-auralinux.txt
@@ -1,3 +1,3 @@
-[document web] focusable
-++[section]
-++++[entry] editable focusable focused single-line selectable-text text-input-type:text
+[document web] focusable caret_offset=1 selection_start=0 selection_end=1
+++[section] caret_offset=1 selection_start=0 selection_end=1
+++++[entry] editable focusable focused single-line selectable-text text-input-type:text caret_offset=5 selection_start=3 selection_end=5
diff --git a/content/test/data/accessibility/html/input-text-with-selection.html b/content/test/data/accessibility/html/input-text-with-selection.html
index 94729b3..f748406 100644
--- a/content/test/data/accessibility/html/input-text-with-selection.html
+++ b/content/test/data/accessibility/html/input-text-with-selection.html
@@ -12,6 +12,9 @@
 @AURALINUX-ALLOW:*-line
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:focus*
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 @BLINK-ALLOW:inputType=*
 @BLINK-ALLOW:textSel*
 -->
diff --git a/content/test/data/accessibility/html/input-text.html b/content/test/data/accessibility/html/input-text.html
index 82b49ae..74a13df 100644
--- a/content/test/data/accessibility/html/input-text.html
+++ b/content/test/data/accessibility/html/input-text.html
@@ -17,6 +17,9 @@
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:*-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <html>
   <body>
diff --git a/content/test/data/accessibility/html/input-url-expected-auralinux.txt b/content/test/data/accessibility/html/input-url-expected-auralinux.txt
index 04cd01b..1f2d150 100644
--- a/content/test/data/accessibility/html/input-url-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/input-url-expected-auralinux.txt
@@ -1,3 +1,3 @@
 [document web] focusable focused
 ++[section]
-++++[entry] editable focusable selectable-text text-input-type:url
+++++[entry] editable focusable selectable-text text-input-type:url caret_offset=0
diff --git a/content/test/data/accessibility/html/input-url.html b/content/test/data/accessibility/html/input-url.html
index 05ad0df2..90e68d9 100644
--- a/content/test/data/accessibility/html/input-url.html
+++ b/content/test/data/accessibility/html/input-url.html
@@ -12,6 +12,9 @@
 @AURALINUX-ALLOW:text-input-type:*
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:editable
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 @BLINK-ALLOW:inputType=*
 @BLINK-ALLOW:textSel*
 -->
diff --git a/content/test/data/accessibility/html/textarea-expected-auralinux.txt b/content/test/data/accessibility/html/textarea-expected-auralinux.txt
index 614277c..43f2f173 100644
--- a/content/test/data/accessibility/html/textarea-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/textarea-expected-auralinux.txt
@@ -1,3 +1,3 @@
 [document web] focusable focused
 ++[section]
-++++[entry] editable focusable multi-line selectable-text
+++++[entry] editable focusable multi-line selectable-text caret_offset=0
diff --git a/content/test/data/accessibility/html/textarea-read-only-expected-auralinux.txt b/content/test/data/accessibility/html/textarea-read-only-expected-auralinux.txt
index ee6fd8a..faa8b55 100644
--- a/content/test/data/accessibility/html/textarea-read-only-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/textarea-read-only-expected-auralinux.txt
@@ -1,3 +1,3 @@
 [document web] focusable focused
 ++[section]
-++++[entry] focusable multi-line selectable-text
+++++[entry] focusable multi-line selectable-text caret_offset=0
diff --git a/content/test/data/accessibility/html/textarea-read-only.html b/content/test/data/accessibility/html/textarea-read-only.html
index 675b5c5..3858624 100644
--- a/content/test/data/accessibility/html/textarea-read-only.html
+++ b/content/test/data/accessibility/html/textarea-read-only.html
@@ -11,6 +11,9 @@
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:*-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/html/textarea-with-selection-expected-auralinux.txt b/content/test/data/accessibility/html/textarea-with-selection-expected-auralinux.txt
index c9caf30e9..dbac219e 100644
--- a/content/test/data/accessibility/html/textarea-with-selection-expected-auralinux.txt
+++ b/content/test/data/accessibility/html/textarea-with-selection-expected-auralinux.txt
@@ -1,3 +1,3 @@
-[document web] focusable
-++[section]
-++++[entry] editable focusable focused multi-line selectable-text
+[document web] focusable caret_offset=1 selection_start=0 selection_end=1
+++[section] caret_offset=1 selection_start=0 selection_end=1
+++++[entry] editable focusable focused multi-line selectable-text caret_offset=58 selection_start=0 selection_end=58
diff --git a/content/test/data/accessibility/html/textarea-with-selection.html b/content/test/data/accessibility/html/textarea-with-selection.html
index b758be14..ba4b263 100644
--- a/content/test/data/accessibility/html/textarea-with-selection.html
+++ b/content/test/data/accessibility/html/textarea-with-selection.html
@@ -11,6 +11,9 @@
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:*-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <!DOCTYPE html>
 <html>
diff --git a/content/test/data/accessibility/html/textarea.html b/content/test/data/accessibility/html/textarea.html
index c540d6705..fb5d0fc2 100644
--- a/content/test/data/accessibility/html/textarea.html
+++ b/content/test/data/accessibility/html/textarea.html
@@ -14,6 +14,9 @@
 @AURALINUX-ALLOW:editable
 @AURALINUX-ALLOW:focus*
 @AURALINUX-ALLOW:*-line
+@AURALINUX-ALLOW:caret_offset*
+@AURALINUX-ALLOW:selection_start*
+@AURALINUX-ALLOW:selection_end*
 -->
 <html>
 <body>
diff --git a/content/test/data/browsing_data/site_data.html b/content/test/data/browsing_data/site_data.html
index 0a2a8883..855e262 100644
--- a/content/test/data/browsing_data/site_data.html
+++ b/content/test/data/browsing_data/site_data.html
@@ -33,7 +33,11 @@
   }
 
   function hasLocalStorage() {
-    domAutomationController.send(localStorage.getItem('foo') == 'bar');
+    try {
+      domAutomationController.send(localStorage.getItem('foo') == 'bar');
+    } catch (e) {
+      failure_();
+    }
   }
 
   function setSessionStorage() {
@@ -42,7 +46,11 @@
   }
 
   function hasSessionStorage() {
-    domAutomationController.send(sessionStorage.getItem('foo') == 'bar');
+    try {
+      domAutomationController.send(sessionStorage.getItem('foo') == 'bar');
+    } catch (e) {
+      failure_();
+    }
   }
 
   function setServiceWorker() {
@@ -54,7 +62,7 @@
   function hasServiceWorker() {
     navigator.serviceWorker.getRegistrations().then(function (registrations) {
       domAutomationController.send(registrations.length > 0);
-    });
+    }).catch(failure_);
   }
 
   function setCacheStorage() {
@@ -68,7 +76,7 @@
       cache.keys().then(function (keys) {
         domAutomationController.send(keys.length > 0);
       });
-    });
+    }).catch(failure_);
   }
 
   function openFile_(name, options, callback, error) {
@@ -94,7 +102,11 @@
   }
 
   function hasWebSql() {
-    var db = openDatabase('testdb', '1.0', 'a test db', 1024);
+    try {
+      var db = openDatabase('testdb', '1.0', 'a test db', 1024);
+    } catch (e) {
+      return failure_();
+    }
     var num_results;
     db.transaction(function (tx) {
       tx.executeSql('CREATE TABLE IF NOT EXISTS foo (text)');
diff --git a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt
index 4e3514c..e5d89fe10 100644
--- a/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt
+++ b/content/test/gpu/gpu_tests/test_expectations/webgl_conformance_expectations.txt
@@ -225,6 +225,8 @@
 crbug.com/950123 [ win amd-0x699f opengl ] conformance/glsl/samplers/glsl-function-texture2dprojlod.html [ Skip ]
 crbug.com/950123 [ win amd-0x699f opengl ] conformance/rendering/line-rendering-quality.html [ Skip ]
 crbug.com/952887 [ win amd-0x699f opengl passthrough ] conformance/rendering/multisample-corruption.html [ Skip ]
+crbug.com/1005814 [ win amd-0x699f opengl passthrough ] conformance/textures/image_data/tex-2d-alpha-alpha-unsigned_byte.html [ Failure ]
+crbug.com/1005814 [ win amd-0x699f opengl passthrough ] conformance/textures/video/tex-2d-rgba-rgba-unsigned_byte.html [ Failure ]
 
 # Mark ANGLE's OpenGL as flaky on Windows Amd
 crbug.com/582083 [ win amd opengl ] conformance/* [ RetryOnFailure ]
diff --git a/device/vr/orientation/orientation_device.cc b/device/vr/orientation/orientation_device.cc
index fe7b0a9..6e148ff22 100644
--- a/device/vr/orientation/orientation_device.cc
+++ b/device/vr/orientation/orientation_device.cc
@@ -99,7 +99,7 @@
   }
 
   default_config.set_frequency(kDefaultPumpFrequencyHz);
-  sensor_.set_connection_error_handler(base::BindOnce(
+  sensor_.set_disconnect_handler(base::BindOnce(
       &VROrientationDevice::HandleSensorError, base::Unretained(this)));
   sensor_->ConfigureReadingChangeNotifications(false /* disabled */);
   sensor_->AddConfiguration(
diff --git a/device/vr/orientation/orientation_device.h b/device/vr/orientation/orientation_device.h
index eff93f7a0..0c9b07d 100644
--- a/device/vr/orientation/orientation_device.h
+++ b/device/vr/orientation/orientation_device.h
@@ -14,6 +14,7 @@
 #include "device/vr/public/mojom/vr_service.mojom.h"
 #include "device/vr/vr_device_base.h"
 #include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/remote.h"
 #include "services/device/public/mojom/sensor_provider.mojom.h"
 #include "ui/gfx/geometry/quaternion.h"
 
@@ -76,7 +77,7 @@
   base::Optional<gfx::Quaternion> base_pose_;
   gfx::Quaternion latest_pose_;
 
-  mojom::SensorPtr sensor_;
+  mojo::Remote<mojom::Sensor> sensor_;
   std::unique_ptr<SensorReadingSharedBufferReader> shared_buffer_reader_;
   mojo::Binding<mojom::SensorClient> binding_;
 
diff --git a/device/vr/orientation/orientation_device_provider_unittest.cc b/device/vr/orientation/orientation_device_provider_unittest.cc
index 1e2a2949..960d529b 100644
--- a/device/vr/orientation/orientation_device_provider_unittest.cc
+++ b/device/vr/orientation/orientation_device_provider_unittest.cc
@@ -18,6 +18,7 @@
 #include "device/vr/orientation/orientation_device_provider.h"
 #include "device/vr/test/fake_orientation_provider.h"
 #include "device/vr/test/fake_sensor_provider.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
 #include "services/device/public/cpp/generic_sensor/sensor_reading.h"
 #include "services/device/public/cpp/generic_sensor/sensor_reading_shared_buffer_reader.h"
 #include "services/device/public/cpp/generic_sensor/sensor_traits.h"
@@ -38,7 +39,7 @@
     fake_sensor_provider_ = std::make_unique<FakeSensorProvider>();
 
     fake_sensor_ = std::make_unique<FakeOrientationSensor>(
-        mojo::MakeRequest(&sensor_ptr_));
+        sensor_.InitWithNewPipeAndPassReceiver());
     shared_buffer_handle_ = mojo::SharedBufferHandle::Create(
         sizeof(SensorReadingSharedBuffer) *
         (static_cast<uint64_t>(mojom::SensorType::kMaxValue) + 1));
@@ -70,7 +71,7 @@
 
   mojom::SensorInitParamsPtr FakeInitParams() {
     auto init_params = mojom::SensorInitParams::New();
-    init_params->sensor = std::move(sensor_ptr_);
+    init_params->sensor = std::move(sensor_);
     init_params->default_configuration = PlatformSensorConfiguration(
         SensorTraits<kOrientationSensorType>::kDefaultFrequency);
 
@@ -142,7 +143,7 @@
 
   // Fake Sensor Init params objects
   std::unique_ptr<FakeOrientationSensor> fake_sensor_;
-  mojom::SensorPtrInfo sensor_ptr_;
+  mojo::PendingRemote<mojom::Sensor> sensor_;
   mojo::ScopedSharedBufferHandle shared_buffer_handle_;
   mojom::SensorClientPtr sensor_client_ptr_;
 
diff --git a/device/vr/orientation/orientation_device_unittest.cc b/device/vr/orientation/orientation_device_unittest.cc
index be55016..cdca116f 100644
--- a/device/vr/orientation/orientation_device_unittest.cc
+++ b/device/vr/orientation/orientation_device_unittest.cc
@@ -16,6 +16,7 @@
 #include "device/vr/orientation/orientation_session.h"
 #include "device/vr/test/fake_orientation_provider.h"
 #include "device/vr/test/fake_sensor_provider.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
 #include "services/device/public/cpp/generic_sensor/sensor_reading.h"
 #include "services/device/public/cpp/generic_sensor/sensor_reading_shared_buffer_reader.h"
 #include "services/device/public/cpp/generic_sensor/sensor_traits.h"
@@ -82,7 +83,7 @@
         mojo::MakeRequest(&sensor_provider_ptr_));
 
     fake_sensor_ = std::make_unique<FakeOrientationSensor>(
-        mojo::MakeRequest(&sensor_ptr_));
+        sensor_.InitWithNewPipeAndPassReceiver());
 
     shared_buffer_handle_ = mojo::SharedBufferHandle::Create(
         sizeof(SensorReadingSharedBuffer) *
@@ -190,7 +191,7 @@
 
   mojom::SensorInitParamsPtr FakeInitParams() {
     auto init_params = mojom::SensorInitParams::New();
-    init_params->sensor = std::move(sensor_ptr_);
+    init_params->sensor = std::move(sensor_);
     init_params->default_configuration = PlatformSensorConfiguration(
         SensorTraits<kOrientationSensorType>::kDefaultFrequency);
 
@@ -233,7 +234,7 @@
 
   // Fake Sensor Init params objects
   std::unique_ptr<FakeOrientationSensor> fake_sensor_;
-  mojom::SensorPtrInfo sensor_ptr_;
+  mojo::PendingRemote<mojom::Sensor> sensor_;
   mojo::ScopedSharedBufferHandle shared_buffer_handle_;
   mojo::ScopedSharedBufferMapping shared_buffer_mapping_;
   mojom::SensorClientPtr sensor_client_ptr_;
diff --git a/device/vr/test/fake_orientation_provider.cc b/device/vr/test/fake_orientation_provider.cc
index c9d6f37b..9f25f20 100644
--- a/device/vr/test/fake_orientation_provider.cc
+++ b/device/vr/test/fake_orientation_provider.cc
@@ -8,10 +8,9 @@
 
 namespace device {
 
-FakeOrientationSensor::FakeOrientationSensor(mojom::SensorRequest request)
-    : binding_(this) {
-  binding_.Bind(std::move(request));
-}
+FakeOrientationSensor::FakeOrientationSensor(
+    mojo::PendingReceiver<mojom::Sensor> receiver)
+    : receiver_(this, std::move(receiver)) {}
 
 FakeOrientationSensor::~FakeOrientationSensor() = default;
 
diff --git a/device/vr/test/fake_orientation_provider.h b/device/vr/test/fake_orientation_provider.h
index 6eeed9e..354a154 100644
--- a/device/vr/test/fake_orientation_provider.h
+++ b/device/vr/test/fake_orientation_provider.h
@@ -5,14 +5,15 @@
 #ifndef DEVICE_VR_TEST_FAKE_ORIENTATION_PROVIDER_H_
 #define DEVICE_VR_TEST_FAKE_ORIENTATION_PROVIDER_H_
 
-#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/receiver.h"
 #include "services/device/public/mojom/sensor.mojom.h"
 
 namespace device {
 
 class FakeOrientationSensor : public mojom::Sensor {
  public:
-  FakeOrientationSensor(mojom::SensorRequest request);
+  FakeOrientationSensor(mojo::PendingReceiver<mojom::Sensor> receiver);
   ~FakeOrientationSensor() override;
 
   void AddConfiguration(const PlatformSensorConfiguration& configuration,
@@ -27,7 +28,7 @@
   void Resume() override {}
 
  private:
-  mojo::Binding<mojom::Sensor> binding_;
+  mojo::Receiver<mojom::Sensor> receiver_;
 
   DISALLOW_COPY_AND_ASSIGN(FakeOrientationSensor);
 };
diff --git a/gpu/vulkan/vulkan_swap_chain.cc b/gpu/vulkan/vulkan_swap_chain.cc
index df049018..e4927996 100644
--- a/gpu/vulkan/vulkan_swap_chain.cc
+++ b/gpu/vulkan/vulkan_swap_chain.cc
@@ -46,7 +46,7 @@
     bool use_protected_memory,
     std::unique_ptr<VulkanSwapChain> old_swap_chain) {
   DCHECK(device_queue);
-  DCHECK(!use_protected_memory || device_queue_->allow_protected_memory());
+  DCHECK(!use_protected_memory || device_queue->allow_protected_memory());
   use_protected_memory_ = use_protected_memory;
   device_queue_ = device_queue;
   device_queue_->GetFenceHelper()->ProcessCleanupTasks();
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm
index 65dfa89..7fc9e0fe7 100644
--- a/ios/chrome/browser/flags/about_flags.mm
+++ b/ios/chrome/browser/flags/about_flags.mm
@@ -304,9 +304,6 @@
      flag_descriptions::kNewClearBrowsingDataUIName,
      flag_descriptions::kNewClearBrowsingDataUIDescription, flags_ui::kOsIos,
      FEATURE_VALUE_TYPE(kNewClearBrowsingDataUI)},
-    {"unified-consent", flag_descriptions::kUnifiedConsentName,
-     flag_descriptions::kUnifiedConsentDescription, flags_ui::kOsIos,
-     FEATURE_VALUE_TYPE(unified_consent::kUnifiedConsent)},
     {"autofill-show-all-profiles-on-prefilled-forms",
      flag_descriptions::kAutofillShowAllSuggestionsOnPrefilledFormsName,
      flag_descriptions::kAutofillShowAllSuggestionsOnPrefilledFormsDescription,
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
index 31568f1..5ff7caa6 100644
--- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
+++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -352,12 +352,6 @@
 const char kToolbarNewTabButtonDescription[] =
     "When enabled, the bottom toolbar middle button opens a new tab";
 
-const char kUnifiedConsentName[] = "Unified Consent";
-const char kUnifiedConsentDescription[] =
-    "Enables a unified management of user consent for privacy-related "
-    "features. This includes new confirmation screens and improved settings "
-    "pages.";
-
 const char kUseDdljsonApiName[] = "Use new ddljson API for Doodles";
 const char kUseDdljsonApiDescription[] =
     "Enables the new ddljson API to fetch Doodles for the NTP.";
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
index b6f2e24..1616ad7 100644
--- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
+++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -301,10 +301,6 @@
 extern const char kToolbarNewTabButtonName[];
 extern const char kToolbarNewTabButtonDescription[];
 
-// Title and description for the flag to enable the unified consent.
-extern const char kUnifiedConsentName[];
-extern const char kUnifiedConsentDescription[];
-
 // Title and description for the flag to enable the ddljson Doodle API.
 extern const char kUseDdljsonApiName[];
 extern const char kUseDdljsonApiDescription[];
diff --git a/ios/chrome/browser/signin/ios_chrome_signin_client.h b/ios/chrome/browser/signin/ios_chrome_signin_client.h
index bbe8cae..397eb40 100644
--- a/ios/chrome/browser/signin/ios_chrome_signin_client.h
+++ b/ios/chrome/browser/signin/ios_chrome_signin_client.h
@@ -31,7 +31,6 @@
   void Shutdown() override;
 
   // SigninClient implementation.
-  std::string GetProductVersion() override;
   std::unique_ptr<GaiaAuthFetcher> CreateGaiaAuthFetcher(
       GaiaAuthConsumer* consumer,
       gaia::GaiaSource source) override;
diff --git a/ios/chrome/browser/signin/ios_chrome_signin_client.mm b/ios/chrome/browser/signin/ios_chrome_signin_client.mm
index 9b1715ab..254b4d9 100644
--- a/ios/chrome/browser/signin/ios_chrome_signin_client.mm
+++ b/ios/chrome/browser/signin/ios_chrome_signin_client.mm
@@ -40,13 +40,6 @@
   network_callback_helper_.reset();
 }
 
-// Returns a string describing the chrome version environment. Version format:
-// <Build Info> <OS> <Version number> (<Last change>)<channel or "-devel">
-// If version information is unavailable, returns "invalid."
-std::string IOSChromeSigninClient::GetProductVersion() {
-  return GetVersionString();
-}
-
 PrefService* IOSChromeSigninClient::GetPrefs() {
   return browser_state_->GetPrefs();
 }
diff --git a/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.h b/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.h
index c00f4dbe..03ef3716 100644
--- a/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.h
+++ b/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.h
@@ -57,6 +57,9 @@
 - (instancetype)initWithBaseViewController:(UIViewController*)viewController
                                    browser:(Browser*)browser NS_UNAVAILABLE;
 
+// This resets the input accessory to a clean state.
+- (void)reset;
+
 @end
 
 #endif  // IOS_CHROME_BROWSER_UI_AUTOFILL_FORM_INPUT_ACCESSORY_FORM_INPUT_ACCESSORY_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.mm b/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.mm
index 0701f16a..b1f2a3c 100644
--- a/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.mm
+++ b/ios/chrome/browser/ui/autofill/form_input_accessory/form_input_accessory_coordinator.mm
@@ -107,6 +107,10 @@
   [self.formInputAccessoryMediator disconnect];
 }
 
+- (void)reset {
+  [self.formInputAccessoryViewController reset];
+}
+
 #pragma mark - Presenting Children
 
 - (void)stopChildren {
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn b/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn
index 06bdb05c..0d5351b 100644
--- a/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn
+++ b/ios/chrome/browser/ui/autofill/manual_fill/BUILD.gn
@@ -193,6 +193,7 @@
   configs += [ "//build/config/compiler:enable_arc" ]
   testonly = true
   sources = [
+    "address_view_controller_egtest.mm",
     "card_view_controller_egtest.mm",
     "fallback_coordinator_egtest.mm",
     "fallback_view_controller_egtest.mm",
@@ -210,6 +211,7 @@
     "//components/autofill/ios/browser",
     "//components/keyed_service/core",
     "//components/password_manager/core/browser",
+    "//ios/chrome/app/strings:ios_strings_grit",
     "//ios/chrome/browser",
     "//ios/chrome/browser/autofill",
     "//ios/chrome/browser/passwords",
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/address_view_controller_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/address_view_controller_egtest.mm
new file mode 100644
index 0000000..3655e1ef
--- /dev/null
+++ b/ios/chrome/browser/ui/autofill/manual_fill/address_view_controller_egtest.mm
@@ -0,0 +1,377 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <EarlGrey/EarlGrey.h>
+#import <EarlGrey/GREYKeyboard.h>
+
+#include "base/ios/ios_util.h"
+#include "base/strings/sys_string_conversions.h"
+#include "base/strings/utf_string_conversions.h"
+#import "base/test/ios/wait_util.h"
+#include "components/autofill/core/browser/autofill_test_utils.h"
+#include "components/autofill/core/browser/personal_data_manager.h"
+#include "components/autofill/core/common/autofill_features.h"
+#include "components/autofill/ios/browser/autofill_switches.h"
+#include "components/keyed_service/core/service_access_type.h"
+#import "ios/chrome/browser/autofill/form_suggestion_view.h"
+#include "ios/chrome/browser/autofill/personal_data_manager_factory.h"
+#import "ios/chrome/browser/ui/autofill/manual_fill/address_mediator.h"
+#import "ios/chrome/browser/ui/autofill/manual_fill/address_view_controller.h"
+#import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.h"
+#import "ios/chrome/browser/ui/settings/autofill/autofill_profile_table_view_controller.h"
+#import "ios/chrome/browser/ui/util/ui_util.h"
+#import "ios/chrome/test/app/chrome_test_util.h"
+#import "ios/chrome/test/earl_grey/chrome_actions.h"
+#import "ios/chrome/test/earl_grey/chrome_earl_grey.h"
+#import "ios/chrome/test/earl_grey/chrome_matchers.h"
+#import "ios/chrome/test/earl_grey/chrome_test_case.h"
+#import "ios/web/public/test/earl_grey/web_view_matchers.h"
+#include "ios/web/public/test/element_selector.h"
+#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "url/gurl.h"
+
+#if !defined(__has_feature) || !__has_feature(objc_arc)
+#error "This file requires ARC support."
+#endif
+
+using chrome_test_util::CancelButton;
+using chrome_test_util::GetOriginalBrowserState;
+using ios::ChromeBrowserState;
+using manual_fill::AccessoryAddressAccessibilityIdentifier;
+using manual_fill::AccessoryKeyboardAccessibilityIdentifier;
+using manual_fill::AddressTableViewAccessibilityIdentifier;
+using manual_fill::ManageAddressAccessibilityIdentifier;
+
+namespace {
+
+constexpr char kFormElementName[] = "name";
+constexpr char kFormElementCity[] = "city";
+
+constexpr char kFormHTMLFile[] = "/profile_form.html";
+
+// Returns a matcher for the scroll view in keyboard accessory bar.
+id<GREYMatcher> FormSuggestionViewMatcher() {
+  return grey_accessibilityID(kFormSuggestionsViewAccessibilityIdentifier);
+}
+
+// Returns a matcher for the profiles icon in the keyboard accessory bar.
+id<GREYMatcher> ProfilesIconMatcher() {
+  return grey_accessibilityID(AccessoryAddressAccessibilityIdentifier);
+}
+
+// Matcher for the Keyboard icon in the accessory bar.
+id<GREYMatcher> KeyboardIconMatcher() {
+  return grey_accessibilityID(AccessoryKeyboardAccessibilityIdentifier);
+}
+
+// Returns a matcher for the profiles table view in manual fallback.
+id<GREYMatcher> ProfilesTableViewMatcher() {
+  return grey_accessibilityID(AddressTableViewAccessibilityIdentifier);
+}
+
+// Returns a matcher for the button to open profile settings in manual
+// fallback.
+id<GREYMatcher> ManageProfilesMatcher() {
+  return grey_accessibilityID(ManageAddressAccessibilityIdentifier);
+}
+
+// Returns the matcher for an enabled cancel button in a navigation bar.
+id<GREYMatcher> NavigationBarCancelMatcher() {
+  return grey_allOf(
+      grey_ancestor(grey_kindOfClass([UINavigationBar class])), CancelButton(),
+      grey_not(grey_accessibilityTrait(UIAccessibilityTraitNotEnabled)), nil);
+}
+
+// Returns a matcher for the profiles settings collection view.
+id<GREYMatcher> ProfileSettingsMatcher() {
+  return grey_accessibilityID(kAutofillProfileTableViewID);
+}
+
+// Returns a matcher for the ProfileTableView window.
+id<GREYMatcher> ProfileTableViewWindowMatcher() {
+  id<GREYMatcher> classMatcher = grey_kindOfClass([UIWindow class]);
+  id<GREYMatcher> parentMatcher = grey_descendant(ProfilesTableViewMatcher());
+  return grey_allOf(classMatcher, parentMatcher, nil);
+}
+
+// Saves an example profile in the store.
+void AddAutofillProfile(autofill::PersonalDataManager* personalDataManager) {
+  using base::test::ios::WaitUntilConditionOrTimeout;
+  using base::test::ios::kWaitForActionTimeout;
+
+  autofill::AutofillProfile profile = autofill::test::GetFullProfile();
+  size_t previousProfileCount = personalDataManager->GetProfiles().size();
+  personalDataManager->AddProfile(profile);
+  GREYAssert(WaitUntilConditionOrTimeout(
+                 kWaitForActionTimeout,
+                 ^bool() {
+                   return previousProfileCount <
+                          personalDataManager->GetProfiles().size();
+                 }),
+             @"Failed to add profile.");
+}
+
+void ClearProfiles(autofill::PersonalDataManager* personalDataManager) {
+  for (const auto* profile : personalDataManager->GetProfiles()) {
+    personalDataManager->RemoveByGUID(profile->guid());
+  }
+  GREYAssert(base::test::ios::WaitUntilConditionOrTimeout(
+                 base::test::ios::kWaitForActionTimeout,
+                 ^bool() {
+                   return 0 == personalDataManager->GetProfiles().size();
+                 }),
+             @"Failed to clean profiles.");
+}
+
+}  // namespace
+
+// Integration Tests for Mannual Fallback Addresses View Controller.
+@interface AddressViewControllerTestCase : ChromeTestCase {
+  // The PersonalDataManager instance for the current browser state.
+  autofill::PersonalDataManager* _personalDataManager;
+}
+
+@end
+
+@implementation AddressViewControllerTestCase
+
++ (void)setUp {
+  [super setUp];
+  // If the previous run was manually stopped then the profile will be in the
+  // store and the test will fail. We clean it here for those cases.
+  ios::ChromeBrowserState* browserState =
+      chrome_test_util::GetOriginalBrowserState();
+  autofill::PersonalDataManager* personalDataManager =
+      autofill::PersonalDataManagerFactory::GetForBrowserState(browserState);
+  ClearProfiles(personalDataManager);
+}
+
+- (void)setUp {
+  [super setUp];
+  ChromeBrowserState* browserState = GetOriginalBrowserState();
+  _personalDataManager =
+      autofill::PersonalDataManagerFactory::GetForBrowserState(browserState);
+  _personalDataManager->SetSyncingForTest(true);
+  // Store one address.
+  AddAutofillProfile(_personalDataManager);
+
+  GREYAssertTrue(self.testServer->Start(), @"Test server failed to start.");
+  const GURL URL = self.testServer->GetURL(kFormHTMLFile);
+  [ChromeEarlGrey loadURL:URL];
+  [ChromeEarlGrey waitForWebStateContainingText:"Profile form"];
+}
+
+- (void)tearDown {
+  ClearProfiles(_personalDataManager);
+  [super tearDown];
+}
+
+// Tests that the addresses view controller appears on screen.
+- (void)testAddressesViewControllerIsPresented {
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementName)];
+
+  // Tap on the addresses icon.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address controller table view is visible.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+}
+
+// Tests that the addresses view controller contains the "Manage Addresses..."
+// action.
+- (void)testAddressesViewControllerContainsManageAddressesAction {
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementName)];
+
+  // Tap on the addresses icon.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address controller contains the "Manage Addresses..." action.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)];
+  [[EarlGrey selectElementWithMatcher:ManageProfilesMatcher()]
+      assertWithMatcher:grey_interactable()];
+}
+
+// Tests that the "Manage Addresses..." action works.
+- (void)testManageAddressesActionOpensAddressSettings {
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementName)];
+
+  // Tap on the addresses icon.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      performAction:grey_tap()];
+
+  // Tap the "Manage Addresses..." action.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)];
+  [[EarlGrey selectElementWithMatcher:ManageProfilesMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address settings opened.
+  [[EarlGrey selectElementWithMatcher:ProfileSettingsMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+}
+
+// Tests that returning from "Manage Addresses..." leaves the icons in the right
+// state.
+- (void)testAddressesButtonStateAfterPresentingManageAddresses {
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementName)];
+
+  // Tap on the addresses icon.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icon.
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_not(grey_userInteractionEnabled())];
+
+  // Tap the "Manage Addresses..." action.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)];
+  [[EarlGrey selectElementWithMatcher:ManageProfilesMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address settings opened.
+  [[EarlGrey selectElementWithMatcher:ProfileSettingsMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+
+  // Tap Cancel Button.
+  [[EarlGrey selectElementWithMatcher:NavigationBarCancelMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address settings closed.
+  [[EarlGrey selectElementWithMatcher:ProfileSettingsMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+
+  // Verify the status of the icons.
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+}
+
+// Tests that the Address View Controller is dismissed when tapping the
+// keyboard icon.
+- (void)testKeyboardIconDismissAddressController {
+  if ([ChromeEarlGrey isIPadIdiom]) {
+    // The keyboard icon is never present in iPads.
+    EARL_GREY_TEST_SKIPPED(@"Test is not applicable for iPad");
+    ;
+  }
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementName)];
+
+  // Tap on the addresses icon.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address controller table view is visible.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+
+  // Tap on the keyboard icon.
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address controller table view and the address icon is NOT
+  // visible.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      assertWithMatcher:grey_notVisible()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_notVisible()];
+}
+
+// Tests that the Address View Controller is dismissed when tapping the outside
+// the popover on iPad.
+- (void)testIPadTappingOutsidePopOverDismissAddressController {
+  if (![ChromeEarlGrey isIPadIdiom]) {
+    EARL_GREY_TEST_SKIPPED(@"Test is not applicable for iPhone");
+  }
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementName)];
+
+  // Tap on the addresses icon.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the address controller table view is visible.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+
+  // Tap on a point outside of the popover.
+  // The way EarlGrey taps doesn't go through the window hierarchy. Because of
+  // this, the tap needs to be done in the same window as the popover.
+  [[EarlGrey selectElementWithMatcher:ProfileTableViewWindowMatcher()]
+      performAction:grey_tapAtPoint(CGPointMake(0, 0))];
+
+  // Verify the address controller table view and the address icon is NOT
+  // visible.
+  [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
+      assertWithMatcher:grey_notVisible()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_notVisible()];
+}
+
+// Tests that the address icon is hidden when no addresses are available.
+- (void)testAddressIconIsNotVisibleWhenAddressStoreEmpty {
+  // Delete the profile that is added on |-setUp|.
+  ClearProfiles(_personalDataManager);
+
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementName)];
+
+  // Wait for the keyboard to appear.
+  [GREYKeyboard waitForKeyboardToAppear];
+
+  // Assert the address icon is not visible.
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_notVisible()];
+
+  // Store one address.
+  AddAutofillProfile(_personalDataManager);
+
+  // Tap another field to trigger form activity.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementCity)];
+
+  // Assert the address icon is visible now.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  // Verify the status of the icons.
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+}
+
+@end
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm
index 9c1b45b2..496839a0 100644
--- a/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm
+++ b/ios/chrome/browser/ui/autofill/manual_fill/card_view_controller_egtest.mm
@@ -15,6 +15,7 @@
 #include "components/autofill/core/browser/personal_data_manager.h"
 #include "components/autofill/core/common/autofill_features.h"
 #include "components/keyed_service/core/service_access_type.h"
+#import "ios/chrome/browser/autofill/form_suggestion_view.h"
 #include "ios/chrome/browser/autofill/personal_data_manager_factory.h"
 #import "ios/chrome/browser/ui/autofill/manual_fill/card_coordinator.h"
 #import "ios/chrome/browser/ui/autofill/manual_fill/card_mediator.h"
@@ -23,6 +24,7 @@
 #import "ios/chrome/browser/ui/settings/autofill/autofill_credit_card_table_view_controller.h"
 #import "ios/chrome/browser/ui/settings/autofill/features.h"
 #import "ios/chrome/browser/ui/util/ui_util.h"
+#include "ios/chrome/grit/ios_strings.h"
 #import "ios/chrome/test/app/chrome_test_util.h"
 #import "ios/chrome/test/earl_grey/chrome_actions.h"
 #import "ios/chrome/test/earl_grey/chrome_earl_grey.h"
@@ -37,6 +39,9 @@
 #error "This file requires ARC support."
 #endif
 
+using chrome_test_util::CancelButton;
+using chrome_test_util::StaticTextWithAccessibilityLabelId;
+
 namespace {
 
 const char kFormElementUsername[] = "username";
@@ -68,6 +73,11 @@
 // PersonalDataManager.
 const NSTimeInterval kPDMMaxDelaySeconds = 10.0;
 
+// Returns a matcher for the scroll view in keyboard accessory bar.
+id<GREYMatcher> FormSuggestionViewMatcher() {
+  return grey_accessibilityID(kFormSuggestionsViewAccessibilityIdentifier);
+}
+
 // Returns a matcher for the credit card icon in the keyboard accessory bar.
 id<GREYMatcher> CreditCardIconMatcher() {
   return grey_accessibilityID(
@@ -103,6 +113,12 @@
   return grey_accessibilityID(kAutofillCreditCardTableViewId);
 }
 
+// Matcher for the not secure website alert.
+id<GREYMatcher> NotSecureWebsiteAlert() {
+  return StaticTextWithAccessibilityLabelId(
+      IDS_IOS_MANUAL_FALLBACK_NOT_SECURE_TITLE);
+}
+
 // Returns a matcher for the CreditCardTableView window.
 id<GREYMatcher> CreditCardTableViewWindowMatcher() {
   id<GREYMatcher> classMatcher = grey_kindOfClass([UIWindow class]);
@@ -110,6 +126,13 @@
   return grey_allOf(classMatcher, parentMatcher, nil);
 }
 
+// Returns the matcher for an enabled cancel button in a navigation bar.
+id<GREYMatcher> NavigationBarCancelMatcher() {
+  return grey_allOf(
+      grey_ancestor(grey_kindOfClass([UINavigationBar class])), CancelButton(),
+      grey_not(grey_accessibilityTrait(UIAccessibilityTraitNotEnabled)), nil);
+}
+
 // Polls the JavaScript query |java_script_condition| until the returned
 // |boolValue| is YES with a kWaitForActionTimeout timeout.
 BOOL WaitForJavaScriptCondition(NSString* java_script_condition) {
@@ -277,6 +300,48 @@
       assertWithMatcher:grey_sufficientlyVisible()];
 }
 
+// Tests that the manual fallback view icon is not highlighted after presenting
+// the manage credit cards view.
+- (void)testCreditCardsButtonStateAfterPresentingCreditCardSettings {
+  [self saveLocalCreditCard];
+
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementUsername)];
+
+  // Scroll to the right.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+
+  // Tap on the credit card icon.
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icon.
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      assertWithMatcher:grey_not(grey_userInteractionEnabled())];
+
+  // Try to scroll.
+  [[EarlGrey selectElementWithMatcher:CreditCardTableViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)];
+
+  // Tap the "Manage Credit Cards..." action.
+  [[EarlGrey selectElementWithMatcher:ManageCreditCardsMatcher()]
+      performAction:grey_tap()];
+
+  // Tap Cancel Button.
+  [[EarlGrey selectElementWithMatcher:NavigationBarCancelMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icons.
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+}
+
 // Tests that the "Add Credit Cards..." action works.
 - (void)testAddCreditCardsActionOpensAddCreditCardSettings {
   base::test::ScopedFeatureList featureList;
@@ -304,6 +369,50 @@
       assertWithMatcher:grey_sufficientlyVisible()];
 }
 
+// Tests that the manual fallback view icon is not highlighted after presenting
+// the add credit card view.
+- (void)testCreditCardsButtonStateAfterPresentingAddCreditCard {
+  base::test::ScopedFeatureList featureList;
+  featureList.InitAndEnableFeature(kSettingsAddPaymentMethod);
+  [self saveLocalCreditCard];
+
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementUsername)];
+
+  // Scroll to the right.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+
+  // Tap on the credit card icon.
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icon.
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      assertWithMatcher:grey_not(grey_userInteractionEnabled())];
+
+  // Try to scroll.
+  [[EarlGrey selectElementWithMatcher:CreditCardTableViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeBottom)];
+
+  // Tap the "Add Credit Cards..." action.
+  [[EarlGrey selectElementWithMatcher:AddCreditCardsMatcher()]
+      performAction:grey_tap()];
+
+  // Tap Cancel Button.
+  [[EarlGrey selectElementWithMatcher:NavigationBarCancelMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icons.
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:CreditCardIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+}
+
 // Tests that the credit card View Controller is dismissed when tapping the
 // keyboard icon.
 - (void)testKeyboardIconDismissCreditCardController {
@@ -458,6 +567,16 @@
                         doesInjectValue:@""];
 }
 
+// Tests an alert is shown warning the user when trying to fill a credit card
+// number in an HTTP form.
+- (void)testCreditCardLocalNumberShowsWarningOnHttp {
+  [self verifyCreditCardButtonWithTitle:kLocalNumberObfuscated
+                        doesInjectValue:@""];
+  // Look for the alert.
+  [[EarlGrey selectElementWithMatcher:NotSecureWebsiteAlert()]
+      assertWithMatcher:grey_not(grey_nil())];
+}
+
 // Tests that credit card cardholder is injected.
 - (void)testCreditCardCardHolderInjectsCorrectly {
   [self verifyCreditCardButtonWithTitle:kLocalCardHolder
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm
index d7fdab96..75d2bca 100644
--- a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm
+++ b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm
@@ -37,6 +37,8 @@
 #error "This file requires ARC support."
 #endif
 
+using manual_fill::AccessoryKeyboardAccessibilityIdentifier;
+
 namespace {
 
 constexpr char kFormElementName[] = "name";
@@ -84,6 +86,11 @@
   return grey_buttonTitle(@"Underworld");
 }
 
+// Matcher for the Keyboard icon in the accessory bar.
+id<GREYMatcher> KeyboardIconMatcher() {
+  return grey_accessibilityID(AccessoryKeyboardAccessibilityIdentifier);
+}
+
 // Saves an example profile in the store.
 void AddAutofillProfile(autofill::PersonalDataManager* personalDataManager) {
   autofill::AutofillProfile profile = autofill::test::GetFullProfile();
@@ -461,6 +468,22 @@
   // Verify the profiles controller table view is not visible.
   [[EarlGrey selectElementWithMatcher:ProfilesTableViewMatcher()]
       assertWithMatcher:grey_notVisible()];
+
+  // Verify the status of the icons.
+  if ([ChromeEarlGrey isIPadIdiom]) {
+    // Hidden on iPad.
+    [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+        assertWithMatcher:grey_notVisible()];
+    [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+        assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+  } else {
+    [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+        assertWithMatcher:grey_sufficientlyVisible()];
+    [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+        assertWithMatcher:grey_userInteractionEnabled()];
+    [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+        assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+  }
 }
 
 // Tests that the input accessory view continues working after a picker is
@@ -515,8 +538,13 @@
   // bar.
   [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
       performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  // Verify the status of the icons.
   [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
       assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
 }
 
 // Same as before but with the keyboard undocked the re-docked.
@@ -586,8 +614,15 @@
 
   // Verify the profiles icon is visible, and therefore also the input accessory
   // bar.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  // Verify the status of the icons.
   [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
       assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
 }
 
 // Test the input accessory bar is present when undocking then docking the
@@ -625,8 +660,15 @@
 
   // Verify the profiles icon is visible, and therefore also the input accessory
   // bar.
+  [[EarlGrey selectElementWithMatcher:FormSuggestionViewMatcher()]
+      performAction:grey_scrollToContentEdge(kGREYContentEdgeRight)];
+  // Verify the status of the icons.
   [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
       assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
 }
 
 // Tests that the manual fallback view is present in incognito.
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm
index acf59df..a895c48 100644
--- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm
+++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.mm
@@ -46,6 +46,16 @@
 // iPad override for the icons' spacing.
 constexpr CGFloat ManualFillIconsIPadSpacing = 15;
 
+// Color to use for the buttons while enabled.
+UIColor* IconActiveTintColor() {
+  return [UIColor colorNamed:kToolbarButtonColor];
+}
+
+// Color to use for the buttons while highlighted.
+UIColor* IconHighlightTintColor() {
+  return [UIColor colorNamed:kBlueColor];
+}
+
 }  // namespace
 
 static NSTimeInterval MFAnimationDuration = 0.2;
@@ -87,7 +97,7 @@
 - (void)resetAnimated:(BOOL)animated {
   [UIView animateWithDuration:animated ? MFAnimationDuration : 0
                    animations:^{
-                     [self resetTintColors];
+                     [self resetIcons];
                    }];
   if (!self.keyboardButton.hidden) {
     [self setKeyboardButtonHidden:YES animated:animated];
@@ -131,7 +141,7 @@
   UIButton* button = [UIButton buttonWithType:UIButtonTypeSystem];
   UIImage* image = [UIImage imageNamed:imageName];
   [button setImage:image forState:UIControlStateNormal];
-  button.tintColor = [self activeTintColor];
+  button.tintColor = IconActiveTintColor();
   button.translatesAutoresizingMaskIntoConstraints = NO;
   [button addTarget:self
                 action:selector
@@ -220,16 +230,15 @@
   ]];
 }
 
-// Resets the colors of all the icons to the active color.
-- (void)resetTintColors {
-  UIColor* activeTintColor = [self activeTintColor];
-  [self.accountButton setTintColor:activeTintColor];
-  [self.passwordButton setTintColor:activeTintColor];
-  [self.cardsButton setTintColor:activeTintColor];
-}
+// Resets the icon's color and userInteractionEnabled.
+- (void)resetIcons {
+  self.accountButton.userInteractionEnabled = YES;
+  self.cardsButton.userInteractionEnabled = YES;
+  self.passwordButton.userInteractionEnabled = YES;
 
-- (UIColor*)activeTintColor {
-  return [UIColor colorNamed:kToolbarButtonColor];
+  [self.accountButton setTintColor:IconActiveTintColor()];
+  [self.passwordButton setTintColor:IconActiveTintColor()];
+  [self.cardsButton setTintColor:IconActiveTintColor()];
 }
 
 - (void)setKeyboardButtonHidden:(BOOL)hidden animated:(BOOL)animated {
@@ -258,24 +267,27 @@
 - (void)passwordButtonPressed:(UIButton*)sender {
   base::RecordAction(base::UserMetricsAction("ManualFallback_OpenPassword"));
   [self setKeyboardButtonHidden:NO animated:YES];
-  [self resetTintColors];
-  [self.passwordButton setTintColor:[UIColor colorNamed:kBlueColor]];
+  [self resetIcons];
+  self.passwordButton.userInteractionEnabled = NO;
+  self.passwordButton.tintColor = IconHighlightTintColor();
   [self.delegate passwordButtonPressed:sender];
 }
 
 - (void)cardButtonPressed:(UIButton*)sender {
   base::RecordAction(base::UserMetricsAction("ManualFallback_OpenCreditCard"));
   [self setKeyboardButtonHidden:NO animated:YES];
-  [self resetTintColors];
-  [self.cardsButton setTintColor:[UIColor colorNamed:kBlueColor]];
+  [self resetIcons];
+  self.cardsButton.userInteractionEnabled = NO;
+  self.cardsButton.tintColor = IconHighlightTintColor();
   [self.delegate cardButtonPressed:sender];
 }
 
 - (void)accountButtonPressed:(UIButton*)sender {
   base::RecordAction(base::UserMetricsAction("ManualFallback_OpenProfile"));
   [self setKeyboardButtonHidden:NO animated:YES];
-  [self resetTintColors];
-  [self.accountButton setTintColor:[UIColor colorNamed:kBlueColor]];
+  [self resetIcons];
+  self.accountButton.userInteractionEnabled = NO;
+  self.accountButton.tintColor = IconHighlightTintColor();
   [self.delegate accountButtonPressed:sender];
 }
 
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.h b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.h
index bdbe748..4cb96dd 100644
--- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.h
+++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.h
@@ -15,6 +15,8 @@
 @protocol ManualFillContentInjector;
 @class ManualFillCredential;
 
+extern NSString* const kMaskedPasswordTitle;
+
 // Wrapper to show password cells in a ChromeTableViewController.
 @interface ManualFillCredentialItem : TableViewItem
 
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm
index 4f17b04c..46cc1d3 100644
--- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm
+++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.mm
@@ -23,6 +23,8 @@
 #error "This file requires ARC support."
 #endif
 
+NSString* const kMaskedPasswordTitle = @"••••••••";
+
 @interface ManualFillCredentialItem ()
 
 // The credential for this item.
@@ -210,7 +212,8 @@
   [verticalLeadViews addObject:self.usernameButton];
 
   if (credential.password.length) {
-    [self.passwordButton setTitle:@"••••••••" forState:UIControlStateNormal];
+    [self.passwordButton setTitle:kMaskedPasswordTitle
+                         forState:UIControlStateNormal];
     self.passwordButton.accessibilityLabel =
         l10n_util::GetNSString(IDS_IOS_SETTINGS_PASSWORD_HIDDEN_LABEL);
     [verticalLeadViews addObject:self.passwordButton];
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/password_view_controller_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/password_view_controller_egtest.mm
index a4cdfa0..16509a2 100644
--- a/ios/chrome/browser/ui/autofill/manual_fill/password_view_controller_egtest.mm
+++ b/ios/chrome/browser/ui/autofill/manual_fill/password_view_controller_egtest.mm
@@ -18,10 +18,12 @@
 #include "ios/chrome/browser/passwords/ios_chrome_password_store_factory.h"
 #import "ios/chrome/browser/ui/autofill/manual_fill/all_password_coordinator.h"
 #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_accessory_view_controller.h"
+#import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_cell.h"
 #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_mediator.h"
 #import "ios/chrome/browser/ui/autofill/manual_fill/password_view_controller.h"
 #import "ios/chrome/browser/ui/settings/password/passwords_table_view_controller.h"
 #import "ios/chrome/browser/ui/util/ui_util.h"
+#include "ios/chrome/grit/ios_strings.h"
 #import "ios/chrome/test/app/chrome_test_util.h"
 #import "ios/chrome/test/earl_grey/chrome_actions.h"
 #import "ios/chrome/test/earl_grey/chrome_earl_grey.h"
@@ -36,6 +38,10 @@
 #error "This file requires ARC support."
 #endif
 
+using chrome_test_util::CancelButton;
+using chrome_test_util::NavigationBarDoneButton;
+using chrome_test_util::StaticTextWithAccessibilityLabelId;
+
 namespace {
 
 const char kFormElementUsername[] = "username";
@@ -93,6 +99,11 @@
   return grey_buttonTitle(base::SysUTF8ToNSString(kExampleUsername));
 }
 
+// Returns a matcher for the example password in the list.
+id<GREYMatcher> PasswordButtonMatcher() {
+  return grey_buttonTitle(kMaskedPasswordTitle);
+}
+
 // Returns a matcher for the password settings collection view.
 id<GREYMatcher> PasswordSettingsMatcher() {
   return grey_accessibilityID(kPasswordsTableViewId);
@@ -103,6 +114,12 @@
   return grey_accessibilityID(kPasswordsSearchBarId);
 }
 
+// Matcher for the not secure website alert.
+id<GREYMatcher> NotSecureWebsiteAlert() {
+  return StaticTextWithAccessibilityLabelId(
+      IDS_IOS_MANUAL_FALLBACK_NOT_SECURE_TITLE);
+}
+
 // Returns a matcher for the PasswordTableView window.
 id<GREYMatcher> PasswordTableViewWindowMatcher() {
   id<GREYMatcher> classMatcher = grey_kindOfClass([UIWindow class]);
@@ -110,6 +127,13 @@
   return grey_allOf(classMatcher, parentMatcher, nil);
 }
 
+// Returns the matcher for an enabled cancel button in a navigation bar.
+id<GREYMatcher> NavigationBarCancelMatcher() {
+  return grey_allOf(
+      grey_ancestor(grey_kindOfClass([UINavigationBar class])), CancelButton(),
+      grey_not(grey_accessibilityTrait(UIAccessibilityTraitNotEnabled)), nil);
+}
+
 // Gets the current password store.
 scoped_refptr<password_manager::PasswordStore> GetPasswordStore() {
   // ServiceAccessType governs behaviour in Incognito: only modifications with
@@ -303,6 +327,42 @@
       assertWithMatcher:grey_sufficientlyVisible()];
 }
 
+// Tests that returning from "Manage Passwords..." leaves the icons in the right
+// state.
+- (void)testPasswordsButtonStateAfterPresentingManagePasswords {
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementUsername)];
+
+  // Tap on the passwords icon.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icon.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_not(grey_userInteractionEnabled())];
+
+  // Tap the "Manage Passwords..." action.
+  [[EarlGrey selectElementWithMatcher:ManagePasswordsMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the password settings opened.
+  [[EarlGrey selectElementWithMatcher:PasswordSettingsMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+
+  // Tap Cancel Button.
+  [[EarlGrey selectElementWithMatcher:NavigationBarCancelMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icons.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+}
+
 // Tests that the "Use Other Password..." action works.
 - (void)testUseOtherPasswordActionOpens {
   // Bring up the keyboard.
@@ -322,6 +382,42 @@
       assertWithMatcher:grey_sufficientlyVisible()];
 }
 
+// Tests that returning from "Use Other Password..." leaves the icons in the
+// right state.
+- (void)testPasswordsButtonStateAfterPresentingUseOtherPassword {
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementUsername)];
+
+  // Tap on the passwords icon.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icon.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_not(grey_userInteractionEnabled())];
+
+  // Tap the "Manage Passwords..." action.
+  [[EarlGrey selectElementWithMatcher:OtherPasswordsMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the use other passwords opened.
+  [[EarlGrey selectElementWithMatcher:OtherPasswordsDismissMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+
+  // Tap Cancel Button.
+  [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()]
+      performAction:grey_tap()];
+
+  // Verify the status of the icons.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
+  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
+      assertWithMatcher:grey_not(grey_sufficientlyVisible())];
+}
+
 // Tests that the Password View Controller is not present when presenting UI.
 - (void)testPasswordControllerPauses {
   // Bring up the keyboard.
@@ -476,12 +572,15 @@
   [[EarlGrey selectElementWithMatcher:PasswordTableViewWindowMatcher()]
       performAction:grey_tapAtPoint(CGPointMake(0, 0))];
 
-  // Verify the password controller table view and the password icon is NOT
-  // visible.
+  // Verify the password controller table view is not visible and the password
+  // icon is visible.
   [[EarlGrey selectElementWithMatcher:PasswordTableViewMatcher()]
       assertWithMatcher:grey_notVisible()];
-  [[EarlGrey selectElementWithMatcher:KeyboardIconMatcher()]
-      assertWithMatcher:grey_notVisible()];
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_interactable()];
+  // Verify the interaction status of the password icon.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      assertWithMatcher:grey_userInteractionEnabled()];
 }
 
 // Tests that the Password View Controller is dismissed when tapping the
@@ -605,6 +704,36 @@
   XCTAssertTrue(WaitForJavaScriptCondition(javaScriptCondition));
 }
 
+// Tests that an alert is shown when trying to fill a password in an unsecure
+// field.
+- (void)testPasswordControllerPresentsUnsecureAlert {
+  const GURL URL = self.testServer->GetURL(kFormHTMLFile);
+  SaveLocalPasswordForm(URL);
+
+  // Bring up the keyboard.
+  [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()]
+      performAction:chrome_test_util::TapWebElement(kFormElementUsername)];
+
+  // Wait for the accessory icon to appear.
+  [GREYKeyboard waitForKeyboardToAppear];
+
+  // Tap on the passwords icon.
+  [[EarlGrey selectElementWithMatcher:PasswordIconMatcher()]
+      performAction:grey_tap()];
+
+  // Verify the password controller table view is visible.
+  [[EarlGrey selectElementWithMatcher:PasswordTableViewMatcher()]
+      assertWithMatcher:grey_sufficientlyVisible()];
+
+  // Select a password.
+  [[EarlGrey selectElementWithMatcher:PasswordButtonMatcher()]
+      performAction:grey_tap()];
+
+  // Look for the alert.
+  [[EarlGrey selectElementWithMatcher:NotSecureWebsiteAlert()]
+      assertWithMatcher:grey_not(grey_nil())];
+}
+
 // Tests that the password icon is hidden when no passwords are available.
 - (void)testPasswordIconIsNotVisibleWhenPasswordStoreEmpty {
   ClearPasswordStore();
diff --git a/ios/chrome/browser/ui/browser_view/browser_coordinator.mm b/ios/chrome/browser/ui/browser_view/browser_coordinator.mm
index 864cdfcd..8762be02 100644
--- a/ios/chrome/browser/ui/browser_view/browser_coordinator.mm
+++ b/ios/chrome/browser/ui/browser_view/browser_coordinator.mm
@@ -439,6 +439,7 @@
 }
 
 - (void)showAddCreditCard {
+  [self.formInputAccessoryCoordinator reset];
   [self.addCreditCardCoordinator start];
 }
 
diff --git a/ios/chrome/browser/ui/main/scene_controller.h b/ios/chrome/browser/ui/main/scene_controller.h
index ad38cbe..6b2706e5 100644
--- a/ios/chrome/browser/ui/main/scene_controller.h
+++ b/ios/chrome/browser/ui/main/scene_controller.h
@@ -7,8 +7,18 @@
 
 #import <UIKit/UIKit.h>
 
+#import "ios/chrome/browser/ui/main/scene_state.h"
+
 // The controller object for a scene. Reacts to scene state changes.
-@interface SceneController : NSObject
+@interface SceneController : NSObject <SceneStateObserver>
+
+- (instancetype)init NS_UNAVAILABLE;
+- (instancetype)initWithSceneState:(SceneState*)sceneState
+    NS_DESIGNATED_INITIALIZER;
+
+// The state of the scene controlled by this object.
+@property(nonatomic, weak, readonly) SceneState* sceneState;
+
 @end
 
 #endif  // IOS_CHROME_BROWSER_UI_MAIN_SCENE_CONTROLLER_H_
diff --git a/ios/chrome/browser/ui/main/scene_controller.mm b/ios/chrome/browser/ui/main/scene_controller.mm
index bf0d3c1..9430b5eb 100644
--- a/ios/chrome/browser/ui/main/scene_controller.mm
+++ b/ios/chrome/browser/ui/main/scene_controller.mm
@@ -10,4 +10,19 @@
 
 @implementation SceneController
 
+- (instancetype)initWithSceneState:(SceneState*)sceneState {
+  self = [super init];
+  if (self) {
+    _sceneState = sceneState;
+    [_sceneState addObserver:self];
+  }
+  return self;
+}
+
+#pragma mark - SceneStateObserver
+
+- (void)sceneState:(SceneState*)sceneState
+    transitionedToActivationLevel:(SceneActivationLevel)level {
+}
+
 @end
diff --git a/ios/chrome/browser/ui/main/scene_controller_unittest.mm b/ios/chrome/browser/ui/main/scene_controller_unittest.mm
index e7a9292..d24065d 100644
--- a/ios/chrome/browser/ui/main/scene_controller_unittest.mm
+++ b/ios/chrome/browser/ui/main/scene_controller_unittest.mm
@@ -16,8 +16,9 @@
 class SceneControllerTest : public PlatformTest {
  protected:
   SceneControllerTest() {
-    scene_controller_ = [[SceneController alloc] init];
     scene_state_ = [[SceneState alloc] init];
+    scene_controller_ =
+        [[SceneController alloc] initWithSceneState:scene_state_];
   }
 
   SceneController* scene_controller_;
diff --git a/ios/chrome/browser/ui/main/scene_delegate.h b/ios/chrome/browser/ui/main/scene_delegate.h
index 0370ba9..02d635526 100644
--- a/ios/chrome/browser/ui/main/scene_delegate.h
+++ b/ios/chrome/browser/ui/main/scene_delegate.h
@@ -7,6 +7,7 @@
 
 #import <UIKit/UIKit.h>
 
+#import "ios/chrome/browser/ui/main/scene_controller.h"
 #import "ios/chrome/browser/ui/main/scene_state.h"
 
 // An object acting as a scene delegate for UIKit. Updates the scene state.
@@ -17,6 +18,9 @@
 // The object that holds the state of the scene associated with this delegate.
 @property(nonatomic, strong) SceneState* sceneState;
 
+// The controller created and owned by this object.
+@property(nonatomic, strong) SceneController* sceneController;
+
 @end
 
 #endif  // IOS_CHROME_BROWSER_UI_MAIN_SCENE_DELEGATE_H_
diff --git a/ios/chrome/browser/ui/main/scene_delegate.mm b/ios/chrome/browser/ui/main/scene_delegate.mm
index ad51cc2acc..76570750 100644
--- a/ios/chrome/browser/ui/main/scene_delegate.mm
+++ b/ios/chrome/browser/ui/main/scene_delegate.mm
@@ -13,6 +13,7 @@
 - (SceneState*)sceneState {
   if (!_sceneState) {
     _sceneState = [[SceneState alloc] init];
+    _sceneController = [[SceneController alloc] initWithSceneState:_sceneState];
   }
   return _sceneState;
 }
diff --git a/ios/chrome/browser/ui/main/scene_state.h b/ios/chrome/browser/ui/main/scene_state.h
index 2d41fe9..d417eda 100644
--- a/ios/chrome/browser/ui/main/scene_state.h
+++ b/ios/chrome/browser/ui/main/scene_state.h
@@ -7,6 +7,8 @@
 
 #import <UIKit/UIKit.h>
 
+@class SceneState;
+
 // Describes the possible scene states.
 // This is an iOS 12 compatible version of UISceneActivationState enum.
 typedef NS_ENUM(NSUInteger, SceneActivationLevel) {
@@ -23,6 +25,17 @@
   SceneActivationLevelForegroundActive
 };
 
+@protocol SceneStateObserver <NSObject>
+
+@optional
+
+// Called whenever the scene state transitions between different activity
+// states.
+- (void)sceneState:(SceneState*)sceneState
+    transitionedToActivationLevel:(SceneActivationLevel)level;
+
+@end
+
 // An object containing the state of a UIWindowScene. One state object
 // corresponds to one scene.
 @interface SceneState : NSObject
@@ -33,6 +46,13 @@
 // Window for the associated scene, if any.
 @property(nonatomic, weak) UIWindow* window;
 
+// Adds an observer to this scene state. The observers will be notified about
+// scene state changes per SceneStateObserver protocol.
+- (void)addObserver:(id<SceneStateObserver>)observer;
+// Removes the observer. It's safe to call this at any time, including from
+// SceneStateObserver callbacks.
+- (void)removeObserver:(id<SceneStateObserver>)observer;
+
 @end
 
 #endif  // IOS_CHROME_BROWSER_UI_MAIN_SCENE_STATE_H_
diff --git a/ios/chrome/browser/ui/main/scene_state.mm b/ios/chrome/browser/ui/main/scene_state.mm
index 61d0e68..286a76231 100644
--- a/ios/chrome/browser/ui/main/scene_state.mm
+++ b/ios/chrome/browser/ui/main/scene_state.mm
@@ -4,9 +4,85 @@
 
 #import "ios/chrome/browser/ui/main/scene_state.h"
 
+#import "base/ios/crb_protocol_observers.h"
+
 #if !defined(__has_feature) || !__has_feature(objc_arc)
 #error "This file requires ARC support."
 #endif
 
+@interface SceneStateObserverList : CRBProtocolObservers <SceneStateObserver>
+@end
+
+@implementation SceneStateObserverList
+@end
+
+#pragma mark - SceneState
+
+@interface SceneState ()
+
+// Container for this object's observers.
+@property(nonatomic, strong) SceneStateObserverList* observers;
+
+@end
+
 @implementation SceneState
+
+- (instancetype)init {
+  self = [super init];
+  if (self) {
+    _observers = [SceneStateObserverList
+        observersWithProtocol:@protocol(SceneStateObserver)];
+  }
+  return self;
+}
+
+#pragma mark - public
+
+- (void)addObserver:(id<SceneStateObserver>)observer {
+  [self.observers addObserver:observer];
+}
+
+- (void)removeObserver:(id<SceneStateObserver>)observer {
+  [self.observers removeObserver:observer];
+}
+
+#pragma mark - Setters & Getters.
+
+- (void)setActivationLevel:(SceneActivationLevel)newLevel {
+  if (_activationLevel == newLevel) {
+    return;
+  }
+  _activationLevel = newLevel;
+
+  [self.observers sceneState:self transitionedToActivationLevel:newLevel];
+}
+
+#pragma mark - debug
+
+- (NSString*)description {
+  NSString* activityString = nil;
+  switch (self.activationLevel) {
+    case SceneActivationLevelUnattached: {
+      activityString = @"Unattached";
+      break;
+    }
+
+    case SceneActivationLevelBackground: {
+      activityString = @"Background";
+      break;
+    }
+    case SceneActivationLevelForegroundInactive: {
+      activityString = @"Foreground, Inactive";
+      break;
+    }
+    case SceneActivationLevelForegroundActive: {
+      activityString = @"Active";
+      break;
+    }
+  }
+
+  return
+      [NSString stringWithFormat:@"SceneState %p (%@)", self, activityString];
+}
+
 @end
diff --git a/ios/web/navigation/wk_navigation_util.mm b/ios/web/navigation/wk_navigation_util.mm
index 9412fc5..e132fc9 100644
--- a/ios/web/navigation/wk_navigation_util.mm
+++ b/ios/web/navigation/wk_navigation_util.mm
@@ -60,7 +60,7 @@
     return last_committed_item_index;
   }
 
-  if (items.size() - last_committed_item_index < kMaxSessionSize / 2) {
+  if (items.size() - last_committed_item_index <= kMaxSessionSize / 2) {
     // Items which are the furthest to |last_committed_item_index| are located
     // on the left side of the vector. Trim those.
     *begin = items.end() - kMaxSessionSize;
diff --git a/ios/web/navigation/wk_navigation_util_unittest.mm b/ios/web/navigation/wk_navigation_util_unittest.mm
index b92d6bb..56d6b785 100644
--- a/ios/web/navigation/wk_navigation_util_unittest.mm
+++ b/ios/web/navigation/wk_navigation_util_unittest.mm
@@ -92,6 +92,33 @@
             session_json);
 }
 
+// In the past the math within CreateRestoreSessionUrl has had some edge case
+// crashes.  Ensure that nothing crashes.
+TEST_F(WKNavigationUtilTest, CreateRestoreSessionBruteForce) {
+  std::vector<std::unique_ptr<NavigationItem>> items;
+  int first_index = 0;
+  GURL restore_session_url;
+  for (int num_items = 70; num_items < 80; num_items++) {
+    std::vector<std::unique_ptr<NavigationItem>> items;
+    CreateTestNavigationItems(num_items, items);
+    for (int last_committed_index = 0; last_committed_index < num_items;
+         last_committed_index++) {
+      CreateRestoreSessionUrl(last_committed_index, items, &restore_session_url,
+                              &first_index);
+      // Extract session JSON from restoration URL.
+      base::JSONReader::ValueWithError value_with_error =
+          ExtractSessionDict(restore_session_url);
+
+      base::Value* urls_value = value_with_error.value->FindKey("urls");
+      if (num_items > kMaxSessionSize) {
+        ASSERT_EQ(kMaxSessionSize, (int)urls_value->GetList().size());
+      } else {
+        ASSERT_EQ(num_items, (int)urls_value->GetList().size());
+      }
+    }
+  }
+}
+
 // Verifies that large session can be stored in NSURL. GURL is converted to
 // NSURL, because NSURL is passed to WKWebView during the session restoration.
 TEST_F(WKNavigationUtilTest, CreateRestoreSessionUrlForLargeSession) {
diff --git a/ios/web_view/internal/signin/ios_web_view_signin_client.h b/ios/web_view/internal/signin/ios_web_view_signin_client.h
index c1410b4..e3bcd766 100644
--- a/ios/web_view/internal/signin/ios_web_view_signin_client.h
+++ b/ios/web_view/internal/signin/ios_web_view_signin_client.h
@@ -36,7 +36,6 @@
   void Shutdown() override;
 
   // SigninClient implementation.
-  std::string GetProductVersion() override;
   PrefService* GetPrefs() override;
   scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() override;
   network::mojom::CookieManager* GetCookieManager() override;
diff --git a/ios/web_view/internal/signin/ios_web_view_signin_client.mm b/ios/web_view/internal/signin/ios_web_view_signin_client.mm
index 995645d5..186da039 100644
--- a/ios/web_view/internal/signin/ios_web_view_signin_client.mm
+++ b/ios/web_view/internal/signin/ios_web_view_signin_client.mm
@@ -33,11 +33,6 @@
   network_callback_helper_.reset();
 }
 
-std::string IOSWebViewSigninClient::GetProductVersion() {
-  // TODO(crbug.com/768689): Implement this method with appropriate values.
-  return "";
-}
-
 PrefService* IOSWebViewSigninClient::GetPrefs() {
   return pref_service_;
 }
diff --git a/media/audio/BUILD.gn b/media/audio/BUILD.gn
index 35fd1d7d..b27ebee 100644
--- a/media/audio/BUILD.gn
+++ b/media/audio/BUILD.gn
@@ -295,7 +295,10 @@
       "fuchsia/audio_output_stream_fuchsia.cc",
       "fuchsia/audio_output_stream_fuchsia.h",
     ]
-    deps += [ "//third_party/fuchsia-sdk/sdk:media" ]
+    deps += [
+      "//third_party/fuchsia-sdk/sdk:media",
+      "//third_party/fuchsia-sdk/sdk:sys_cpp",
+    ]
   }
 
   configs += [ "//build/config/compiler:no_size_t_to_int_warning" ]
diff --git a/media/audio/fuchsia/audio_output_stream_fuchsia.cc b/media/audio/fuchsia/audio_output_stream_fuchsia.cc
index cbcda51b..db49de6b 100644
--- a/media/audio/fuchsia/audio_output_stream_fuchsia.cc
+++ b/media/audio/fuchsia/audio_output_stream_fuchsia.cc
@@ -4,10 +4,11 @@
 
 #include "media/audio/fuchsia/audio_output_stream_fuchsia.h"
 
+#include <lib/sys/cpp/component_context.h>
 #include <zircon/syscalls.h>
 
 #include "base/bind.h"
-#include "base/fuchsia/service_directory_client.h"
+#include "base/fuchsia/default_context.h"
 #include "base/memory/writable_shared_memory_region.h"
 #include "media/audio/fuchsia/audio_manager_fuchsia.h"
 #include "media/base/audio_sample_types.h"
@@ -37,8 +38,9 @@
 
   // Connect |audio_renderer_| to the audio service.
   fuchsia::media::AudioPtr audio_server =
-      base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-          ->ConnectToService<fuchsia::media::Audio>();
+      base::fuchsia::ComponentContextForCurrentProcess()
+          ->svc()
+          ->Connect<fuchsia::media::Audio>();
   audio_server->CreateAudioRenderer(audio_renderer_.NewRequest());
   audio_renderer_.set_error_handler(
       fit::bind_member(this, &AudioOutputStreamFuchsia::OnRendererError));
diff --git a/media/learning/common/BUILD.gn b/media/learning/common/BUILD.gn
index 20966d1..a8116637 100644
--- a/media/learning/common/BUILD.gn
+++ b/media/learning/common/BUILD.gn
@@ -37,6 +37,8 @@
     "learning_task.cc",
     "learning_task.h",
     "learning_task_controller.h",
+    "media_learning_tasks.cc",
+    "media_learning_tasks.h",
     "value.cc",
     "value.h",
   ]
@@ -53,6 +55,7 @@
     "experiment_helper_unittest.cc",
     "feature_dictionary_unittest.cc",
     "labelled_example_unittest.cc",
+    "media_learning_tasks_unittest.cc",
     "value_unittest.cc",
   ]
 
diff --git a/media/learning/common/media_learning_tasks.cc b/media/learning/common/media_learning_tasks.cc
new file mode 100644
index 0000000..d11a57e
--- /dev/null
+++ b/media/learning/common/media_learning_tasks.cc
@@ -0,0 +1,35 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "media/learning/common/media_learning_tasks.h"
+
+namespace media {
+namespace learning {
+
+static const LearningTask& GetWillPlayTask() {
+  static LearningTask task_;
+  if (!task_.feature_descriptions.size()) {
+    task_.name = "MediaLearningWillPlay";
+    // TODO(liberato): fill in the rest here, once we have the features picked.
+  }
+
+  return task_;
+}
+
+// static
+const LearningTask& MediaLearningTasks::Get(Id id) {
+  switch (id) {
+    case Id::kWillPlay:
+      return GetWillPlayTask();
+  }
+}
+
+// static
+void MediaLearningTasks::Register(
+    base::RepeatingCallback<void(const LearningTask&)> cb) {
+  cb.Run(Get(Id::kWillPlay));
+}
+
+}  // namespace learning
+}  // namespace media
diff --git a/media/learning/common/media_learning_tasks.h b/media/learning/common/media_learning_tasks.h
new file mode 100644
index 0000000..e5deb0f
--- /dev/null
+++ b/media/learning/common/media_learning_tasks.h
@@ -0,0 +1,41 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef MEDIA_LEARNING_COMMON_MEDIA_LEARNING_TASKS_H_
+#define MEDIA_LEARNING_COMMON_MEDIA_LEARNING_TASKS_H_
+
+#include "base/callback.h"
+#include "base/component_export.h"
+#include "media/learning/common/learning_task.h"
+
+namespace media {
+namespace learning {
+
+// All learning experiments for media/ .
+// TODO(liberato): This should be in media/ somewhere, since the learning
+// framework doesn't care about it.  For now, this is simpler to make deps
+// easier to handle.
+class COMPONENT_EXPORT(LEARNING_COMMON) MediaLearningTasks {
+ public:
+  // Ids for each LearningTask.
+  enum class Id {
+    kWillPlay,
+  };
+
+  // Return the LearningTask for |id|.
+  static const learning::LearningTask& Get(Id id);
+
+  // Register all tasks by calling |registration_cb| repeatedly.
+  static void Register(
+      base::RepeatingCallback<void(const learning::LearningTask&)>
+          registration_cb);
+
+ private:
+  MediaLearningTasks() = delete;
+};
+
+}  // namespace learning
+}  // namespace media
+
+#endif  // MEDIA_LEARNING_COMMON_MEDIA_LEARNING_TASKS_H_
diff --git a/media/learning/common/media_learning_tasks_unittest.cc b/media/learning/common/media_learning_tasks_unittest.cc
new file mode 100644
index 0000000..727893d1
--- /dev/null
+++ b/media/learning/common/media_learning_tasks_unittest.cc
@@ -0,0 +1,37 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "media/learning/common/media_learning_tasks.h"
+
+#include <memory>
+
+#include "base/bind.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+using testing::_;
+
+namespace media {
+namespace learning {
+
+class MediaLearningTasksTest : public testing::Test {};
+
+TEST_F(MediaLearningTasksTest, WillPlayTask) {
+  LearningTask task =
+      MediaLearningTasks::Get(MediaLearningTasks::Id::kWillPlay);
+  // Make sure the name is correct, mostly to reduce cut-and-paste errors.
+  EXPECT_EQ(task.name, "MediaLearningWillPlay");
+}
+
+TEST_F(MediaLearningTasksTest, EnumeratesAllTasks) {
+  int count = 0;
+  auto cb = base::BindRepeating(
+      [](int* count, const LearningTask& task) { (*count)++; },
+      base::Unretained(&count));
+  MediaLearningTasks::Register(std::move(cb));
+  EXPECT_EQ(count, 1);
+}
+
+}  // namespace learning
+}  // namespace media
diff --git a/net/BUILD.gn b/net/BUILD.gn
index 43b1f01..6050ff7a 100644
--- a/net/BUILD.gn
+++ b/net/BUILD.gn
@@ -2325,6 +2325,7 @@
       public_deps += [
         "//third_party/fuchsia-sdk/sdk:hardware_ethernet",
         "//third_party/fuchsia-sdk/sdk:netstack",
+        "//third_party/fuchsia-sdk/sdk:sys_cpp",
       ]
     }
 
diff --git a/net/base/network_change_notifier_fuchsia.cc b/net/base/network_change_notifier_fuchsia.cc
index ddeae7d0..6a7398a9 100644
--- a/net/base/network_change_notifier_fuchsia.cc
+++ b/net/base/network_change_notifier_fuchsia.cc
@@ -4,14 +4,15 @@
 
 #include "net/base/network_change_notifier_fuchsia.h"
 
+#include <lib/sys/cpp/component_context.h>
 #include <algorithm>
 #include <string>
 #include <utility>
 #include <vector>
 
 #include "base/bind.h"
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 #include "base/optional.h"
 #include "base/run_loop.h"
 #include "net/base/network_interfaces.h"
@@ -22,8 +23,9 @@
 NetworkChangeNotifierFuchsia::NetworkChangeNotifierFuchsia(
     uint32_t required_features)
     : NetworkChangeNotifierFuchsia(
-          base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-              ->ConnectToService<fuchsia::netstack::Netstack>(),
+          base::fuchsia::ComponentContextForCurrentProcess()
+              ->svc()
+              ->Connect<fuchsia::netstack::Netstack>(),
           required_features) {}
 
 NetworkChangeNotifierFuchsia::NetworkChangeNotifierFuchsia(
diff --git a/net/base/network_interfaces_fuchsia.cc b/net/base/network_interfaces_fuchsia.cc
index f98a911..955ffc7 100644
--- a/net/base/network_interfaces_fuchsia.cc
+++ b/net/base/network_interfaces_fuchsia.cc
@@ -7,13 +7,14 @@
 #include <fuchsia/hardware/ethernet/cpp/fidl.h>
 #include <fuchsia/net/cpp/fidl.h>
 #include <fuchsia/netstack/cpp/fidl.h>
+#include <lib/sys/cpp/component_context.h>
 
 #include <string>
 #include <utility>
 
 #include "base/format_macros.h"
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 #include "base/strings/stringprintf.h"
 #include "net/base/ip_endpoint.h"
 #include "net/base/network_interfaces.h"
@@ -102,9 +103,9 @@
 bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
   DCHECK(networks);
 
-  fuchsia::netstack::NetstackSyncPtr netstack =
-      base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-          ->ConnectToServiceSync<fuchsia::netstack::Netstack>();
+  fuchsia::netstack::NetstackSyncPtr netstack;
+  base::fuchsia::ComponentContextForCurrentProcess()->svc()->Connect(
+      netstack.NewRequest());
 
   // TODO(kmarshall): Use NetworkChangeNotifier's cached interface list.
   std::vector<fuchsia::netstack::NetInterface> interfaces;
diff --git a/net/cookies/canonical_cookie.cc b/net/cookies/canonical_cookie.cc
index e0de0172..e5b0492 100644
--- a/net/cookies/canonical_cookie.cc
+++ b/net/cookies/canonical_cookie.cc
@@ -434,6 +434,16 @@
     status.AddExclusionReason(CookieInclusionStatus::EXCLUDE_NOT_ON_PATH);
   // Don't include same-site cookies for cross-site requests.
   CookieEffectiveSameSite effective_same_site = GetEffectiveSameSite();
+  // Log the effective SameSite mode that is applied to the cookie on this
+  // request, if its SameSite was not specified.
+  if (SameSite() == CookieSameSite::UNSPECIFIED) {
+    UMA_HISTOGRAM_ENUMERATION("Cookie.SameSiteUnspecifiedEffective",
+                              effective_same_site,
+                              CookieEffectiveSameSite::COUNT);
+  }
+  UMA_HISTOGRAM_ENUMERATION("Cookie.RequestSameSiteContext",
+                            options.same_site_cookie_context(),
+                            CookieOptions::SameSiteCookieContext::COUNT);
   switch (effective_same_site) {
     case CookieEffectiveSameSite::STRICT_MODE:
       if (options.same_site_cookie_context() <
diff --git a/net/cookies/cookie_constants.h b/net/cookies/cookie_constants.h
index 3569b43..f0545bfc 100644
--- a/net/cookies/cookie_constants.h
+++ b/net/cookies/cookie_constants.h
@@ -39,6 +39,7 @@
 
 // These are the enforcement modes that may be applied to a cookie when deciding
 // inclusion/exclusion. They mostly correspond to CookieSameSite values.
+// Keep in sync with enums.xml.
 enum class CookieEffectiveSameSite {
   NO_RESTRICTION = 0,
   LAX_MODE = 1,
diff --git a/net/cookies/cookie_options.h b/net/cookies/cookie_options.h
index 9ae0b3b0..46c92f4 100644
--- a/net/cookies/cookie_options.h
+++ b/net/cookies/cookie_options.h
@@ -18,12 +18,16 @@
  public:
   // Relation between the cookie and the navigational environment.
   // Ordered from least to most trusted environment.
+  // Don't renumber, used in histograms.
   enum class SameSiteCookieContext {
-    CROSS_SITE,
+    CROSS_SITE = 0,
     // Same rules as lax but the http method is unsafe.
-    SAME_SITE_LAX_METHOD_UNSAFE,
-    SAME_SITE_LAX,
-    SAME_SITE_STRICT
+    SAME_SITE_LAX_METHOD_UNSAFE = 1,
+    SAME_SITE_LAX = 2,
+    SAME_SITE_STRICT = 3,
+
+    // Keep last, used for histograms.
+    COUNT
   };
 
   // Creates a CookieOptions object which:
diff --git a/ppapi/api/dev/pp_print_settings_dev.idl b/ppapi/api/dev/pp_print_settings_dev.idl
index 010d1b8c..d24803ef 100644
--- a/ppapi/api/dev/pp_print_settings_dev.idl
+++ b/ppapi/api/dev/pp_print_settings_dev.idl
@@ -29,7 +29,8 @@
   PP_PRINTSCALINGOPTION_NONE = 0,
   PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA = 1,
   PP_PRINTSCALINGOPTION_SOURCE_SIZE = 2,
-  PP_PRINTSCALINGOPTION_LAST = PP_PRINTSCALINGOPTION_SOURCE_SIZE
+  PP_PRINTSCALINGOPTION_FIT_TO_PAPER = 3,
+  PP_PRINTSCALINGOPTION_LAST = PP_PRINTSCALINGOPTION_FIT_TO_PAPER
 };
 
 [assert_size(60)]
diff --git a/ppapi/c/dev/pp_print_settings_dev.h b/ppapi/c/dev/pp_print_settings_dev.h
index 67c37b2..b474740 100644
--- a/ppapi/c/dev/pp_print_settings_dev.h
+++ b/ppapi/c/dev/pp_print_settings_dev.h
@@ -3,7 +3,7 @@
  * found in the LICENSE file.
  */
 
-/* From dev/pp_print_settings_dev.idl modified Wed Oct 25 09:45:07 2017. */
+/* From dev/pp_print_settings_dev.idl modified Tue Sep  3 14:00:26 2019. */
 
 #ifndef PPAPI_C_DEV_PP_PRINT_SETTINGS_DEV_H_
 #define PPAPI_C_DEV_PP_PRINT_SETTINGS_DEV_H_
@@ -46,7 +46,8 @@
   PP_PRINTSCALINGOPTION_NONE = 0,
   PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA = 1,
   PP_PRINTSCALINGOPTION_SOURCE_SIZE = 2,
-  PP_PRINTSCALINGOPTION_LAST = PP_PRINTSCALINGOPTION_SOURCE_SIZE
+  PP_PRINTSCALINGOPTION_FIT_TO_PAPER = 3,
+  PP_PRINTSCALINGOPTION_LAST = PP_PRINTSCALINGOPTION_FIT_TO_PAPER
 } PP_PrintScalingOption_Dev;
 PP_COMPILE_ASSERT_SIZE_IN_BYTES(PP_PrintScalingOption_Dev, 4);
 /**
diff --git a/printing/print_job_constants.cc b/printing/print_job_constants.cc
index 1c15dfa..51b2219 100644
--- a/printing/print_job_constants.cc
+++ b/printing/print_job_constants.cc
@@ -67,6 +67,10 @@
 // selected else false.
 const char kSettingFitToPageEnabled[] = "fitToPageEnabled";
 
+// Option to fit source page contents to paper size: true if
+// selected else false.
+const char kSettingFitToPaperEnabled[] = "fitToPaperEnabled";
+
 // Option to print headers and Footers: true if selected, false if not.
 const char kSettingHeaderFooterEnabled[] = "headerFooterEnabled";
 
diff --git a/printing/print_job_constants.h b/printing/print_job_constants.h
index c894de81..7c0065f 100644
--- a/printing/print_job_constants.h
+++ b/printing/print_job_constants.h
@@ -29,6 +29,7 @@
 PRINTING_EXPORT extern const char kSettingDuplexMode[];
 PRINTING_EXPORT extern const char kSettingFitToPageEnabled[];
 PRINTING_EXPORT extern const char kSettingFitToPageScaling[];
+PRINTING_EXPORT extern const char kSettingFitToPaperEnabled[];
 PRINTING_EXPORT extern const char kSettingHeaderFooterEnabled[];
 PRINTING_EXPORT extern const float kSettingHeaderFooterInterstice;
 PRINTING_EXPORT extern const char kSettingHeaderFooterDate[];
diff --git a/services/device/generic_sensor/generic_sensor_service_unittest.cc b/services/device/generic_sensor/generic_sensor_service_unittest.cc
index 3e19f8c..94bcccf9 100644
--- a/services/device/generic_sensor/generic_sensor_service_unittest.cc
+++ b/services/device/generic_sensor/generic_sensor_service_unittest.cc
@@ -9,6 +9,7 @@
 #include "base/run_loop.h"
 #include "base/test/scoped_feature_list.h"
 #include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/remote.h"
 #include "services/device/device_service.h"
 #include "services/device/device_service_test_base.h"
 #include "services/device/generic_sensor/fake_platform_sensor_and_provider.h"
@@ -100,7 +101,8 @@
     check_value_ = std::move(callback);
   }
 
-  mojom::SensorPtr& sensor() { return sensor_; }
+  mojom::Sensor* sensor() { return sensor_.get(); }
+  void ResetSensor() { sensor_.reset(); }
 
  private:
   void UpdateReadingData() {
@@ -127,7 +129,7 @@
     return true;
   }
 
-  mojom::SensorPtr sensor_;
+  mojo::Remote<mojom::Sensor> sensor_;
   mojo::Binding<mojom::SensorClient> client_binding_;
   mojo::ScopedSharedBufferMapping shared_buffer_;
   SensorReading reading_data_;
@@ -321,7 +323,7 @@
   }
 
   // Breaks mojo connection of client_1.
-  client_1->sensor().reset();
+  client_1->ResetSensor();
 
   {
     base::RunLoop run_loop;
diff --git a/services/device/generic_sensor/sensor_provider_impl.cc b/services/device/generic_sensor/sensor_provider_impl.cc
index 0c9fe68..9821155 100644
--- a/services/device/generic_sensor/sensor_provider_impl.cc
+++ b/services/device/generic_sensor/sensor_provider_impl.cc
@@ -10,7 +10,7 @@
 #include "base/feature_list.h"
 #include "base/memory/ptr_util.h"
 #include "base/threading/thread_task_runner_handle.h"
-#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
 #include "services/device/generic_sensor/platform_sensor_provider.h"
 #include "services/device/generic_sensor/sensor_impl.h"
 #include "services/device/public/cpp/device_features.h"
@@ -93,10 +93,10 @@
   auto sensor_impl = std::make_unique<SensorImpl>(sensor);
   init_params->client_request = sensor_impl->GetClient();
 
-  mojom::SensorPtrInfo sensor_ptr_info;
-  sensor_bindings_.AddBinding(std::move(sensor_impl),
-                              mojo::MakeRequest(&sensor_ptr_info));
-  init_params->sensor = std::move(sensor_ptr_info);
+  mojo::PendingRemote<mojom::Sensor> pending_sensor;
+  sensor_receivers_.Add(std::move(sensor_impl),
+                        pending_sensor.InitWithNewPipeAndPassReceiver());
+  init_params->sensor = std::move(pending_sensor);
 
   init_params->memory = std::move(cloned_handle);
   init_params->buffer_offset = SensorReadingSharedBuffer::GetOffset(type);
diff --git a/services/device/generic_sensor/sensor_provider_impl.h b/services/device/generic_sensor/sensor_provider_impl.h
index 9a13f0a..4f26db0 100644
--- a/services/device/generic_sensor/sensor_provider_impl.h
+++ b/services/device/generic_sensor/sensor_provider_impl.h
@@ -8,7 +8,7 @@
 #include "base/macros.h"
 #include "base/single_thread_task_runner.h"
 #include "mojo/public/cpp/bindings/binding_set.h"
-#include "mojo/public/cpp/bindings/strong_binding_set.h"
+#include "mojo/public/cpp/bindings/unique_receiver_set.h"
 #include "services/device/public/mojom/sensor_provider.mojom.h"
 
 namespace device {
@@ -40,7 +40,7 @@
 
   std::unique_ptr<PlatformSensorProvider> provider_;
   mojo::BindingSet<mojom::SensorProvider> bindings_;
-  mojo::StrongBindingSet<mojom::Sensor> sensor_bindings_;
+  mojo::UniqueReceiverSet<mojom::Sensor> sensor_receivers_;
   base::WeakPtrFactory<SensorProviderImpl> weak_ptr_factory_{this};
 
   DISALLOW_COPY_AND_ASSIGN(SensorProviderImpl);
diff --git a/services/device/public/cpp/test/fake_sensor_and_provider.cc b/services/device/public/cpp/test/fake_sensor_and_provider.cc
index c8363fb..f75702d 100644
--- a/services/device/public/cpp/test/fake_sensor_and_provider.cc
+++ b/services/device/public/cpp/test/fake_sensor_and_provider.cc
@@ -10,7 +10,7 @@
 #include "base/logging.h"
 #include "base/time/time.h"
 #include "mojo/public/cpp/bindings/interface_request.h"
-#include "mojo/public/cpp/bindings/strong_binding.h"
+#include "mojo/public/cpp/bindings/self_owned_receiver.h"
 #include "services/device/public/cpp/generic_sensor/sensor_traits.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -175,8 +175,9 @@
     init_params->maximum_frequency = sensor->GetMaximumSupportedFrequency();
     init_params->minimum_frequency = sensor->GetMinimumSupportedFrequency();
 
-    mojo::MakeStrongBinding(std::move(sensor),
-                            mojo::MakeRequest(&init_params->sensor));
+    mojo::MakeSelfOwnedReceiver(
+        std::move(sensor),
+        init_params->sensor.InitWithNewPipeAndPassReceiver());
     std::move(callback).Run(mojom::SensorCreationResult::SUCCESS,
                             std::move(init_params));
   } else {
diff --git a/services/device/public/mojom/sensor_provider.mojom b/services/device/public/mojom/sensor_provider.mojom
index b341f5fa..1e56e26 100644
--- a/services/device/public/mojom/sensor_provider.mojom
+++ b/services/device/public/mojom/sensor_provider.mojom
@@ -8,7 +8,7 @@
 
 struct SensorInitParams {
   // The Sensor interface.
-  Sensor sensor;
+  pending_remote<Sensor> sensor;
 
   // The SensorClient interface used to report sensor events.
   SensorClient& client_request;
diff --git a/services/network/public/cpp/cookie_manager_mojom_traits.cc b/services/network/public/cpp/cookie_manager_mojom_traits.cc
index 014a3c9..6f3461ff 100644
--- a/services/network/public/cpp/cookie_manager_mojom_traits.cc
+++ b/services/network/public/cpp/cookie_manager_mojom_traits.cc
@@ -154,9 +154,10 @@
       return network::mojom::CookieSameSiteContext::SAME_SITE_LAX_METHOD_UNSAFE;
     case net::CookieOptions::SameSiteCookieContext::CROSS_SITE:
       return network::mojom::CookieSameSiteContext::CROSS_SITE;
+    default:
+      NOTREACHED();
+      return network::mojom::CookieSameSiteContext::CROSS_SITE;
   }
-  NOTREACHED();
-  return network::mojom::CookieSameSiteContext::CROSS_SITE;
 }
 
 bool EnumTraits<network::mojom::CookieSameSiteContext,
diff --git a/services/viz/public/cpp/compositing/shared_quad_state_mojom_traits.h b/services/viz/public/cpp/compositing/shared_quad_state_mojom_traits.h
index d2e955b8..4153d90 100644
--- a/services/viz/public/cpp/compositing/shared_quad_state_mojom_traits.h
+++ b/services/viz/public/cpp/compositing/shared_quad_state_mojom_traits.h
@@ -67,6 +67,10 @@
   static bool is_fast_rounded_corner(const OptSharedQuadState& input) {
     return input.sqs->is_fast_rounded_corner;
   }
+
+  static float de_jelly_delta_y(const OptSharedQuadState& input) {
+    return input.sqs->de_jelly_delta_y;
+  }
 };
 
 template <>
@@ -116,6 +120,10 @@
     return sqs.is_fast_rounded_corner;
   }
 
+  static float de_jelly_delta_y(const viz::SharedQuadState& sqs) {
+    return sqs.de_jelly_delta_y;
+  }
+
   static bool Read(viz::mojom::SharedQuadStateDataView data,
                    viz::SharedQuadState* out) {
     if (!data.ReadQuadToTargetTransform(&out->quad_to_target_transform) ||
@@ -134,6 +142,7 @@
     out->blend_mode = static_cast<SkBlendMode>(data.blend_mode());
     out->sorting_context_id = data.sorting_context_id();
     out->is_fast_rounded_corner = data.is_fast_rounded_corner();
+    out->de_jelly_delta_y = data.de_jelly_delta_y();
     return true;
   }
 };
diff --git a/services/viz/public/mojom/compositing/shared_quad_state.mojom b/services/viz/public/mojom/compositing/shared_quad_state.mojom
index 2f873f4..12062fb 100644
--- a/services/viz/public/mojom/compositing/shared_quad_state.mojom
+++ b/services/viz/public/mojom/compositing/shared_quad_state.mojom
@@ -39,4 +39,8 @@
   int32 sorting_context_id;
 
   bool is_fast_rounded_corner;
+
+  // The y offset by which to skew quads in this layer. For experimental
+  // de-jelly effect.
+  float de_jelly_delta_y;
 };
diff --git a/skia/BUILD.gn b/skia/BUILD.gn
index ecb5604..3fda6d4 100644
--- a/skia/BUILD.gn
+++ b/skia/BUILD.gn
@@ -436,6 +436,7 @@
       "//third_party/fuchsia-sdk/sdk:fonts",
       "//third_party/fuchsia-sdk/sdk:io",
       "//third_party/fuchsia-sdk/sdk:sys",
+      "//third_party/fuchsia-sdk/sdk:sys_cpp",
       "//third_party/fuchsia-sdk/sdk:zx",
       "//third_party/icu:icuuc",
     ]
@@ -836,6 +837,7 @@
       "//third_party/fuchsia-sdk/sdk:fonts",
       "//third_party/fuchsia-sdk/sdk:io",
       "//third_party/fuchsia-sdk/sdk:sys",
+      "//third_party/fuchsia-sdk/sdk:sys_cpp",
     ]
   }
   if (is_linux) {
diff --git a/skia/ext/fontmgr_default_fuchsia.cc b/skia/ext/fontmgr_default_fuchsia.cc
index 4c09946..6126c29 100644
--- a/skia/ext/fontmgr_default_fuchsia.cc
+++ b/skia/ext/fontmgr_default_fuchsia.cc
@@ -5,17 +5,19 @@
 #include "skia/ext/fontmgr_default.h"
 
 #include <fuchsia/fonts/cpp/fidl.h>
+#include <lib/sys/cpp/component_context.h>
 
-#include "base/fuchsia/service_directory_client.h"
+#include "base/fuchsia/default_context.h"
 #include "third_party/skia/include/core/SkFontMgr.h"
 #include "third_party/skia/include/ports/SkFontMgr_fuchsia.h"
 
 namespace skia {
 
 SK_API sk_sp<SkFontMgr> CreateDefaultSkFontMgr() {
-  return SkFontMgr_New_Fuchsia(
-      base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-          ->ConnectToServiceSync<fuchsia::fonts::Provider>());
+  fuchsia::fonts::ProviderSyncPtr provider;
+  base::fuchsia::ComponentContextForCurrentProcess()->svc()->Connect(
+      provider.NewRequest());
+  return SkFontMgr_New_Fuchsia(std::move(provider));
 }
 
 }  // namespace skia
\ No newline at end of file
diff --git a/skia/ext/test_fonts_fuchsia.cc b/skia/ext/test_fonts_fuchsia.cc
index d47c3409..083b2c0 100644
--- a/skia/ext/test_fonts_fuchsia.cc
+++ b/skia/ext/test_fonts_fuchsia.cc
@@ -8,9 +8,10 @@
 #include <fuchsia/io/cpp/fidl.h>
 #include <fuchsia/sys/cpp/fidl.h>
 #include <lib/fidl/cpp/interface_handle.h>
+#include <lib/sys/cpp/component_context.h>
 
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/file_utils.h"
-#include "base/fuchsia/service_directory_client.h"
 #include "base/no_destructor.h"
 #include "base/path_service.h"
 #include "skia/ext/fontmgr_default.h"
@@ -43,17 +44,18 @@
   launch_info.directory_request =
       font_provider_services_dir.NewRequest().TakeChannel();
 
-  fuchsia::sys::LauncherSyncPtr launcher =
-      base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-          ->ConnectToServiceSync<fuchsia::sys::Launcher>();
+  fuchsia::sys::LauncherSyncPtr launcher;
+  base::fuchsia::ComponentContextForCurrentProcess()->svc()->Connect(
+      launcher.NewRequest());
   launcher->CreateComponent(std::move(launch_info),
                             controller_out->NewRequest());
 
-  base::fuchsia::ServiceDirectoryClient font_provider_services_client(
+  sys::ServiceDirectory font_provider_services_client(
       std::move(font_provider_services_dir));
 
-  return font_provider_services_client
-      .ConnectToServiceSync<fuchsia::fonts::Provider>();
+  fuchsia::fonts::ProviderSyncPtr provider;
+  font_provider_services_client.Connect(provider.NewRequest());
+  return provider;
 }
 
 void ConfigureTestFont() {
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json
index 643b3a7d..af45755 100644
--- a/testing/variations/fieldtrial_testing_config.json
+++ b/testing/variations/fieldtrial_testing_config.json
@@ -1456,28 +1456,6 @@
             ]
         }
     ],
-    "CacheStorageParallelOps": [
-        {
-            "platforms": [
-                "windows",
-                "mac",
-                "chromeos",
-                "linux",
-                "android"
-            ],
-            "experiments": [
-                {
-                    "name": "Enabled16_v1",
-                    "params": {
-                        "max_shared_ops": "16"
-                    },
-                    "enable_features": [
-                        "CacheStorageParallelOps"
-                    ]
-                }
-            ]
-        }
-    ],
     "CacheStorageSequence": [
         {
             "platforms": [
@@ -1547,6 +1525,21 @@
             ]
         }
     ],
+    "ChromeCleanupProtobufIPC": [
+        {
+            "platforms": [
+                "windows"
+            ],
+            "experiments": [
+                {
+                    "name": "Enabled",
+                    "enable_features": [
+                        "ChromeCleanupProtobufIPC"
+                    ]
+                }
+            ]
+        }
+    ],
     "ChromeSmartSelection": [
         {
             "platforms": [
@@ -4649,6 +4642,9 @@
     "PreventDownloadsWithSamePath": [
         {
             "platforms": [
+                "chromeos",
+                "linux",
+                "mac",
                 "windows"
             ],
             "experiments": [
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc
index 8c850012..30a0154d 100644
--- a/third_party/blink/common/features.cc
+++ b/third_party/blink/common/features.cc
@@ -262,8 +262,8 @@
                                      base::FEATURE_DISABLED_BY_DEFAULT};
 
 // Allows for synchronous XHR requests during page dismissal
-const base::Feature kForbidSyncXHRInPageDismissal{
-    "ForbidSyncXHRInPageDismissal", base::FEATURE_ENABLED_BY_DEFAULT};
+const base::Feature kAllowSyncXHRInPageDismissal{
+    "AllowSyncXHRInPageDismissal", base::FEATURE_DISABLED_BY_DEFAULT};
 
 // Prefetch request properties are updated to be privacy-preserving. See
 // crbug.com/988956.
diff --git a/third_party/blink/public/BUILD.gn b/third_party/blink/public/BUILD.gn
index 027c0c68..b354871 100644
--- a/third_party/blink/public/BUILD.gn
+++ b/third_party/blink/public/BUILD.gn
@@ -149,10 +149,22 @@
     "platform/modules/mediastream/web_platform_media_stream_source.h",
     "platform/modules/mediastream/web_platform_media_stream_track.h",
     "platform/modules/mediastream/webrtc_uma_histograms.h",
+    "platform/modules/p2p/empty_network_manager.h",
+    "platform/modules/p2p/filtering_network_manager.h",
+    "platform/modules/p2p/ipc_network_manager.h",
+    "platform/modules/p2p/network_list_manager.h",
+    "platform/modules/p2p/network_list_observer.h",
+    "platform/modules/p2p/network_manager_uma.h",
+    "platform/modules/p2p/socket_client.h",
+    "platform/modules/p2p/socket_client_delegate.h",
     "platform/modules/peerconnection/audio_codec_factory.h",
     "platform/modules/peerconnection/rtc_event_log_output_sink.h",
     "platform/modules/peerconnection/rtc_event_log_output_sink_proxy_util.h",
+    "platform/modules/peerconnection/rtc_video_decoder_factory_util.h",
+    "platform/modules/peerconnection/rtc_video_encoder_factory_util.h",
+    "platform/modules/peerconnection/stun_field_trial.h",
     "platform/modules/peerconnection/two_keys_adapter_map.h",
+    "platform/modules/peerconnection/video_codec_factory.h",
     "platform/modules/peerconnection/webrtc_audio_sink.h",
     "platform/modules/peerconnection/webrtc_util.h",
     "platform/modules/peerconnection/webrtc_video_track_source.h",
@@ -374,7 +386,6 @@
     "web/modules/mediastream/web_media_stream_utils.h",
     "web/modules/mediastream/webmediaplayer_ms.h",
     "web/modules/peerconnection/media_stream_remote_video_source.h",
-    "web/modules/peerconnection/peer_connection_dependency_factory.h",
     "web/modules/service_worker/web_service_worker_context_client.h",
     "web/modules/service_worker/web_service_worker_context_proxy.h",
     "web/modules/webrtc/webrtc_audio_device_impl.h",
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h
index 29ee3bc..76975321 100644
--- a/third_party/blink/public/common/features.h
+++ b/third_party/blink/public/common/features.h
@@ -73,7 +73,7 @@
 BLINK_COMMON_EXPORT extern const base::Feature kWasmCodeCache;
 BLINK_COMMON_EXPORT extern const base::Feature kNativeFileSystemAPI;
 BLINK_COMMON_EXPORT extern const base::Feature kFileHandlingAPI;
-BLINK_COMMON_EXPORT extern const base::Feature kForbidSyncXHRInPageDismissal;
+BLINK_COMMON_EXPORT extern const base::Feature kAllowSyncXHRInPageDismissal;
 BLINK_COMMON_EXPORT extern const base::Feature kPrefetchPrivacyChanges;
 
 BLINK_COMMON_EXPORT extern const char kMixedContentAutoupgradeModeParamName[];
diff --git a/third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom b/third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom
index 0ee74d3..709e5c6 100644
--- a/third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom
+++ b/third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom
@@ -65,5 +65,5 @@
   // Create a TransferToken for this directory. This token can be used to pass
   // a reference to this directory to other methods, for example to copy or move
   // the directory, or when transferring the handle over postMessage.
-  Transfer(NativeFileSystemTransferToken& token);
+  Transfer(pending_receiver<NativeFileSystemTransferToken> token);
 };
diff --git a/third_party/blink/public/mojom/native_file_system/native_file_system_file_handle.mojom b/third_party/blink/public/mojom/native_file_system/native_file_system_file_handle.mojom
index badc3b6..708b469 100644
--- a/third_party/blink/public/mojom/native_file_system/native_file_system_file_handle.mojom
+++ b/third_party/blink/public/mojom/native_file_system/native_file_system_file_handle.mojom
@@ -31,5 +31,5 @@
   // Create a TransferToken for this directory. This token can be used to pass
   // a reference to this directory to other methods, for example to copy or move
   // the file, or when transferring the handle over postMessage.
-  Transfer(NativeFileSystemTransferToken& token);
+  Transfer(pending_receiver<NativeFileSystemTransferToken> token);
 };
diff --git a/third_party/blink/public/mojom/native_file_system/native_file_system_manager.mojom b/third_party/blink/public/mojom/native_file_system/native_file_system_manager.mojom
index 3bdedf7..021ef37 100644
--- a/third_party/blink/public/mojom/native_file_system/native_file_system_manager.mojom
+++ b/third_party/blink/public/mojom/native_file_system/native_file_system_manager.mojom
@@ -49,6 +49,6 @@
        array<NativeFileSystemEntry> entries);
 
   // TODO(mek): Add this method when it is needed for transferability of handles.
-  // GetHandleFromToken(NativeFileSystemTransferToken token) =>
+  // GetHandleFromToken(pending_remote<NativeFileSystemTransferToken> token) =>
   //     (NativeFileSystemError result, NativeFileSystemHandle? entry_handle);
 };
diff --git a/third_party/blink/public/platform/modules/p2p/DEPS b/third_party/blink/public/platform/modules/p2p/DEPS
new file mode 100644
index 0000000..66a33743
--- /dev/null
+++ b/third_party/blink/public/platform/modules/p2p/DEPS
@@ -0,0 +1,4 @@
+include_rules = [
+    "+net/base/ip_endpoint.h",
+    "+services/network/public/cpp/p2p_socket_type.h",
+]
diff --git a/third_party/blink/public/platform/modules/p2p/OWNERS b/third_party/blink/public/platform/modules/p2p/OWNERS
new file mode 100644
index 0000000..de19af2b
--- /dev/null
+++ b/third_party/blink/public/platform/modules/p2p/OWNERS
@@ -0,0 +1 @@
+file://third_party/blink/renderer/platform/p2p/OWNERS
diff --git a/third_party/blink/renderer/platform/p2p/empty_network_manager.h b/third_party/blink/public/platform/modules/p2p/empty_network_manager.h
similarity index 78%
rename from third_party/blink/renderer/platform/p2p/empty_network_manager.h
rename to third_party/blink/public/platform/modules/p2p/empty_network_manager.h
index 77d43634..41f5495 100644
--- a/third_party/blink/renderer/platform/p2p/empty_network_manager.h
+++ b/third_party/blink/public/platform/modules/p2p/empty_network_manager.h
@@ -2,13 +2,13 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_EMPTY_NETWORK_MANAGER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_EMPTY_NETWORK_MANAGER_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_EMPTY_NETWORK_MANAGER_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_EMPTY_NETWORK_MANAGER_H_
 
 #include "base/macros.h"
 #include "base/memory/weak_ptr.h"
 #include "base/threading/thread_checker.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/public/platform/web_common.h"
 #include "third_party/webrtc/rtc_base/network.h"
 #include "third_party/webrtc/rtc_base/third_party/sigslot/sigslot.h"
 
@@ -21,14 +21,17 @@
 // A NetworkManager implementation which handles the case where local address
 // enumeration is not requested and just returns empty network lists. This class
 // is not thread safe and should only be used by WebRTC's network thread.
+//
+// TODO(crbug.com/787254): Move this class out of the Blink exposed API when
+// all users of it have been Onion souped. Also, move it away from std::vector.
 class EmptyNetworkManager : public rtc::NetworkManagerBase,
                             public sigslot::has_slots<> {
  public:
   // This class is created by WebRTC's signaling thread but used by WebRTC's
   // worker thread |task_runner|.
-  PLATFORM_EXPORT explicit EmptyNetworkManager(
+  BLINK_PLATFORM_EXPORT explicit EmptyNetworkManager(
       rtc::NetworkManager* network_manager);
-  PLATFORM_EXPORT ~EmptyNetworkManager() override;
+  BLINK_PLATFORM_EXPORT ~EmptyNetworkManager() override;
 
   // rtc::NetworkManager:
   void StartUpdating() override;
@@ -66,4 +69,4 @@
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_EMPTY_NETWORK_MANAGER_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_EMPTY_NETWORK_MANAGER_H_
diff --git a/third_party/blink/renderer/platform/p2p/filtering_network_manager.h b/third_party/blink/public/platform/modules/p2p/filtering_network_manager.h
similarity index 93%
rename from third_party/blink/renderer/platform/p2p/filtering_network_manager.h
rename to third_party/blink/public/platform/modules/p2p/filtering_network_manager.h
index 39611ce..bb957e6 100644
--- a/third_party/blink/renderer/platform/p2p/filtering_network_manager.h
+++ b/third_party/blink/public/platform/modules/p2p/filtering_network_manager.h
@@ -2,15 +2,15 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_FILTERING_NETWORK_MANAGER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_FILTERING_NETWORK_MANAGER_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_FILTERING_NETWORK_MANAGER_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_FILTERING_NETWORK_MANAGER_H_
 
 #include "base/macros.h"
 #include "base/memory/weak_ptr.h"
 #include "base/threading/thread_checker.h"
 #include "base/time/time.h"
+#include "third_party/blink/public/platform/modules/p2p/network_manager_uma.h"
 #include "third_party/blink/public/platform/web_common.h"
-#include "third_party/blink/renderer/platform/p2p/network_manager_uma.h"
 #include "third_party/webrtc/rtc_base/network.h"
 #include "third_party/webrtc/rtc_base/third_party/sigslot/sigslot.h"
 #include "url/gurl.h"
@@ -125,4 +125,4 @@
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_FILTERING_NETWORK_MANAGER_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_FILTERING_NETWORK_MANAGER_H_
diff --git a/third_party/blink/renderer/platform/p2p/ipc_network_manager.h b/third_party/blink/public/platform/modules/p2p/ipc_network_manager.h
similarity index 73%
rename from third_party/blink/renderer/platform/p2p/ipc_network_manager.h
rename to third_party/blink/public/platform/modules/p2p/ipc_network_manager.h
index 8db0420..d70b628 100644
--- a/third_party/blink/renderer/platform/p2p/ipc_network_manager.h
+++ b/third_party/blink/public/platform/modules/p2p/ipc_network_manager.h
@@ -2,15 +2,15 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_IPC_NETWORK_MANAGER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_IPC_NETWORK_MANAGER_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_IPC_NETWORK_MANAGER_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_IPC_NETWORK_MANAGER_H_
 
 #include <memory>
 
 #include "base/memory/weak_ptr.h"
-#include "third_party/blink/renderer/platform/p2p/network_list_manager.h"
-#include "third_party/blink/renderer/platform/p2p/network_list_observer.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/public/platform/modules/p2p/network_list_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/network_list_observer.h"
+#include "third_party/blink/public/platform/web_common.h"
 #include "third_party/webrtc/rtc_base/mdns_responder_interface.h"
 #include "third_party/webrtc/rtc_base/network.h"
 
@@ -26,7 +26,7 @@
                           public blink::NetworkListObserver {
  public:
   // Constructor doesn't take ownership of the |network_list_manager|.
-  PLATFORM_EXPORT IpcNetworkManager(
+  BLINK_PLATFORM_EXPORT IpcNetworkManager(
       blink::NetworkListManager* network_list_manager,
       std::unique_ptr<webrtc::MdnsResponderInterface> mdns_responder);
   ~IpcNetworkManager() override;
@@ -45,8 +45,6 @@
  private:
   void SendNetworksChangedSignal();
 
-  // TODO(crbug.com/787254): Consider moving NetworkListManager to Oilpan and
-  // avoid using a raw pointer.
   blink::NetworkListManager* network_list_manager_;
   std::unique_ptr<webrtc::MdnsResponderInterface> mdns_responder_;
   int start_count_ = 0;
@@ -57,4 +55,4 @@
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_IPC_NETWORK_MANAGER_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_IPC_NETWORK_MANAGER_H_
diff --git a/third_party/blink/renderer/platform/p2p/network_list_manager.h b/third_party/blink/public/platform/modules/p2p/network_list_manager.h
similarity index 70%
rename from third_party/blink/renderer/platform/p2p/network_list_manager.h
rename to third_party/blink/public/platform/modules/p2p/network_list_manager.h
index 0be11c05..0928325 100644
--- a/third_party/blink/renderer/platform/p2p/network_list_manager.h
+++ b/third_party/blink/public/platform/modules/p2p/network_list_manager.h
@@ -6,18 +6,18 @@
 // IpcNetworkManager such that it doesn't depend on implementation of
 // P2PSocketDispatcher.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_LIST_MANAGER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_LIST_MANAGER_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_LIST_MANAGER_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_LIST_MANAGER_H_
 
-#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/public/platform/web_common.h"
 
 namespace blink {
 
 class NetworkListObserver;
 
-// TODO(crbug.com/787254): Verify whether this abstract class is still
-// needed now that its Clients have all switched to Blink.
-class PLATFORM_EXPORT NetworkListManager {
+// TODO(crbug.com/787254): Move this class out of the Blink exposed API when
+// all users of it have been Onion souped.
+class BLINK_PLATFORM_EXPORT NetworkListManager {
  public:
   // Add a new network list observer. Each observer is called
   // immidiately after it is registered and then later whenever
@@ -39,4 +39,4 @@
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_LIST_MANAGER_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_LIST_MANAGER_H_
diff --git a/third_party/blink/renderer/platform/p2p/network_list_observer.h b/third_party/blink/public/platform/modules/p2p/network_list_observer.h
similarity index 61%
rename from third_party/blink/renderer/platform/p2p/network_list_observer.h
rename to third_party/blink/public/platform/modules/p2p/network_list_observer.h
index 714c9a7..8c80fbd 100644
--- a/third_party/blink/renderer/platform/p2p/network_list_observer.h
+++ b/third_party/blink/public/platform/modules/p2p/network_list_observer.h
@@ -2,8 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_LIST_OBSERVER_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_LIST_OBSERVER_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_LIST_OBSERVER_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_LIST_OBSERVER_H_
 
 #include <vector>
 
@@ -15,10 +15,8 @@
 
 namespace blink {
 
-// TODO(crbug.com/787254): Verify whether this abstract class is still
-// needed now that its Clients have all switched to Blink.
-//
-// TODO(crbug.com/787254): Move this class away from std::vector.
+// TODO(crbug.com/787254): Move this class out of the Blink exposed API when
+// all users of it have been Onion souped. Also, move it away from std::vector.
 class NetworkListObserver {
  public:
   virtual ~NetworkListObserver() {}
@@ -34,4 +32,4 @@
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_LIST_OBSERVER_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_LIST_OBSERVER_H_
diff --git a/third_party/blink/renderer/platform/p2p/network_manager_uma.h b/third_party/blink/public/platform/modules/p2p/network_manager_uma.h
similarity index 71%
rename from third_party/blink/renderer/platform/p2p/network_manager_uma.h
rename to third_party/blink/public/platform/modules/p2p/network_manager_uma.h
index 618e3d9f..f26a93b0 100644
--- a/third_party/blink/renderer/platform/p2p/network_manager_uma.h
+++ b/third_party/blink/public/platform/modules/p2p/network_manager_uma.h
@@ -2,10 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_MANAGER_UMA_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_MANAGER_UMA_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_MANAGER_UMA_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_MANAGER_UMA_H_
 
-#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/public/platform/web_common.h"
 
 namespace base {
 class TimeDelta;
@@ -28,10 +28,10 @@
   PERMISSION_MAX,
 };
 
-PLATFORM_EXPORT void ReportIPPermissionStatus(IPPermissionStatus status);
-PLATFORM_EXPORT void ReportTimeToUpdateNetworkList(
+BLINK_PLATFORM_EXPORT void ReportIPPermissionStatus(IPPermissionStatus status);
+BLINK_PLATFORM_EXPORT void ReportTimeToUpdateNetworkList(
     const base::TimeDelta& ticks);
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_NETWORK_MANAGER_UMA_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_NETWORK_MANAGER_UMA_H_
diff --git a/third_party/blink/renderer/platform/p2p/socket_client.h b/third_party/blink/public/platform/modules/p2p/socket_client.h
similarity index 69%
rename from third_party/blink/renderer/platform/p2p/socket_client.h
rename to third_party/blink/public/platform/modules/p2p/socket_client.h
index 4b0ef9b8..6d7fe7a 100644
--- a/third_party/blink/renderer/platform/p2p/socket_client.h
+++ b/third_party/blink/public/platform/modules/p2p/socket_client.h
@@ -2,14 +2,15 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_SOCKET_CLIENT_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_SOCKET_CLIENT_H_
 
 #include <stdint.h>
 
+#include <vector>
+
 #include "net/base/ip_endpoint.h"
 #include "services/network/public/cpp/p2p_socket_type.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
 
 namespace rtc {
 struct PacketOptions;
@@ -21,10 +22,8 @@
 
 // P2P socket that routes all calls over IPC.
 //
-// TODO(crbug.com/787254): Verify whether this class is still needed
-// now that all its clients are in Blink.
-//
-// Also, move it away from std::vector.
+// TODO(crbug.com/787254): Move this class out of the Blink exposed API when
+// all users of it have been Onion souped. Also, move it away from std::vector.
 class P2PSocketClient {
  public:
   virtual ~P2PSocketClient() {}
@@ -32,7 +31,7 @@
   // Send the |data| to the |address| using Differentiated Services Code Point
   // |dscp|. Return value is the unique packet_id for this packet.
   virtual uint64_t Send(const net::IPEndPoint& address,
-                        const Vector<int8_t>& data,
+                        const std::vector<int8_t>& data,
                         const rtc::PacketOptions& options) = 0;
 
   virtual void SetOption(network::P2PSocketOption option, int value) = 0;
@@ -48,4 +47,4 @@
 };
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_SOCKET_CLIENT_H_
diff --git a/third_party/blink/renderer/platform/p2p/socket_client_delegate.h b/third_party/blink/public/platform/modules/p2p/socket_client_delegate.h
similarity index 74%
rename from third_party/blink/renderer/platform/p2p/socket_client_delegate.h
rename to third_party/blink/public/platform/modules/p2p/socket_client_delegate.h
index 282784fb..e9eaf28d 100644
--- a/third_party/blink/renderer/platform/p2p/socket_client_delegate.h
+++ b/third_party/blink/public/platform/modules/p2p/socket_client_delegate.h
@@ -2,8 +2,10 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_DELEGATE_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_DELEGATE_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_SOCKET_CLIENT_DELEGATE_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_SOCKET_CLIENT_DELEGATE_H_
+
+#include <vector>
 
 #include "net/base/ip_endpoint.h"
 #include "services/network/public/cpp/p2p_socket_type.h"
@@ -12,8 +14,8 @@
 
 class P2PSocketClient;
 
-// TODO(crbug.com/787254): Consider eliminating this pure virtual class now
-// that it has moved to blink/renderer.
+// TODO(crbug.com/787254): Move this class out of the Blink exposed API when
+// all users of it have been Onion souped. Also, move it away from std::vector.
 class P2PSocketClientDelegate {
  public:
   virtual ~P2PSocketClientDelegate() {}
@@ -39,10 +41,10 @@
 
   // Called when data is received on the socket.
   virtual void OnDataReceived(const net::IPEndPoint& address,
-                              const Vector<int8_t>& data,
+                              const std::vector<int8_t>& data,
                               const base::TimeTicks& timestamp) = 0;
 };
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_P2P_SOCKET_CLIENT_DELEGATE_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_P2P_SOCKET_CLIENT_DELEGATE_H_
diff --git a/third_party/blink/public/platform/modules/peerconnection/rtc_video_decoder_factory_util.h b/third_party/blink/public/platform/modules/peerconnection/rtc_video_decoder_factory_util.h
new file mode 100644
index 0000000..de64ea4d
--- /dev/null
+++ b/third_party/blink/public/platform/modules/peerconnection/rtc_video_decoder_factory_util.h
@@ -0,0 +1,29 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_RTC_VIDEO_DECODER_FACTORY_UTIL_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_RTC_VIDEO_DECODER_FACTORY_UTIL_H_
+
+#include <memory>
+
+#include "third_party/blink/public/platform/web_common.h"
+
+namespace media {
+class GpuVideoAcceleratorFactories;
+}
+
+namespace webrtc {
+class VideoDecoderFactory;
+}
+
+namespace blink {
+
+// TODO(crbug.com/787254): Remove this API when its clients are Onion souped.
+BLINK_PLATFORM_EXPORT std::unique_ptr<webrtc::VideoDecoderFactory>
+CreateRTCVideoDecoderFactory(
+    media::GpuVideoAcceleratorFactories* gpu_factories);
+
+}  // namespace blink
+
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_RTC_VIDEO_DECODER_FACTORY_UTIL_H_
diff --git a/third_party/blink/public/platform/modules/peerconnection/rtc_video_encoder_factory_util.h b/third_party/blink/public/platform/modules/peerconnection/rtc_video_encoder_factory_util.h
new file mode 100644
index 0000000..45bafd3f
--- /dev/null
+++ b/third_party/blink/public/platform/modules/peerconnection/rtc_video_encoder_factory_util.h
@@ -0,0 +1,29 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_RTC_VIDEO_ENCODER_FACTORY_UTIL_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_RTC_VIDEO_ENCODER_FACTORY_UTIL_H_
+
+#include <memory>
+
+#include "third_party/blink/public/platform/web_common.h"
+
+namespace media {
+class GpuVideoAcceleratorFactories;
+}
+
+namespace webrtc {
+class VideoEncoderFactory;
+}
+
+namespace blink {
+
+// TODO(crbug.com/787254): Remove this API when its clients are Onion souped.
+BLINK_PLATFORM_EXPORT std::unique_ptr<webrtc::VideoEncoderFactory>
+CreateRTCVideoEncoderFactory(
+    media::GpuVideoAcceleratorFactories* gpu_factories);
+
+}  // namespace blink
+
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_RTC_VIDEO_ENCODER_FACTORY_UTIL_H_
diff --git a/third_party/blink/renderer/platform/peerconnection/stun_field_trial.h b/third_party/blink/public/platform/modules/peerconnection/stun_field_trial.h
similarity index 74%
rename from third_party/blink/renderer/platform/peerconnection/stun_field_trial.h
rename to third_party/blink/public/platform/modules/peerconnection/stun_field_trial.h
index 223e0145..45953c03 100644
--- a/third_party/blink/renderer/platform/peerconnection/stun_field_trial.h
+++ b/third_party/blink/public/platform/modules/peerconnection/stun_field_trial.h
@@ -2,8 +2,8 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_PEERCONNECTION_STUN_FIELD_TRIAL_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_PEERCONNECTION_STUN_FIELD_TRIAL_H_
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_STUN_FIELD_TRIAL_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_STUN_FIELD_TRIAL_H_
 
 #include <memory>
 #include <string>
@@ -12,9 +12,9 @@
 #include "base/macros.h"
 #include "base/threading/thread_checker.h"
 #include "base/timer/timer.h"
-#include "third_party/blink/renderer/platform/p2p/network_list_manager.h"
-#include "third_party/blink/renderer/platform/p2p/network_list_observer.h"
-#include "third_party/blink/renderer/platform/platform_export.h"
+#include "third_party/blink/public/platform/modules/p2p/network_list_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/network_list_observer.h"
+#include "third_party/blink/public/platform/web_common.h"
 #include "third_party/webrtc/p2p/stunprober/stun_prober.h"
 #include "third_party/webrtc/rtc_base/network.h"
 #include "third_party/webrtc/rtc_base/third_party/sigslot/sigslot.h"
@@ -32,11 +32,13 @@
 // stun probe.
 static const int kExperimentStartDelayMs = 30000;
 
-// TODO(crbug.com/787254): Migrate away from std::vector and std::string.
+// TODO(crbug.com/787254): Move this class out of the Blink exposed API when
+// all users of it have been Onion souped. Also migrate away from std::vector
+// and std::string.
 class StunProberTrial : public stunprober::StunProber::Observer,
                         public sigslot::has_slots<> {
  public:
-  struct PLATFORM_EXPORT Param {
+  struct BLINK_PLATFORM_EXPORT Param {
     Param();
     ~Param();
     int requests_per_ip = 0;
@@ -47,9 +49,9 @@
     std::vector<rtc::SocketAddress> servers;
   };
 
-  PLATFORM_EXPORT StunProberTrial(rtc::NetworkManager* network_manager,
-                                  const std::string& params,
-                                  rtc::PacketSocketFactory* factory);
+  BLINK_PLATFORM_EXPORT StunProberTrial(rtc::NetworkManager* network_manager,
+                                        const std::string& params,
+                                        rtc::PacketSocketFactory* factory);
   ~StunProberTrial() override;
 
  private:
@@ -59,8 +61,9 @@
   void OnNetworksChanged();
 
   // Parsing function to decode the '/' separated parameter string |params|.
-  static PLATFORM_EXPORT bool ParseParameters(const std::string& param_line,
-                                              Param* params);
+  static BLINK_PLATFORM_EXPORT bool ParseParameters(
+      const std::string& param_line,
+      Param* params);
 
   // stunprober::StunProber::Observer:
   void OnPrepared(stunprober::StunProber* prober,
@@ -100,4 +103,4 @@
 
 }  // namespace blink
 
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_PEERCONNECTION_STUN_FIELD_TRIAL_H_
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_STUN_FIELD_TRIAL_H_
diff --git a/third_party/blink/public/platform/modules/peerconnection/video_codec_factory.h b/third_party/blink/public/platform/modules/peerconnection/video_codec_factory.h
new file mode 100644
index 0000000..99a4fbd3
--- /dev/null
+++ b/third_party/blink/public/platform/modules/peerconnection/video_codec_factory.h
@@ -0,0 +1,29 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_VIDEO_CODEC_FACTORY_H_
+#define THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_VIDEO_CODEC_FACTORY_H_
+
+#include "third_party/blink/public/platform/web_common.h"
+#include "third_party/webrtc/api/video_codecs/video_decoder_factory.h"
+#include "third_party/webrtc/api/video_codecs/video_encoder_factory.h"
+
+namespace media {
+class GpuVideoAcceleratorFactories;
+}
+
+namespace blink {
+
+// TODO(crbug.com/787254): Remove these APIs when their clients are Onion
+// souped.
+BLINK_PLATFORM_EXPORT std::unique_ptr<webrtc::VideoEncoderFactory>
+CreateWebrtcVideoEncoderFactory(
+    media::GpuVideoAcceleratorFactories* gpu_factories);
+BLINK_PLATFORM_EXPORT std::unique_ptr<webrtc::VideoDecoderFactory>
+CreateWebrtcVideoDecoderFactory(
+    media::GpuVideoAcceleratorFactories* gpu_factories);
+
+}  // namespace blink
+
+#endif  // THIRD_PARTY_BLINK_PUBLIC_PLATFORM_MODULES_PEERCONNECTION_VIDEO_CODEC_FACTORY_H_
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h
index 414aff9..cd95729 100644
--- a/third_party/blink/public/platform/platform.h
+++ b/third_party/blink/public/platform/platform.h
@@ -126,6 +126,7 @@
 class WebMediaCapabilitiesClient;
 class WebPrescientNetworking;
 class WebPublicSuffixList;
+class WebRtcAudioDeviceImpl;
 class WebRTCCertificateGenerator;
 class WebRTCPeerConnectionHandler;
 class WebRTCPeerConnectionHandlerClient;
@@ -630,6 +631,10 @@
     return media::AudioLatency::LATENCY_PLAYBACK;
   }
 
+  virtual blink::WebRtcAudioDeviceImpl* GetWebRtcAudioDevice() {
+    return nullptr;
+  }
+
   virtual base::Optional<std::string> GetWebRTCAudioProcessingConfiguration() {
     return base::nullopt;
   }
@@ -645,8 +650,6 @@
 
   virtual bool IsWebRtcEncryptionEnabled() { return true; }
 
-  virtual bool IsWebRtcStunOriginEnabled() { return false; }
-
   virtual base::Optional<std::string> WebRtcStunProbeTrialParameter() {
     return base::nullopt;
   }
diff --git a/third_party/blink/public/platform/web_runtime_features.h b/third_party/blink/public/platform/web_runtime_features.h
index c559be49..2d1bab79 100644
--- a/third_party/blink/public/platform/web_runtime_features.h
+++ b/third_party/blink/public/platform/web_runtime_features.h
@@ -226,7 +226,7 @@
   BLINK_PLATFORM_EXPORT static void EnableTranslateService(bool);
   BLINK_PLATFORM_EXPORT static void EnableMergeBlockingNonBlockingPools(bool);
   BLINK_PLATFORM_EXPORT static void EnableGetDisplayMedia(bool);
-  BLINK_PLATFORM_EXPORT static void EnableForbidSyncXHRInPageDismissal(bool);
+  BLINK_PLATFORM_EXPORT static void EnableAllowSyncXHRInPageDismissal(bool);
   BLINK_PLATFORM_EXPORT static void EnableShadowDOMV0(bool);
   BLINK_PLATFORM_EXPORT static void EnableCustomElementsV0(bool);
   BLINK_PLATFORM_EXPORT static void EnableHTMLImports(bool);
diff --git a/third_party/blink/public/web/modules/peerconnection/DEPS b/third_party/blink/public/web/modules/peerconnection/DEPS
deleted file mode 100644
index 1db93ebc..0000000
--- a/third_party/blink/public/web/modules/peerconnection/DEPS
+++ /dev/null
@@ -1,9 +0,0 @@
-include_rules = [
-    # TODO(crbug.com/787254): Remove the use of base::MessageLoopCurrent.
-    "+base/message_loop/message_loop_current.h",
-
-    # TODO(crbug.com/787254): Replace base::SequenceChecker by base::ThreadChecker.
-    "+base/sequence_checker.h",
-    "+base/single_thread_task_runner.h",
-    "+base/threading/thread.h",
-]
diff --git a/third_party/blink/public/web/web_embedded_worker.h b/third_party/blink/public/web/web_embedded_worker.h
index 724e63c..c3fd121 100644
--- a/third_party/blink/public/web/web_embedded_worker.h
+++ b/third_party/blink/public/web/web_embedded_worker.h
@@ -64,8 +64,6 @@
   // instance of WebEmbeddedWorker.
   static std::unique_ptr<WebEmbeddedWorker> Create(
       WebServiceWorkerContextClient*,
-      std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>,
-      mojo::ScopedMessagePipeHandle content_settings_handle,
       mojo::ScopedMessagePipeHandle cache_storage,
       mojo::ScopedMessagePipeHandle interface_provider,
       mojo::ScopedMessagePipeHandle browser_interface_broker);
@@ -73,9 +71,12 @@
   virtual ~WebEmbeddedWorker() = default;
 
   // Starts and terminates WorkerThread and WorkerGlobalScope.
-  virtual void StartWorkerContext(const WebEmbeddedWorkerStartData&,
-                                  scoped_refptr<base::SingleThreadTaskRunner>
-                                      initiator_thread_task_runner) = 0;
+  virtual void StartWorkerContext(
+      const WebEmbeddedWorkerStartData&,
+      std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>,
+      mojo::ScopedMessagePipeHandle content_settings_handle,
+      scoped_refptr<base::SingleThreadTaskRunner>
+          initiator_thread_task_runner) = 0;
   virtual void TerminateWorkerContext() = 0;
 
   // Resumes starting a worker startup that was paused via
diff --git a/third_party/blink/public/web/web_print_scaling_option.h b/third_party/blink/public/web/web_print_scaling_option.h
index 379a60a..044bde7b 100644
--- a/third_party/blink/public/web/web_print_scaling_option.h
+++ b/third_party/blink/public/web/web_print_scaling_option.h
@@ -43,7 +43,9 @@
   kWebPrintScalingOptionSourceSize,  // Print output page size is same as the
                                      // actual source page size. Do not
                                      // scale/center/fit to printable area.
-  kWebPrintScalingOptionLast = kWebPrintScalingOptionSourceSize
+  kWebPrintScalingOptionFitToPaper,  // Reduces or enlarges each page to fit the
+                                     // selected printer paper size.
+  kWebPrintScalingOptionLast = kWebPrintScalingOptionFitToPaper
 };
 
 }  // namespace blink
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc b/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc
index 7d2d37f..a173b893 100644
--- a/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc
+++ b/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc
@@ -222,7 +222,7 @@
   }
 
   if (!this->IsPaintable() || Size().IsEmpty()) {
-    error_msg << "The size of " << object_name << " iz zero.";
+    error_msg << "The size of " << object_name << " is zero.";
     exception_state.ThrowDOMException(DOMExceptionCode::kIndexSizeError,
                                       error_msg.str().c_str());
     return ScriptPromise();
diff --git a/third_party/blink/renderer/core/html/resources/controls_refresh.css b/third_party/blink/renderer/core/html/resources/controls_refresh.css
index 91f07b66..5982d59 100644
--- a/third_party/blink/renderer/core/html/resources/controls_refresh.css
+++ b/third_party/blink/renderer/core/html/resources/controls_refresh.css
@@ -63,7 +63,6 @@
 
 input[type="password" i]::-internal-reveal:hover,
 input[type="password" i]::-internal-reveal:focus {
-  background-color: #F7F7F7;
   border-radius: 1px;
   cursor: pointer;
 }
diff --git a/third_party/blink/renderer/core/html/resources/images/password_reveal_off.svg b/third_party/blink/renderer/core/html/resources/images/password_reveal_off.svg
index 0ced2be5f..4d3beff6 100644
--- a/third_party/blink/renderer/core/html/resources/images/password_reveal_off.svg
+++ b/third_party/blink/renderer/core/html/resources/images/password_reveal_off.svg
@@ -1,4 +1,4 @@
 <svg width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">

-<path d="M10 4C10.7812 4 11.5417 4.10156 12.2812 4.30469C13.0208 4.50781 13.7292 4.78906 14.4062 5.14844C15.0885 5.5026 15.7292 5.92448 16.3281 6.41406C16.9323 6.90365 17.4896 7.43229 18 8C17.4896 8.57292 16.9323 9.10417 16.3281 9.59375C15.7292 10.0781 15.0885 10.5 14.4062 10.8594C13.7292 11.2135 13.0208 11.4922 12.2812 11.6953C11.5417 11.8984 10.7812 12 10 12C9.21875 12 8.45833 11.8984 7.71875 11.6953C6.97917 11.4922 6.26823 11.2135 5.58594 10.8594C4.90885 10.5 4.26823 10.0781 3.66406 9.59375C3.0599 9.10417 2.50521 8.57292 2 8C2.50521 7.43229 3.0599 6.90365 3.66406 6.41406C4.26823 5.92448 4.90885 5.5026 5.58594 5.14844C6.26823 4.78906 6.97917 4.50781 7.71875 4.30469C8.45833 4.10156 9.21875 4 10 4ZM13 8C13 7.58854 12.9193 7.20052 12.7578 6.83594C12.6016 6.47135 12.388 6.15365 12.1172 5.88281C11.8464 5.61198 11.5286 5.39844 11.1641 5.24219C10.7995 5.08073 10.4115 5 10 5C9.58854 5 9.20052 5.08073 8.83594 5.24219C8.47135 5.39844 8.15365 5.61198 7.88281 5.88281C7.61198 6.15365 7.39583 6.47135 7.23438 6.83594C7.07812 7.20052 7 7.58854 7 8C7 8.41146 7.07812 8.79948 7.23438 9.16406C7.39583 9.52865 7.61198 9.84635 7.88281 10.1172C8.15365 10.388 8.47135 10.6042 8.83594 10.7656C9.20052 10.9219 9.58854 11 10 11C10.4115 11 10.7995 10.9219 11.1641 10.7656C11.5286 10.6042 11.8464 10.388 12.1172 10.1172C12.388 9.84635 12.6016 9.52865 12.7578 9.16406C12.9193 8.79948 13 8.41146 13 8ZM3.38281 8C3.8724 8.47396 4.39323 8.90885 4.94531 9.30469C5.4974 9.69531 6.08854 10.0234 6.71875 10.2891C6.48438 9.95573 6.30469 9.59375 6.17969 9.20312C6.0599 8.80729 6 8.40625 6 8C6 7.59375 6.0599 7.19531 6.17969 6.80469C6.30469 6.40885 6.48438 6.04427 6.71875 5.71094C6.08854 5.97656 5.4974 6.30729 4.94531 6.70312C4.39323 7.09375 3.8724 7.52604 3.38281 8ZM13.2812 10.2891C13.9115 10.0234 14.5026 9.69531 15.0547 9.30469C15.6068 8.90885 16.1276 8.47396 16.6172 8C16.1276 7.52604 15.6068 7.09375 15.0547 6.70312C14.5026 6.30729 13.9115 5.97656 13.2812 5.71094C13.5156 6.04427 13.6927 6.40885 13.8125 6.80469C13.9375 7.19531 14 7.59375 14 8C14 8.40625 13.9375 8.80729 13.8125 9.20312C13.6927 9.59375 13.5156 9.95573 13.2812 10.2891ZM10 9C9.85938 9 9.72917 8.97396 9.60938 8.92188C9.48958 8.86979 9.38281 8.79948 9.28906 8.71094C9.20052 8.61719 9.13021 8.51042 9.07812 8.39062C9.02604 8.27083 9 8.14062 9 8C9 7.85938 9.02604 7.72917 9.07812 7.60938C9.13021 7.48958 9.20052 7.38542 9.28906 7.29688C9.38281 7.20312 9.48958 7.13021 9.60938 7.07812C9.72917 7.02604 9.85938 7 10 7C10.1406 7 10.2708 7.02604 10.3906 7.07812C10.5104 7.13021 10.6146 7.20312 10.7031 7.29688C10.7969 7.38542 10.8698 7.48958 10.9219 7.60938C10.974 7.72917 11 7.85938 11 8C11 8.14062 10.974 8.27083 10.9219 8.39062C10.8698 8.51042 10.7969 8.61719 10.7031 8.71094C10.6146 8.79948 10.5104 8.86979 10.3906 8.92188C10.2708 8.97396 10.1406 9 10 9Z" fill="black"/>

-<line x1="3.36031" y1="14.5754" x2="17.3603" y2="0.575402" stroke="black"/>

+<path d="M10 4C10.7812 4 11.5417 4.10156 12.2812 4.30469C13.0208 4.50781 13.7292 4.78906 14.4062 5.14844C15.0885 5.5026 15.7292 5.92448 16.3281 6.41406C16.9323 6.90365 17.4896 7.43229 18 8C17.4896 8.57292 16.9323 9.10417 16.3281 9.59375C15.7292 10.0781 15.0885 10.5 14.4062 10.8594C13.7292 11.2135 13.0208 11.4922 12.2812 11.6953C11.5417 11.8984 10.7812 12 10 12C9.21875 12 8.45833 11.8984 7.71875 11.6953C6.97917 11.4922 6.26823 11.2135 5.58594 10.8594C4.90885 10.5 4.26823 10.0781 3.66406 9.59375C3.0599 9.10417 2.50521 8.57292 2 8C2.50521 7.43229 3.0599 6.90365 3.66406 6.41406C4.26823 5.92448 4.90885 5.5026 5.58594 5.14844C6.26823 4.78906 6.97917 4.50781 7.71875 4.30469C8.45833 4.10156 9.21875 4 10 4ZM13 8C13 7.58854 12.9193 7.20052 12.7578 6.83594C12.6016 6.47135 12.388 6.15365 12.1172 5.88281C11.8464 5.61198 11.5286 5.39844 11.1641 5.24219C10.7995 5.08073 10.4115 5 10 5C9.58854 5 9.20052 5.08073 8.83594 5.24219C8.47135 5.39844 8.15365 5.61198 7.88281 5.88281C7.61198 6.15365 7.39583 6.47135 7.23438 6.83594C7.07812 7.20052 7 7.58854 7 8C7 8.41146 7.07812 8.79948 7.23438 9.16406C7.39583 9.52865 7.61198 9.84635 7.88281 10.1172C8.15365 10.388 8.47135 10.6042 8.83594 10.7656C9.20052 10.9219 9.58854 11 10 11C10.4115 11 10.7995 10.9219 11.1641 10.7656C11.5286 10.6042 11.8464 10.388 12.1172 10.1172C12.388 9.84635 12.6016 9.52865 12.7578 9.16406C12.9193 8.79948 13 8.41146 13 8ZM3.38281 8C3.8724 8.47396 4.39323 8.90885 4.94531 9.30469C5.4974 9.69531 6.08854 10.0234 6.71875 10.2891C6.48438 9.95573 6.30469 9.59375 6.17969 9.20312C6.0599 8.80729 6 8.40625 6 8C6 7.59375 6.0599 7.19531 6.17969 6.80469C6.30469 6.40885 6.48438 6.04427 6.71875 5.71094C6.08854 5.97656 5.4974 6.30729 4.94531 6.70312C4.39323 7.09375 3.8724 7.52604 3.38281 8ZM13.2812 10.2891C13.9115 10.0234 14.5026 9.69531 15.0547 9.30469C15.6068 8.90885 16.1276 8.47396 16.6172 8C16.1276 7.52604 15.6068 7.09375 15.0547 6.70312C14.5026 6.30729 13.9115 5.97656 13.2812 5.71094C13.5156 6.04427 13.6927 6.40885 13.8125 6.80469C13.9375 7.19531 14 7.59375 14 8C14 8.40625 13.9375 8.80729 13.8125 9.20312C13.6927 9.59375 13.5156 9.95573 13.2812 10.2891ZM10 9C9.85938 9 9.72917 8.97396 9.60938 8.92188C9.48958 8.86979 9.38281 8.79948 9.28906 8.71094C9.20052 8.61719 9.13021 8.51042 9.07812 8.39062C9.02604 8.27083 9 8.14062 9 8C9 7.85938 9.02604 7.72917 9.07812 7.60938C9.13021 7.48958 9.20052 7.38542 9.28906 7.29688C9.38281 7.20312 9.48958 7.13021 9.60938 7.07812C9.72917 7.02604 9.85938 7 10 7C10.1406 7 10.2708 7.02604 10.3906 7.07812C10.5104 7.13021 10.6146 7.20312 10.7031 7.29688C10.7969 7.38542 10.8698 7.48958 10.9219 7.60938C10.974 7.72917 11 7.85938 11 8C11 8.14062 10.974 8.27083 10.9219 8.39062C10.8698 8.51042 10.7969 8.61719 10.7031 8.71094C10.6146 8.79948 10.5104 8.86979 10.3906 8.92188C10.2708 8.97396 10.1406 9 10 9Z" fill="WindowText"/>

+<line x1="3.36031" y1="14.5754" x2="17.3603" y2="0.575402" stroke="WindowText"/>

 </svg>
\ No newline at end of file
diff --git a/third_party/blink/renderer/core/html/resources/images/password_reveal_on.svg b/third_party/blink/renderer/core/html/resources/images/password_reveal_on.svg
index f7134a9a..50d5c0d 100644
--- a/third_party/blink/renderer/core/html/resources/images/password_reveal_on.svg
+++ b/third_party/blink/renderer/core/html/resources/images/password_reveal_on.svg
@@ -1,3 +1,3 @@
 <svg width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">

-<path d="M10 4C10.7812 4 11.5417 4.10156 12.2812 4.30469C13.0208 4.50781 13.7292 4.78906 14.4062 5.14844C15.0885 5.5026 15.7292 5.92448 16.3281 6.41406C16.9323 6.90365 17.4896 7.43229 18 8C17.4896 8.57292 16.9323 9.10417 16.3281 9.59375C15.7292 10.0781 15.0885 10.5 14.4062 10.8594C13.7292 11.2135 13.0208 11.4922 12.2812 11.6953C11.5417 11.8984 10.7812 12 10 12C9.21875 12 8.45833 11.8984 7.71875 11.6953C6.97917 11.4922 6.26823 11.2135 5.58594 10.8594C4.90885 10.5 4.26823 10.0781 3.66406 9.59375C3.0599 9.10417 2.50521 8.57292 2 8C2.50521 7.43229 3.0599 6.90365 3.66406 6.41406C4.26823 5.92448 4.90885 5.5026 5.58594 5.14844C6.26823 4.78906 6.97917 4.50781 7.71875 4.30469C8.45833 4.10156 9.21875 4 10 4ZM13 8C13 7.58854 12.9193 7.20052 12.7578 6.83594C12.6016 6.47135 12.388 6.15365 12.1172 5.88281C11.8464 5.61198 11.5286 5.39844 11.1641 5.24219C10.7995 5.08073 10.4115 5 10 5C9.58854 5 9.20052 5.08073 8.83594 5.24219C8.47135 5.39844 8.15365 5.61198 7.88281 5.88281C7.61198 6.15365 7.39583 6.47135 7.23438 6.83594C7.07812 7.20052 7 7.58854 7 8C7 8.41146 7.07812 8.79948 7.23438 9.16406C7.39583 9.52865 7.61198 9.84635 7.88281 10.1172C8.15365 10.388 8.47135 10.6042 8.83594 10.7656C9.20052 10.9219 9.58854 11 10 11C10.4115 11 10.7995 10.9219 11.1641 10.7656C11.5286 10.6042 11.8464 10.388 12.1172 10.1172C12.388 9.84635 12.6016 9.52865 12.7578 9.16406C12.9193 8.79948 13 8.41146 13 8ZM3.38281 8C3.8724 8.47396 4.39323 8.90885 4.94531 9.30469C5.4974 9.69531 6.08854 10.0234 6.71875 10.2891C6.48438 9.95573 6.30469 9.59375 6.17969 9.20312C6.0599 8.80729 6 8.40625 6 8C6 7.59375 6.0599 7.19531 6.17969 6.80469C6.30469 6.40885 6.48438 6.04427 6.71875 5.71094C6.08854 5.97656 5.4974 6.30729 4.94531 6.70312C4.39323 7.09375 3.8724 7.52604 3.38281 8ZM13.2812 10.2891C13.9115 10.0234 14.5026 9.69531 15.0547 9.30469C15.6068 8.90885 16.1276 8.47396 16.6172 8C16.1276 7.52604 15.6068 7.09375 15.0547 6.70312C14.5026 6.30729 13.9115 5.97656 13.2812 5.71094C13.5156 6.04427 13.6927 6.40885 13.8125 6.80469C13.9375 7.19531 14 7.59375 14 8C14 8.40625 13.9375 8.80729 13.8125 9.20312C13.6927 9.59375 13.5156 9.95573 13.2812 10.2891ZM10 9C9.85938 9 9.72917 8.97396 9.60938 8.92188C9.48958 8.86979 9.38281 8.79948 9.28906 8.71094C9.20052 8.61719 9.13021 8.51042 9.07812 8.39062C9.02604 8.27083 9 8.14062 9 8C9 7.85938 9.02604 7.72917 9.07812 7.60938C9.13021 7.48958 9.20052 7.38542 9.28906 7.29688C9.38281 7.20312 9.48958 7.13021 9.60938 7.07812C9.72917 7.02604 9.85938 7 10 7C10.1406 7 10.2708 7.02604 10.3906 7.07812C10.5104 7.13021 10.6146 7.20312 10.7031 7.29688C10.7969 7.38542 10.8698 7.48958 10.9219 7.60938C10.974 7.72917 11 7.85938 11 8C11 8.14062 10.974 8.27083 10.9219 8.39062C10.8698 8.51042 10.7969 8.61719 10.7031 8.71094C10.6146 8.79948 10.5104 8.86979 10.3906 8.92188C10.2708 8.97396 10.1406 9 10 9Z" fill="black"/>

+<path d="M10 4C10.7812 4 11.5417 4.10156 12.2812 4.30469C13.0208 4.50781 13.7292 4.78906 14.4062 5.14844C15.0885 5.5026 15.7292 5.92448 16.3281 6.41406C16.9323 6.90365 17.4896 7.43229 18 8C17.4896 8.57292 16.9323 9.10417 16.3281 9.59375C15.7292 10.0781 15.0885 10.5 14.4062 10.8594C13.7292 11.2135 13.0208 11.4922 12.2812 11.6953C11.5417 11.8984 10.7812 12 10 12C9.21875 12 8.45833 11.8984 7.71875 11.6953C6.97917 11.4922 6.26823 11.2135 5.58594 10.8594C4.90885 10.5 4.26823 10.0781 3.66406 9.59375C3.0599 9.10417 2.50521 8.57292 2 8C2.50521 7.43229 3.0599 6.90365 3.66406 6.41406C4.26823 5.92448 4.90885 5.5026 5.58594 5.14844C6.26823 4.78906 6.97917 4.50781 7.71875 4.30469C8.45833 4.10156 9.21875 4 10 4ZM13 8C13 7.58854 12.9193 7.20052 12.7578 6.83594C12.6016 6.47135 12.388 6.15365 12.1172 5.88281C11.8464 5.61198 11.5286 5.39844 11.1641 5.24219C10.7995 5.08073 10.4115 5 10 5C9.58854 5 9.20052 5.08073 8.83594 5.24219C8.47135 5.39844 8.15365 5.61198 7.88281 5.88281C7.61198 6.15365 7.39583 6.47135 7.23438 6.83594C7.07812 7.20052 7 7.58854 7 8C7 8.41146 7.07812 8.79948 7.23438 9.16406C7.39583 9.52865 7.61198 9.84635 7.88281 10.1172C8.15365 10.388 8.47135 10.6042 8.83594 10.7656C9.20052 10.9219 9.58854 11 10 11C10.4115 11 10.7995 10.9219 11.1641 10.7656C11.5286 10.6042 11.8464 10.388 12.1172 10.1172C12.388 9.84635 12.6016 9.52865 12.7578 9.16406C12.9193 8.79948 13 8.41146 13 8ZM3.38281 8C3.8724 8.47396 4.39323 8.90885 4.94531 9.30469C5.4974 9.69531 6.08854 10.0234 6.71875 10.2891C6.48438 9.95573 6.30469 9.59375 6.17969 9.20312C6.0599 8.80729 6 8.40625 6 8C6 7.59375 6.0599 7.19531 6.17969 6.80469C6.30469 6.40885 6.48438 6.04427 6.71875 5.71094C6.08854 5.97656 5.4974 6.30729 4.94531 6.70312C4.39323 7.09375 3.8724 7.52604 3.38281 8ZM13.2812 10.2891C13.9115 10.0234 14.5026 9.69531 15.0547 9.30469C15.6068 8.90885 16.1276 8.47396 16.6172 8C16.1276 7.52604 15.6068 7.09375 15.0547 6.70312C14.5026 6.30729 13.9115 5.97656 13.2812 5.71094C13.5156 6.04427 13.6927 6.40885 13.8125 6.80469C13.9375 7.19531 14 7.59375 14 8C14 8.40625 13.9375 8.80729 13.8125 9.20312C13.6927 9.59375 13.5156 9.95573 13.2812 10.2891ZM10 9C9.85938 9 9.72917 8.97396 9.60938 8.92188C9.48958 8.86979 9.38281 8.79948 9.28906 8.71094C9.20052 8.61719 9.13021 8.51042 9.07812 8.39062C9.02604 8.27083 9 8.14062 9 8C9 7.85938 9.02604 7.72917 9.07812 7.60938C9.13021 7.48958 9.20052 7.38542 9.28906 7.29688C9.38281 7.20312 9.48958 7.13021 9.60938 7.07812C9.72917 7.02604 9.85938 7 10 7C10.1406 7 10.2708 7.02604 10.3906 7.07812C10.5104 7.13021 10.6146 7.20312 10.7031 7.29688C10.7969 7.38542 10.8698 7.48958 10.9219 7.60938C10.974 7.72917 11 7.85938 11 8C11 8.14062 10.974 8.27083 10.9219 8.39062C10.8698 8.51042 10.7969 8.61719 10.7031 8.71094C10.6146 8.79948 10.5104 8.86979 10.3906 8.92188C10.2708 8.97396 10.1406 9 10 9Z" fill="WindowText"/>

 </svg>
\ No newline at end of file
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
index 5bb5078e..8740093f 100644
--- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
+++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -70,6 +70,7 @@
 #include "third_party/blink/renderer/platform/loader/fetch/resource.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_info.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.h b/third_party/blink/renderer/core/inspector/inspector_network_agent.h
index 9193e42..dba8a6d 100644
--- a/third_party/blink/renderer/core/inspector/inspector_network_agent.h
+++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.h
@@ -39,6 +39,7 @@
 #include "third_party/blink/renderer/core/inspector/inspector_base_agent.h"
 #include "third_party/blink/renderer/core/inspector/inspector_page_agent.h"
 #include "third_party/blink/renderer/core/inspector/protocol/Network.h"
+#include "third_party/blink/renderer/platform/blob/blob_data.h"
 #include "third_party/blink/renderer/platform/heap/handle.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
 #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -54,7 +55,6 @@
 
 namespace blink {
 
-class BlobDataHandle;
 class Document;
 class DocumentLoader;
 class ExecutionContext;
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
index 8ef8fa09..df4da61 100644
--- a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
+++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -37,6 +37,7 @@
 #include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
 #include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
 #include "third_party/blink/renderer/platform/weborigin/kurl.h"
diff --git a/third_party/blink/renderer/core/loader/resource/script_resource.cc b/third_party/blink/renderer/core/loader/resource/script_resource.cc
index 559e956..1e8c905 100644
--- a/third_party/blink/renderer/core/loader/resource/script_resource.cc
+++ b/third_party/blink/renderer/core/loader/resource/script_resource.cc
@@ -109,6 +109,18 @@
   return resource;
 }
 
+ScriptResource* ScriptResource::CreateForTest(
+    const KURL& url,
+    const WTF::TextEncoding& encoding) {
+  ResourceRequest request(url);
+  request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
+  ResourceLoaderOptions options;
+  TextResourceDecoderOptions decoder_options(
+      TextResourceDecoderOptions::kPlainTextContent, encoding);
+  return MakeGarbageCollected<ScriptResource>(request, options,
+                                              decoder_options);
+}
+
 ScriptResource::ScriptResource(
     const ResourceRequest& resource_request,
     const ResourceLoaderOptions& options,
diff --git a/third_party/blink/renderer/core/loader/resource/script_resource.h b/third_party/blink/renderer/core/loader/resource/script_resource.h
index 3025db0..4e31c0c 100644
--- a/third_party/blink/renderer/core/loader/resource/script_resource.h
+++ b/third_party/blink/renderer/core/loader/resource/script_resource.h
@@ -78,15 +78,7 @@
 
   // Public for testing
   static ScriptResource* CreateForTest(const KURL& url,
-                                       const WTF::TextEncoding& encoding) {
-    ResourceRequest request(url);
-    request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
-    ResourceLoaderOptions options;
-    TextResourceDecoderOptions decoder_options(
-        TextResourceDecoderOptions::kPlainTextContent, encoding);
-    return MakeGarbageCollected<ScriptResource>(request, options,
-                                                decoder_options);
-  }
+                                       const WTF::TextEncoding& encoding);
 
   ScriptResource(const ResourceRequest&,
                  const ResourceLoaderOptions&,
diff --git a/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc b/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc
index 164aeac..d003626 100644
--- a/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc
+++ b/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc
@@ -71,6 +71,14 @@
         WebString(base_url_), test::CoreTestDataPath(), WebString(file_name));
   }
 
+  uint32_t GetMainThreadScrollingReasons(const GraphicsLayer& layer) const {
+    const auto* scroll = layer.GetPropertyTreeState()
+                             .Transform()
+                             .NearestScrollTranslationNode()
+                             .ScrollNode();
+    return scroll->GetMainThreadScrollingReasons();
+  }
+
   uint32_t GetViewMainThreadScrollingReasons() const {
     const auto* scroll = GetFrame()
                              ->View()
@@ -135,7 +143,7 @@
   cc::Layer* cc_scroll_layer = scroll_layer->CcLayer();
   ASSERT_TRUE(cc_scroll_layer->scrollable());
   ASSERT_TRUE(
-      cc_scroll_layer->GetMainThreadScrollingReasons() &
+      GetMainThreadScrollingReasons(*scroll_layer) &
       cc::MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects);
 
   // Remove fixed background-attachment should make the iframe
@@ -157,7 +165,7 @@
   cc_scroll_layer = scroll_layer->CcLayer();
   ASSERT_TRUE(cc_scroll_layer->scrollable());
   ASSERT_FALSE(
-      cc_scroll_layer->GetMainThreadScrollingReasons() &
+      GetMainThreadScrollingReasons(*scroll_layer) &
       cc::MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects);
 
   // Force main frame to scroll on main thread. All its descendants
@@ -180,7 +188,7 @@
   cc_scroll_layer = scroll_layer->CcLayer();
   ASSERT_TRUE(cc_scroll_layer->scrollable());
   ASSERT_TRUE(
-      cc_scroll_layer->GetMainThreadScrollingReasons() &
+      GetMainThreadScrollingReasons(*scroll_layer) &
       cc::MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects);
 }
 
@@ -232,10 +240,11 @@
   EXPECT_TRUE(GetViewMainThreadScrollingReasons());
 
   // Main scrolling should also propagate to inner viewport layer.
-  cc::Layer* inner_viewport_scroll_layer =
-      GetFrame()->GetPage()->GetVisualViewport().ScrollLayer()->CcLayer();
-  ASSERT_TRUE(inner_viewport_scroll_layer->scrollable());
-  EXPECT_TRUE(inner_viewport_scroll_layer->GetMainThreadScrollingReasons());
+  const auto& visual_viewport_scroll_graphics_layer =
+      *GetFrame()->GetPage()->GetVisualViewport().ScrollLayer();
+  ASSERT_TRUE(visual_viewport_scroll_graphics_layer.CcLayer()->scrollable());
+  EXPECT_TRUE(
+      GetMainThreadScrollingReasons(visual_viewport_scroll_graphics_layer));
 }
 
 TEST_F(MainThreadScrollingReasonsTest, FastScrollingForFixedPosition) {
@@ -264,10 +273,11 @@
   // Fast scrolling should be enabled by default.
   EXPECT_FALSE(GetViewMainThreadScrollingReasons());
 
-  cc::Layer* inner_viewport_scroll_layer =
-      GetFrame()->GetPage()->GetVisualViewport().ScrollLayer()->CcLayer();
-  ASSERT_TRUE(inner_viewport_scroll_layer->scrollable());
-  EXPECT_FALSE(inner_viewport_scroll_layer->GetMainThreadScrollingReasons());
+  const auto& visual_viewport_scroll_graphics_layer =
+      *GetFrame()->GetPage()->GetVisualViewport().ScrollLayer();
+  ASSERT_TRUE(visual_viewport_scroll_graphics_layer.CcLayer()->scrollable());
+  EXPECT_FALSE(
+      GetMainThreadScrollingReasons(visual_viewport_scroll_graphics_layer));
 }
 
 TEST_F(MainThreadScrollingReasonsTest,
@@ -291,9 +301,8 @@
   ASSERT_TRUE(scrollbar_graphics_layer);
 
   bool has_cc_scrollbar_layer = !scrollbar_graphics_layer->DrawsContent();
-  EXPECT_TRUE(
-      has_cc_scrollbar_layer ||
-      scrollbar_graphics_layer->CcLayer()->GetMainThreadScrollingReasons());
+  EXPECT_TRUE(has_cc_scrollbar_layer ||
+              GetMainThreadScrollingReasons(*scrollbar_graphics_layer));
 }
 
 class NonCompositedMainThreadScrollingReasonsTest
diff --git a/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc b/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc
index 098cad0..d00dbe6 100644
--- a/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc
+++ b/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc
@@ -118,12 +118,6 @@
         WebString::FromUTF8(file_name));
   }
 
-  cc::Layer* GetRootScrollLayer() {
-    GraphicsLayer* layer =
-        GetFrame()->View()->LayoutViewport()->LayerForScrolling();
-    return layer ? layer->CcLayer() : nullptr;
-  }
-
   WebViewImpl* GetWebView() const { return helper_.GetWebView(); }
   LocalFrame* GetFrame() const { return helper_.LocalMainFrame()->GetFrame(); }
   frame_test_helpers::TestWebWidgetClient* GetWidgetClient() const {
@@ -132,6 +126,14 @@
 
   void LoadAhem() { helper_.LoadAhem(); }
 
+  bool HasMainThreadScrollingReasons(const GraphicsLayer& layer) const {
+    const auto* scroll = layer.GetPropertyTreeState()
+                             .Transform()
+                             .NearestScrollTranslationNode()
+                             .ScrollNode();
+    return scroll->GetMainThreadScrollingReasons();
+  }
+
  protected:
   std::string base_url_;
 
@@ -158,10 +160,11 @@
       frame_view));
 
   // Fast scrolling should be enabled by default.
-  cc::Layer* root_scroll_layer = GetRootScrollLayer();
-  ASSERT_TRUE(root_scroll_layer);
-  ASSERT_TRUE(root_scroll_layer->scrollable());
-  ASSERT_FALSE(root_scroll_layer->GetMainThreadScrollingReasons());
+  const auto& root_scroll_graphics_layer =
+      *GetFrame()->View()->LayoutViewport()->LayerForScrolling();
+  EXPECT_FALSE(HasMainThreadScrollingReasons(root_scroll_graphics_layer));
+  EXPECT_TRUE(root_scroll_graphics_layer.CcLayer()->scrollable());
+
   ASSERT_EQ(cc::EventListenerProperties::kNone,
             GetWidgetClient()->EventListenerProperties(
                 cc::EventListenerClass::kTouchStartOrMove));
@@ -169,10 +172,11 @@
             GetWidgetClient()->EventListenerProperties(
                 cc::EventListenerClass::kMouseWheel));
 
-  cc::Layer* inner_viewport_scroll_layer =
-      page->GetVisualViewport().ScrollLayer()->CcLayer();
-  ASSERT_TRUE(inner_viewport_scroll_layer->scrollable());
-  ASSERT_FALSE(inner_viewport_scroll_layer->GetMainThreadScrollingReasons());
+  const auto& inner_viewport_scroll_graphics_layer =
+      *page->GetVisualViewport().ScrollLayer();
+  EXPECT_FALSE(
+      HasMainThreadScrollingReasons(inner_viewport_scroll_graphics_layer));
+  EXPECT_TRUE(inner_viewport_scroll_graphics_layer.CcLayer()->scrollable());
 }
 
 TEST_P(ScrollingCoordinatorTest, fastFractionalScrollingDiv) {
@@ -214,10 +218,9 @@
   NavigateTo(base_url_ + "fixed-position.html");
   ForceFullCompositingUpdate();
 
-  // Fixed position should not fall back to main thread scrolling.
-  cc::Layer* root_scroll_layer = GetRootScrollLayer();
-  ASSERT_TRUE(root_scroll_layer);
-  ASSERT_FALSE(root_scroll_layer->GetMainThreadScrollingReasons());
+  const auto& root_scroll_layer =
+      *GetFrame()->View()->LayoutViewport()->LayerForScrolling();
+  EXPECT_FALSE(HasMainThreadScrollingReasons(root_scroll_layer));
 }
 
 // Sticky constraints are stored on transform property tree nodes.
@@ -234,9 +237,9 @@
   ForceFullCompositingUpdate();
 
   // Sticky position should not fall back to main thread scrolling.
-  cc::Layer* root_scroll_layer = GetRootScrollLayer();
-  ASSERT_TRUE(root_scroll_layer);
-  EXPECT_FALSE(root_scroll_layer->GetMainThreadScrollingReasons());
+  const auto& root_scroll_layer =
+      *GetFrame()->View()->LayoutViewport()->LayerForScrolling();
+  EXPECT_FALSE(HasMainThreadScrollingReasons(root_scroll_layer));
 
   Document* document = GetFrame()->GetDocument();
   {
@@ -455,9 +458,10 @@
   NavigateTo(base_url_ + "clipped-body.html");
   ForceFullCompositingUpdate();
 
-  cc::Layer* root_scroll_layer = GetRootScrollLayer();
-  ASSERT_TRUE(root_scroll_layer);
-  EXPECT_TRUE(root_scroll_layer->non_fast_scrollable_region().IsEmpty());
+  const auto* root_scroll_layer =
+      GetFrame()->View()->LayoutViewport()->LayerForScrolling();
+  EXPECT_TRUE(
+      root_scroll_layer->CcLayer()->non_fast_scrollable_region().IsEmpty());
 }
 
 TEST_P(ScrollingCoordinatorTest, touchAction) {
diff --git a/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc b/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc
index fc37662..5a60df4 100644
--- a/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc
+++ b/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc
@@ -2106,7 +2106,8 @@
 }
 
 GraphicsLayer* CompositedLayerMapping::DetachLayerForOverflowControls() {
-  overflow_controls_host_layer_->RemoveFromParent();
+  if (overflow_controls_host_layer_)
+    overflow_controls_host_layer_->RemoveFromParent();
   return overflow_controls_host_layer_.get();
 }
 
diff --git a/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc b/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc
index 5f8352f5..785130b 100644
--- a/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc
+++ b/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc
@@ -1782,4 +1782,16 @@
   EXPECT_TRUE(mapping->MainGraphicsLayer()->ContentsOpaque());
 }
 
+TEST_F(CompositedLayerMappingTest, NullOverflowControlsHostLayer) {
+  if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+    return;
+
+  SetHtmlInnerHTML("<div id='target' style='will-change: transform'></div>");
+  CompositedLayerMapping* mapping =
+      ToLayoutBoxModelObject(GetLayoutObjectByElementId("target"))
+          ->Layer()
+          ->GetCompositedLayerMapping();
+  EXPECT_FALSE(mapping->DetachLayerForOverflowControls());
+}
+
 }  // namespace blink
diff --git a/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc b/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc
index 084bd945..ed307876 100644
--- a/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc
+++ b/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc
@@ -137,10 +137,11 @@
                 return a.second < b.second;
               });
     for (auto& item : pending) {
-      this_layer_children.insert(item.second + offset,
-                                 item.first->GetCompositedLayerMapping()
-                                     ->DetachLayerForOverflowControls());
-      offset++;
+      if (auto* layer = item.first->GetCompositedLayerMapping()
+                            ->DetachLayerForOverflowControls()) {
+        this_layer_children.insert(item.second + offset, layer);
+        offset++;
+      }
     }
 
     if (!parented && !this_layer_children.IsEmpty()) {
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator.cc b/third_party/blink/renderer/core/scroll/scroll_animator.cc
index e6dcbbd..71ddd05 100644
--- a/third_party/blink/renderer/core/scroll/scroll_animator.cc
+++ b/third_party/blink/renderer/core/scroll/scroll_animator.cc
@@ -34,7 +34,6 @@
 
 #include "base/memory/scoped_refptr.h"
 #include "cc/animation/scroll_offset_animation_curve.h"
-#include "cc/input/main_thread_scrolling_reason.h"
 #include "cc/layers/picture_layer.h"
 #include "third_party/blink/public/platform/platform.h"
 #include "third_party/blink/renderer/core/scroll/scrollable_area.h"
@@ -44,14 +43,6 @@
 
 namespace blink {
 
-namespace {
-
-cc::PictureLayer* ToCcLayer(GraphicsLayer* layer) {
-  return layer ? layer->CcLayer() : nullptr;
-}
-
-}  // namespace
-
 ScrollAnimatorBase* ScrollAnimatorBase::Create(
     ScrollableArea* scrollable_area) {
   if (scrollable_area && scrollable_area->ScrollAnimatorEnabled())
@@ -275,14 +266,6 @@
   NotifyOffsetChanged();
 }
 
-void ScrollAnimator::PostAnimationCleanupAndReset() {
-  // Remove the temporary main thread scrolling reason that was added while
-  // main thread had scheduled an animation.
-  RemoveMainThreadScrollingReason();
-
-  ResetAnimationState();
-}
-
 bool ScrollAnimator::SendAnimationToCompositor() {
   if (scrollable_area_->ShouldScrollOnMainThread())
     return false;
@@ -319,14 +302,14 @@
   ScrollAnimatorCompositorCoordinator::UpdateCompositorAnimations();
 
   if (run_state_ == RunState::kPostAnimationCleanup) {
-    PostAnimationCleanupAndReset();
+    ResetAnimationState();
     return;
   }
 
   if (run_state_ == RunState::kWaitingToCancelOnCompositor) {
     DCHECK(compositor_animation_id());
     AbortAnimation();
-    PostAnimationCleanupAndReset();
+    ResetAnimationState();
     return;
   }
 
@@ -379,33 +362,6 @@
       if (running_on_main_thread)
         run_state_ = RunState::kRunningOnMainThread;
     }
-
-    // Main thread should deal with the scroll animations it started.
-    if (sent_to_compositor || running_on_main_thread)
-      AddMainThreadScrollingReason();
-    else
-      RemoveMainThreadScrollingReason();
-  }
-}
-
-void ScrollAnimator::AddMainThreadScrollingReason() {
-  // Usually main thread scrolling reasons should be updated from
-  // one frame to all its descendants. khandlingScrollFromMainThread
-  // is a special case because its subframes cannot be scrolled
-  // when the reason is set. When the subframes are ready to scroll
-  // the reason has benn reset.
-  if (cc::Layer* scroll_layer =
-          ToCcLayer(GetScrollableArea()->LayerForScrolling())) {
-    scroll_layer->AddMainThreadScrollingReasons(
-        cc::MainThreadScrollingReason::kHandlingScrollFromMainThread);
-  }
-}
-
-void ScrollAnimator::RemoveMainThreadScrollingReason() {
-  if (cc::Layer* scroll_layer =
-          ToCcLayer(GetScrollableArea()->LayerForScrolling())) {
-    scroll_layer->ClearMainThreadScrollingReasons(
-        cc::MainThreadScrollingReason::kHandlingScrollFromMainThread);
   }
 }
 
@@ -430,17 +386,12 @@
 }
 
 void ScrollAnimator::TakeOverCompositorAnimation() {
-  if (run_state_ == RunState::kRunningOnCompositor ||
-      run_state_ == RunState::kRunningOnCompositorButNeedsUpdate)
-    RemoveMainThreadScrollingReason();
-
   ScrollAnimatorCompositorCoordinator::TakeOverCompositorAnimation();
 }
 
 void ScrollAnimator::LayerForCompositedScrollingDidChange(
     CompositorAnimationTimeline* timeline) {
-  if (ReattachCompositorAnimationIfNeeded(timeline) && animation_curve_)
-    AddMainThreadScrollingReason();
+  ReattachCompositorAnimationIfNeeded(timeline);
 }
 
 bool ScrollAnimator::RegisterAndScheduleAnimation() {
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator.h b/third_party/blink/renderer/core/scroll/scroll_animator.h
index 110333f..364beb8 100644
--- a/third_party/blink/renderer/core/scroll/scroll_animator.h
+++ b/third_party/blink/renderer/core/scroll/scroll_animator.h
@@ -144,10 +144,6 @@
   bool RegisterAndScheduleAnimation();
 
   void CreateAnimationCurve();
-  void PostAnimationCleanupAndReset();
-
-  void AddMainThreadScrollingReason();
-  void RemoveMainThreadScrollingReason();
 
   // Returns true if will animate to the given target offset. Returns false
   // only when there is no animation running and we are not starting one
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image.cc b/third_party/blink/renderer/core/svg/graphics/svg_image.cc
index df77f0b..2a93c18 100644
--- a/third_party/blink/renderer/core/svg/graphics/svg_image.cc
+++ b/third_party/blink/renderer/core/svg/graphics/svg_image.cc
@@ -852,7 +852,7 @@
 }
 
 DarkModeClassification SVGImage::CheckTypeSpecificConditionsForDarkMode(
-    const FloatRect& src_rect,
+    const FloatRect& dest_rect,
     DarkModeImageClassifier* classifier) {
   classifier->SetImageType(DarkModeImageClassifier::ImageType::kSvg);
   return DarkModeClassification::kNotClassified;
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image.h b/third_party/blink/renderer/core/svg/graphics/svg_image.h
index e9daf5d..8dd7b4a 100644
--- a/third_party/blink/renderer/core/svg/graphics/svg_image.h
+++ b/third_party/blink/renderer/core/svg/graphics/svg_image.h
@@ -125,7 +125,7 @@
   PaintImage PaintImageForCurrentFrame() override;
 
   DarkModeClassification CheckTypeSpecificConditionsForDarkMode(
-      const FloatRect& src_rect,
+      const FloatRect& dest_rect,
       DarkModeImageClassifier* classifier) override;
 
  protected:
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h b/third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h
index 2d9a8e7..1e617991 100644
--- a/third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h
+++ b/third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h
@@ -89,9 +89,10 @@
   PaintImage PaintImageForCurrentFrame() override;
 
   DarkModeClassification CheckTypeSpecificConditionsForDarkMode(
-      const FloatRect& src_rect,
+      const FloatRect& dest_rect,
       DarkModeImageClassifier* classifier) override {
-    return image_->CheckTypeSpecificConditionsForDarkMode(src_rect, classifier);
+    return image_->CheckTypeSpecificConditionsForDarkMode(dest_rect,
+                                                          classifier);
   }
 
  protected:
diff --git a/third_party/blink/renderer/core/timing/performance.cc b/third_party/blink/renderer/core/timing/performance.cc
index 08e1d7e..124f629 100644
--- a/third_party/blink/renderer/core/timing/performance.cc
+++ b/third_party/blink/renderer/core/timing/performance.cc
@@ -65,6 +65,7 @@
 #include "third_party/blink/renderer/core/timing/profiler_init_options.h"
 #include "third_party/blink/renderer/core/timing/time_clamper.h"
 #include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
 #include "third_party/blink/renderer/platform/runtime_enabled_features.h"
diff --git a/third_party/blink/renderer/core/timing/performance_resource_timing.cc b/third_party/blink/renderer/core/timing/performance_resource_timing.cc
index 2ffba14..a9a5e3cf 100644
--- a/third_party/blink/renderer/core/timing/performance_resource_timing.cc
+++ b/third_party/blink/renderer/core/timing/performance_resource_timing.cc
@@ -36,6 +36,7 @@
 #include "third_party/blink/renderer/core/performance_entry_names.h"
 #include "third_party/blink/renderer/core/timing/performance.h"
 #include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
diff --git a/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc b/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc
index f92ccdd..40f5bb28 100644
--- a/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc
+++ b/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc
@@ -23,6 +23,7 @@
 
 #include <libxml/uri.h>
 #include <libxslt/xsltutils.h>
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
 #include "third_party/blink/renderer/core/dom/document.h"
 #include "third_party/blink/renderer/core/dom/node.h"
 #include "third_party/blink/renderer/core/dom/transform_source.h"
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
index ff1a3fb..6354e8ef 100644
--- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
+++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
@@ -1143,8 +1143,10 @@
       // Update histogram for usage of sync xhr within pagedismissal.
       auto pagedismissal = GetDocument()->PageDismissalEventBeingDispatched();
       if (pagedismissal != Document::kNoDismissal) {
-        // Disallow synchronous requests on page dismissal
-        if (RuntimeEnabledFeatures::ForbidSyncXHRInPageDismissalEnabled()) {
+        // Disallow synchronous requests on page dismissal unless enabled by
+        // origin trial or enterprise policy.
+        if (!RuntimeEnabledFeatures::AllowSyncXHRInPageDismissalEnabled(
+                &execution_context)) {
           UseCounter::Count(&execution_context,
                             WebFeature::kForbiddenSyncXhrInPageDismissal);
           DEFINE_STATIC_LOCAL(EnumerationHistogram,
diff --git a/third_party/blink/renderer/devtools/.eslintrc.js b/third_party/blink/renderer/devtools/.eslintrc.js
index 10cc7cb..401bb011 100644
--- a/third_party/blink/renderer/devtools/.eslintrc.js
+++ b/third_party/blink/renderer/devtools/.eslintrc.js
@@ -7,7 +7,8 @@
     },
 
     "parserOptions": {
-        "ecmaVersion": 9
+        "ecmaVersion": 9,
+        "sourceType": "module"
     },
 
     /**
diff --git a/third_party/blink/renderer/devtools/BUILD.gn b/third_party/blink/renderer/devtools/BUILD.gn
index 917c44c..c5386b70 100644
--- a/third_party/blink/renderer/devtools/BUILD.gn
+++ b/third_party/blink/renderer/devtools/BUILD.gn
@@ -786,7 +786,6 @@
   "front_end/toolbox.js",
   "front_end/toolbox.json",
   "front_end/ui/ActionRegistry.js",
-  "front_end/ui/ARIAUtils.js",
   "front_end/ui/checkboxTextLabel.css",
   "front_end/ui/closeButton.css",
   "front_end/ui/confirmDialog.css",
@@ -958,6 +957,12 @@
 
 all_devtools_files += lighthouse_locale_files
 
+all_devtools_modules = [
+  "front_end/root.js",
+  "front_end/ui/ARIAUtils.js",
+  "front_end/ui/ui.js",
+]
+
 devtools_test_files = [
   "//third_party/axe-core/axe.js",
   "front_end/accessibility_test_runner/AccessibilityPaneTestRunner.js",
@@ -1149,6 +1154,12 @@
   "front_end/worker_app.html",
 ]
 
+copied_devtools_modules = [
+  "$resources_out_dir/root.js",
+  "$resources_out_dir/ui/ARIAUtils.js",
+  "$resources_out_dir/ui/ui.js",
+]
+
 generated_applications = [
   "$resources_out_dir/audits_worker.js",
   "$resources_out_dir/devtools_app.html",
@@ -1267,7 +1278,7 @@
 visibility = [ "//third_party/blink/*" ]
 
 group("devtools_all_files") {
-  data = all_devtools_files
+  data = all_devtools_files + all_devtools_modules
   deps = [
     ":devtools_frontend_resources_data",
   ]
@@ -1284,6 +1295,7 @@
   ":devtools_extension_api",
   ":frontend_protocol_sources",
   ":supported_css_properties",
+  ":copy_devtools_modules",
 ]
 
 if (debug_devtools) {
@@ -1348,8 +1360,8 @@
   ]
 
   grd_files =
-      generated_applications + generated_non_autostart_non_remote_modules +
-      devtools_embedder_scripts +
+      all_devtools_modules + generated_applications +
+      generated_non_autostart_non_remote_modules + devtools_embedder_scripts +
       [ "$resources_out_dir/devtools_extension_api.js" ]
 
   # Bundle remote modules in ChromeOS.
@@ -1468,6 +1480,24 @@
          ]
 }
 
+action("copy_devtools_modules") {
+  script = "scripts/build/copy_devtools_modules.py"
+
+  deps = [
+    ":build_release_devtools",
+  ]
+
+  inputs = all_devtools_modules
+  outputs = copied_devtools_modules
+
+  args = all_devtools_modules + [
+           "--input_path",
+           rebase_path(".", root_build_dir),
+           "--output_path",
+           rebase_path(resources_out_dir, root_build_dir),
+         ]
+}
+
 if (debug_devtools) {
   resources_out_debug_dir = "$root_out_dir/resources/inspector/debug"
 
diff --git a/third_party/blink/renderer/devtools/PRESUBMIT.py b/third_party/blink/renderer/devtools/PRESUBMIT.py
index a59c8ec..b5dc9a0c 100644
--- a/third_party/blink/renderer/devtools/PRESUBMIT.py
+++ b/third_party/blink/renderer/devtools/PRESUBMIT.py
@@ -79,7 +79,7 @@
     # Also fix semicolon to avoid confusing clang-format.
     eslint_process = popen([
         local_node.node_path(),
-        local_node.eslint_path(), '--no-eslintrc', '--fix', '--env=es6', '--parser-options=ecmaVersion:9',
+        local_node.eslint_path(), '--no-eslintrc', '--fix', '--env=es6', '--parser-options=ecmaVersion:9,sourceType:module',
         '--rule={"curly": [2, "multi-or-nest", "consistent"], "semi": 2}'
     ] + affected_files)
     eslint_process.communicate()
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js b/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js
index e911674..430be4a 100644
--- a/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js
+++ b/third_party/blink/renderer/devtools/front_end/bindings/CSSWorkspaceBinding.js
@@ -238,10 +238,13 @@
    * @return {!Array<!SDK.CSSLocation>}
    */
   _uiLocationToRawLocations(uiLocation) {
-    const rawLocations = this._sassSourceMapping.uiLocationToRawLocations(uiLocation);
+    let rawLocations = this._sassSourceMapping.uiLocationToRawLocations(uiLocation);
     if (rawLocations.length)
       return rawLocations;
-    return this._stylesSourceMapping.uiLocationToRawLocations(uiLocation);
+    rawLocations = this._stylesSourceMapping.uiLocationToRawLocations(uiLocation);
+    if (rawLocations.length)
+      return rawLocations;
+    return Bindings.resourceMapping.uiLocationToCSSLocations(uiLocation);
   }
 
   _dispose() {
diff --git a/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js b/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js
index e3c7e75..2add353 100644
--- a/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js
+++ b/third_party/blink/renderer/devtools/front_end/bindings/ResourceMapping.js
@@ -111,6 +111,23 @@
   }
 
   /**
+   * @param {!Workspace.UILocation} uiLocation
+   * @return {!Array<!SDK.CSSLocation>}
+   */
+  uiLocationToCSSLocations(uiLocation) {
+    if (!uiLocation.uiSourceCode[Bindings.ResourceMapping._symbol])
+      return [];
+    const target = Bindings.NetworkProject.targetForUISourceCode(uiLocation.uiSourceCode);
+    if (!target)
+      return [];
+    const cssModel = target.model(SDK.CSSModel);
+    if (!cssModel)
+      return [];
+    return cssModel.createRawLocationsByURL(
+        uiLocation.uiSourceCode.url(), uiLocation.lineNumber, uiLocation.columnNumber);
+  }
+
+  /**
    * @param {!SDK.Target} target
    */
   _resetForTest(target) {
@@ -408,4 +425,4 @@
 };
 
 Bindings.ResourceMapping._symbol = Symbol('Bindings.ResourceMapping._symbol');
-Bindings.ResourceMapping._offsetSymbol = Symbol('Bindings.ResourceMapping._offsetSymbol');
\ No newline at end of file
+Bindings.ResourceMapping._offsetSymbol = Symbol('Bindings.ResourceMapping._offsetSymbol');
diff --git a/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js b/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js
index a192450..9e8000ec 100644
--- a/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js
+++ b/third_party/blink/renderer/devtools/front_end/coverage/CoverageDecorationManager.js
@@ -22,9 +22,6 @@
     this._textByProvider = new Map();
     /** @type {!Multimap<!Common.ContentProvider, !Workspace.UISourceCode>} */
     this._uiSourceCodeByContentProvider = new Multimap();
-    // TODO(crbug.com/720162): get rid of this, use bindings.
-    /** @type {!WeakMap<!Workspace.UISourceCode, !Array<!SDK.CSSStyleSheetHeader>>} */
-    this._documentUISouceCodeToStylesheets = new WeakMap();
 
     for (const uiSourceCode of Workspace.workspace.uiSourceCodes())
       uiSourceCode.addLineDecoration(0, Coverage.CoverageDecorationManager._decoratorType, this);
@@ -146,6 +143,8 @@
       for (let location of locations) {
         const script = location.script();
         if (script.isInlineScript() && contentType.isDocument()) {
+          // TODO(chromium:1005789): Remove this check, once the bindings only return locations that actually belong to
+          // the script they claim to belong to.
           if (comparePositions(script.lineOffset, script.columnOffset, location.lineNumber, location.columnNumber) >
                   0 ||
               comparePositions(script.endLine, script.endColumn, location.lineNumber, location.columnNumber) <= 0) {
@@ -167,14 +166,20 @@
       }
     }
     if (contentType.isStyleSheet() || contentType.isDocument()) {
-      const rawStyleLocations = contentType.isDocument() ?
-          this._documentUILocationToCSSRawLocations(uiSourceCode, line, column) :
+      const rawStyleLocations =
           Bindings.cssWorkspaceBinding.uiLocationToRawLocations(new Workspace.UILocation(uiSourceCode, line, column));
       for (const location of rawStyleLocations) {
         const header = location.header();
         if (!header)
           continue;
         if (header.isInline && contentType.isDocument()) {
+          // TODO(chromium:1005789): Remove this check, once the bindings only return locations that actually belong to
+          // the CSS header they claim to belong to.
+          if (comparePositions(header.startLine, header.startColumn, location.lineNumber, location.columnNumber) > 0) {
+            // TODO(chromium:1005708): Also check that the location is still inside the script once we have the line:column
+            // for the end of the inline script.
+            continue;
+          }
           location.lineNumber -= header.startLine;
           if (!location.lineNumber)
             location.columnNumber -= header.startColumn;
@@ -203,51 +208,6 @@
   }
 
   /**
-   * TODO(crbug.com/720162): get rid of this, use bindings.
-   *
-   * @param {!Workspace.UISourceCode} uiSourceCode
-   * @param {number} line
-   * @param {number} column
-   * @return {!Array<!SDK.CSSLocation>}
-   */
-  _documentUILocationToCSSRawLocations(uiSourceCode, line, column) {
-    let stylesheets = this._documentUISouceCodeToStylesheets.get(uiSourceCode);
-    if (!stylesheets) {
-      stylesheets = [];
-      const cssModel = this._coverageModel.target().model(SDK.CSSModel);
-      if (!cssModel)
-        return [];
-      for (const headerId of cssModel.styleSheetIdsForURL(uiSourceCode.url())) {
-        const header = cssModel.styleSheetHeaderForId(headerId);
-        if (header)
-          stylesheets.push(header);
-      }
-      stylesheets.sort(stylesheetComparator);
-      this._documentUISouceCodeToStylesheets.set(uiSourceCode, stylesheets);
-    }
-    const endIndex =
-        stylesheets.upperBound(undefined, (unused, header) => line - header.startLine || column - header.startColumn);
-    if (!endIndex)
-      return [];
-    const locations = [];
-    const last = stylesheets[endIndex - 1];
-    for (let index = endIndex - 1; index >= 0 && stylesheets[index].startLine === last.startLine &&
-         stylesheets[index].startColumn === last.startColumn;
-         --index)
-      locations.push(new SDK.CSSLocation(stylesheets[index], line, column));
-
-    return locations;
-    /**
-     * @param {!SDK.CSSStyleSheetHeader} a
-     * @param {!SDK.CSSStyleSheetHeader} b
-     * @return {number}
-     */
-    function stylesheetComparator(a, b) {
-      return a.startLine - b.startLine || a.startColumn - b.startColumn || a.id.localeCompare(b.id);
-    }
-  }
-
-  /**
    * @param {!Coverage.RawLocation} a
    * @param {!Coverage.RawLocation} b
    */
diff --git a/third_party/blink/renderer/devtools/front_end/devtools_app.html b/third_party/blink/renderer/devtools/front_end/devtools_app.html
index 81b6645..2460c329 100644
--- a/third_party/blink/renderer/devtools/front_end/devtools_app.html
+++ b/third_party/blink/renderer/devtools/front_end/devtools_app.html
@@ -9,8 +9,9 @@
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
     <meta name="referrer" content="no-referrer">
-    <script src="Runtime.js"></script>
-    <script src="devtools_app.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="devtools_app.js"></script>
 </head>
 <body class="undocked" id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/front_end/inspector.html b/third_party/blink/renderer/devtools/front_end/inspector.html
index b5d6f04e..1ab4d319 100644
--- a/third_party/blink/renderer/devtools/front_end/inspector.html
+++ b/third_party/blink/renderer/devtools/front_end/inspector.html
@@ -9,8 +9,9 @@
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
     <meta name="referrer" content="no-referrer">
-    <script src="Runtime.js"></script>
-    <script src="inspector.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="inspector.js"></script>
 </head>
 <body class="undocked" id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/front_end/integration_test_runner.html b/third_party/blink/renderer/devtools/front_end/integration_test_runner.html
index ca7cc521..073b301 100644
--- a/third_party/blink/renderer/devtools/front_end/integration_test_runner.html
+++ b/third_party/blink/renderer/devtools/front_end/integration_test_runner.html
@@ -8,8 +8,9 @@
 <head>
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
-    <script src="Runtime.js"></script>
-    <script src="integration_test_runner.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="integration_test_runner.js"></script>
 </head>
 <body id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/front_end/js_app.html b/third_party/blink/renderer/devtools/front_end/js_app.html
index 7105918..8cc144c 100644
--- a/third_party/blink/renderer/devtools/front_end/js_app.html
+++ b/third_party/blink/renderer/devtools/front_end/js_app.html
@@ -9,8 +9,9 @@
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
     <meta name="referrer" content="no-referrer">
-    <script src="Runtime.js"></script>
-    <script src="js_app.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="js_app.js"></script>
 </head>
 <body class="undocked" id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/front_end/ndb_app.html b/third_party/blink/renderer/devtools/front_end/ndb_app.html
index ac0dee1..d6f17486 100644
--- a/third_party/blink/renderer/devtools/front_end/ndb_app.html
+++ b/third_party/blink/renderer/devtools/front_end/ndb_app.html
@@ -9,8 +9,9 @@
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
     <meta name="referrer" content="no-referrer">
-    <script src="Runtime.js"></script>
-    <script src="ndb_app.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="ndb_app.js"></script>
 </head>
 <body class="undocked" id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/front_end/node_app.html b/third_party/blink/renderer/devtools/front_end/node_app.html
index 05aa910..5b475a11 100644
--- a/third_party/blink/renderer/devtools/front_end/node_app.html
+++ b/third_party/blink/renderer/devtools/front_end/node_app.html
@@ -9,8 +9,9 @@
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
     <meta name="referrer" content="no-referrer">
-    <script src="Runtime.js"></script>
-    <script src="node_app.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="node_app.js"></script>
 </head>
 <body class="undocked" id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/front_end/root.js b/third_party/blink/renderer/devtools/front_end/root.js
new file mode 100644
index 0000000..4590c37c
--- /dev/null
+++ b/third_party/blink/renderer/devtools/front_end/root.js
@@ -0,0 +1,5 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import './ui/ui.js';
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js
index f600a65..94051a49 100644
--- a/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js
+++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSModel.js
@@ -67,6 +67,52 @@
   }
 
   /**
+   * @param {string} sourceURL
+   * @return {!Array<!SDK.CSSStyleSheetHeader>}
+   */
+  headersForSourceURL(sourceURL) {
+    const headers = [];
+    for (const headerId of this.styleSheetIdsForURL(sourceURL)) {
+      const header = this.styleSheetHeaderForId(headerId);
+      if (header)
+        headers.push(header);
+    }
+    return headers;
+  }
+
+  /**
+   * @param {string} sourceURL
+   * @param {number} lineNumber
+   * @param {number} columnNumber
+   * @return {!Array<!SDK.CSSLocation>}
+   */
+  createRawLocationsByURL(sourceURL, lineNumber, columnNumber) {
+    const headers = this.headersForSourceURL(sourceURL);
+    headers.sort(stylesheetComparator);
+    const compareToArgLocation = (_, header) => lineNumber - header.startLine || columnNumber - header.startColumn;
+    const endIndex = headers.upperBound(undefined, compareToArgLocation);
+    if (!endIndex)
+      return [];
+    const locations = [];
+    const last = headers[endIndex - 1];
+    for (let index = endIndex - 1;
+         index >= 0 && headers[index].startLine === last.startLine && headers[index].startColumn === last.startColumn;
+         --index)
+      locations.push(new SDK.CSSLocation(headers[index], lineNumber, columnNumber));
+
+
+    return locations;
+    /**
+     * @param {!SDK.CSSStyleSheetHeader} a
+     * @param {!SDK.CSSStyleSheetHeader} b
+     * @return {number}
+     */
+    function stylesheetComparator(a, b) {
+      return a.startLine - b.startLine || a.startColumn - b.startColumn || a.id.localeCompare(b.id);
+    }
+  }
+
+  /**
    * @return {!SDK.SourceMapManager<!SDK.CSSStyleSheetHeader>}
    */
   sourceMapManager() {
diff --git a/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js b/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js
index 86e202c3..0800c4da 100644
--- a/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js
+++ b/third_party/blink/renderer/devtools/front_end/sources/SourceFormatter.js
@@ -275,10 +275,7 @@
    */
   _setSourceMappingEnabled(formatData, enable) {
     const original = formatData.originalSourceCode;
-    const rawLocations = Bindings.cssWorkspaceBinding.uiLocationToRawLocations(original.uiLocation(0, 0));
-    const headers = rawLocations.map(rawLocation => rawLocation.header()).filter(header => !!header);
-    if (!headers.length)
-      return;
+    const headers = this._headersForUISourceCode(original);
     if (enable) {
       original[this._headersSymbol] = headers;
       headers.forEach(header => header[Sources.SourceFormatData._formatDataSymbol] = formatData);
@@ -288,6 +285,25 @@
     }
     headers.forEach(header => Bindings.cssWorkspaceBinding.updateLocations(header));
   }
+
+  /**
+   * @param {!Workspace.UISourceCode} uiSourceCode
+   * @return {!Array<!SDK.CSSStyleSheetHeader>}
+   */
+  _headersForUISourceCode(uiSourceCode) {
+    if (uiSourceCode.contentType() === Common.resourceTypes.Document) {
+      const target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode);
+      const cssModel = target && target.model(SDK.CSSModel);
+      if (cssModel) {
+        return cssModel.headersForSourceURL(uiSourceCode.url())
+            .filter(header => header.isInline && !header.hasSourceURL);
+      }
+    } else if (uiSourceCode.contentType().isStyleSheet()) {
+      const rawLocations = Bindings.cssWorkspaceBinding.uiLocationToRawLocations(uiSourceCode.uiLocation(0, 0));
+      return rawLocations.map(rawLocation => rawLocation.header()).filter(header => !!header);
+    }
+    return [];
+  }
 };
 
 Sources.sourceFormatter = new Sources.SourceFormatter();
diff --git a/third_party/blink/renderer/devtools/front_end/toolbox.html b/third_party/blink/renderer/devtools/front_end/toolbox.html
index c48ad36..ab892052 100644
--- a/third_party/blink/renderer/devtools/front_end/toolbox.html
+++ b/third_party/blink/renderer/devtools/front_end/toolbox.html
@@ -8,8 +8,9 @@
 <head>
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' ">
-    <script src="Runtime.js"></script>
-    <script src="toolbox.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="toolbox.js"></script>
 </head>
 <body class="undocked" id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js b/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js
index fd1aad50..088e6ee2 100644
--- a/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js
+++ b/third_party/blink/renderer/devtools/front_end/ui/ARIAUtils.js
@@ -2,327 +2,326 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-UI.ARIAUtils = {};
-UI.ARIAUtils._id = 0;
-
-/**
- * @param {!Element} label
- * @param {!Element} control
- */
-UI.ARIAUtils.bindLabelToControl = function(label, control) {
-  const controlId = UI.ARIAUtils.nextId('labelledControl');
-  control.id = controlId;
-  label.setAttribute('for', controlId);
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsAlert = function(element) {
-  element.setAttribute('role', 'alert');
-  element.setAttribute('aria-live', 'polite');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsButton = function(element) {
-  element.setAttribute('role', 'button');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsCheckbox = function(element) {
-  element.setAttribute('role', 'checkbox');
-};
-
-/**
- * @param {!Element} element
- * @param {boolean=} modal
- */
-UI.ARIAUtils.markAsDialog = function(element, modal) {
-  element.setAttribute('role', 'dialog');
-  if (modal)
-    element.setAttribute('aria-modal', 'true');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsGroup = function(element) {
-  element.setAttribute('role', 'group');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsLink = function(element) {
-  element.setAttribute('role', 'link');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsMenuButton = function(element) {
-  UI.ARIAUtils.markAsButton(element);
-  element.setAttribute('aria-haspopup', true);
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsProgressBar = function(element) {
-  element.setAttribute('role', 'progressbar');
-  element.setAttribute('aria-valuemin', 0);
-  element.setAttribute('aria-valuemax', 100);
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsTab = function(element) {
-  element.setAttribute('role', 'tab');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsTree = function(element) {
-  element.setAttribute('role', 'tree');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsTreeitem = function(element) {
-  element.setAttribute('role', 'treeitem');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsTextBox = function(element) {
-  element.setAttribute('role', 'textbox');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsMenu = function(element) {
-  element.setAttribute('role', 'menu');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsMenuItem = function(element) {
-  element.setAttribute('role', 'menuitem');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsMenuItemSubMenu = function(element) {
-  UI.ARIAUtils.markAsMenuItem(element);
-  element.setAttribute('aria-haspopup', true);
-};
-
-/**
- * Must contain children whose role is option.
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsListBox = function(element) {
-  element.setAttribute('role', 'listbox');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsMultiSelectable = function(element) {
-  element.setAttribute('aria-multiselectable', 'true');
-};
-
-/**
- * Must be contained in, or owned by, an element with the role listbox.
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsOption = function(element) {
-  element.setAttribute('role', 'option');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsRadioGroup = function(element) {
-  element.setAttribute('role', 'radiogroup');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsHidden = function(element) {
-  element.setAttribute('aria-hidden', 'true');
-};
-
-/**
- * @param {!Element} element
- * @param {number} level
- */
-UI.ARIAUtils.markAsHeading = function(element, level) {
-  element.setAttribute('role', 'heading');
-  element.setAttribute('aria-level', level);
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsPoliteLiveRegion = function(element) {
-  element.setAttribute('aria-live', 'polite');
-};
-
-/**
- * @param {!Element} element
- * @param {?string} placeholder
- */
-UI.ARIAUtils.setPlaceholder = function(element, placeholder) {
-  if (placeholder)
-    element.setAttribute('aria-placeholder', placeholder);
-  else
-    element.removeAttribute('aria-placeholder');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsPresentation = function(element) {
-  element.setAttribute('role', 'presentation');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.markAsStatus = function(element) {
-  element.setAttribute('role', 'status');
-};
-
-/**
- * @param {!Element} element
- */
-UI.ARIAUtils.ensureId = function(element) {
-  if (!element.id)
-    element.id = UI.ARIAUtils.nextId('ariaElement');
-};
+let _id = 0;
 
 /**
  * @param {string} prefix
  * @return {string}
  */
-UI.ARIAUtils.nextId = function(prefix) {
-  return (prefix || '') + ++UI.ARIAUtils._id;
-};
+export function nextId(prefix) {
+  return (prefix || '') + ++_id;
+}
+
+/**
+ * @param {!Element} label
+ * @param {!Element} control
+ */
+export function bindLabelToControl(label, control) {
+  const controlId = nextId('labelledControl');
+  control.id = controlId;
+  label.setAttribute('for', controlId);
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsAlert(element) {
+  element.setAttribute('role', 'alert');
+  element.setAttribute('aria-live', 'polite');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsButton(element) {
+  element.setAttribute('role', 'button');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsCheckbox(element) {
+  element.setAttribute('role', 'checkbox');
+}
+
+/**
+ * @param {!Element} element
+ * @param {boolean=} modal
+ */
+export function markAsDialog(element, modal) {
+  element.setAttribute('role', 'dialog');
+  if (modal)
+    element.setAttribute('aria-modal', 'true');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsGroup(element) {
+  element.setAttribute('role', 'group');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsLink(element) {
+  element.setAttribute('role', 'link');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsMenuButton(element) {
+  markAsButton(element);
+  element.setAttribute('aria-haspopup', true);
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsProgressBar(element) {
+  element.setAttribute('role', 'progressbar');
+  element.setAttribute('aria-valuemin', 0);
+  element.setAttribute('aria-valuemax', 100);
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsTab(element) {
+  element.setAttribute('role', 'tab');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsTree(element) {
+  element.setAttribute('role', 'tree');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsTreeitem(element) {
+  element.setAttribute('role', 'treeitem');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsTextBox(element) {
+  element.setAttribute('role', 'textbox');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsMenu(element) {
+  element.setAttribute('role', 'menu');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsMenuItem(element) {
+  element.setAttribute('role', 'menuitem');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsMenuItemSubMenu(element) {
+  markAsMenuItem(element);
+  element.setAttribute('aria-haspopup', true);
+}
+
+/**
+ * Must contain children whose role is option.
+ * @param {!Element} element
+ */
+export function markAsListBox(element) {
+  element.setAttribute('role', 'listbox');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsMultiSelectable(element) {
+  element.setAttribute('aria-multiselectable', 'true');
+}
+
+/**
+ * Must be contained in, or owned by, an element with the role listbox.
+ * @param {!Element} element
+ */
+export function markAsOption(element) {
+  element.setAttribute('role', 'option');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsRadioGroup(element) {
+  element.setAttribute('role', 'radiogroup');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsHidden(element) {
+  element.setAttribute('aria-hidden', 'true');
+}
+
+/**
+ * @param {!Element} element
+ * @param {number} level
+ */
+export function markAsHeading(element, level) {
+  element.setAttribute('role', 'heading');
+  element.setAttribute('aria-level', level);
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsPoliteLiveRegion(element) {
+  element.setAttribute('aria-live', 'polite');
+}
+
+/**
+ * @param {!Element} element
+ * @param {?string} placeholder
+ */
+export function setPlaceholder(element, placeholder) {
+  if (placeholder)
+    element.setAttribute('aria-placeholder', placeholder);
+  else
+    element.removeAttribute('aria-placeholder');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsPresentation(element) {
+  element.setAttribute('role', 'presentation');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function markAsStatus(element) {
+  element.setAttribute('role', 'status');
+}
+
+/**
+ * @param {!Element} element
+ */
+export function ensureId(element) {
+  if (!element.id)
+    element.id = nextId('ariaElement');
+}
 
 /**
  * @param {!Element} element
  * @param {?Element} controlledElement
  */
-UI.ARIAUtils.setControls = function(element, controlledElement) {
+export function setControls(element, controlledElement) {
   if (!controlledElement) {
     element.removeAttribute('aria-controls');
     return;
   }
 
-  UI.ARIAUtils.ensureId(controlledElement);
+  ensureId(controlledElement);
   element.setAttribute('aria-controls', controlledElement.id);
-};
+}
 
 /**
  * @param {!Element} element
  * @param {boolean} value
  */
-UI.ARIAUtils.setChecked = function(element, value) {
+export function setChecked(element, value) {
   element.setAttribute('aria-checked', !!value);
-};
+}
 
 /**
  * @param {!Element} element
  */
-UI.ARIAUtils.setCheckboxAsIndeterminate = function(element) {
+export function setCheckboxAsIndeterminate(element) {
   element.setAttribute('aria-checked', 'mixed');
-};
+}
 
 /**
  * @param {!Element} element
  * @param {boolean} value
  */
-UI.ARIAUtils.setExpanded = function(element, value) {
+export function setExpanded(element, value) {
   element.setAttribute('aria-expanded', !!value);
-};
+}
 
 /**
  * @param {!Element} element
  */
-UI.ARIAUtils.unsetExpandable = function(element) {
+export function unsetExpandable(element) {
   element.removeAttribute('aria-expanded');
-};
+}
 
 /**
  * @param {!Element} element
  * @param {boolean} value
  */
-UI.ARIAUtils.setSelected = function(element, value) {
+export function setSelected(element, value) {
   // aria-selected behaves differently for false and undefined.
   // Often times undefined values are unintentionally typed as booleans.
   // Use !! to make sure this is true or false.
   element.setAttribute('aria-selected', !!value);
-};
+}
 
 /**
  * @param {!Element} element
  * @param {boolean} value
  */
-UI.ARIAUtils.setInvalid = function(element, value) {
+export function setInvalid(element, value) {
   if (value)
     element.setAttribute('aria-invalid', value);
   else
     element.removeAttribute('aria-invalid');
-};
+}
 
 /**
  * @param {!Element} element
  * @param {boolean} value
  */
-UI.ARIAUtils.setPressed = function(element, value) {
+export function setPressed(element, value) {
   // aria-pressed behaves differently for false and undefined.
   // Often times undefined values are unintentionally typed as booleans.
   // Use !! to make sure this is true or false.
   element.setAttribute('aria-pressed', !!value);
-};
+}
 
 /**
  * @param {!Element} element
  * @param {number} value
  */
-UI.ARIAUtils.setProgressBarCurrentPercentage = function(element, value) {
+export function setProgressBarCurrentPercentage(element, value) {
   element.setAttribute('aria-valuenow', value);
-};
+}
 
 /**
  * @param {!Element} element
  * @param {string} name
  */
-UI.ARIAUtils.setAccessibleName = function(element, name) {
+export function setAccessibleName(element, name) {
   element.setAttribute('aria-label', name);
-};
+}
 
 /** @type {!WeakMap<!Element, !Element>} */
-UI.ARIAUtils._descriptionMap = new WeakMap();
+const _descriptionMap = new WeakMap();
 
 /**
  * @param {!Element} element
  * @param {string} description
  */
-UI.ARIAUtils.setDescription = function(element, description) {
+export function setDescription(element, description) {
   // Nodes in the accesesibility tree are made up of a core
   // triplet of "name", "value", "description"
   // The "description" field is taken from either
@@ -348,12 +347,12 @@
   // The rest of DevTools shouldn't have to worry about this,
   // so there is some unfortunate code below.
 
-  if (UI.ARIAUtils._descriptionMap.has(element))
-    UI.ARIAUtils._descriptionMap.get(element).remove();
+  if (_descriptionMap.has(element))
+    _descriptionMap.get(element).remove();
   element.removeAttribute('data-aria-utils-animation-hack');
 
   if (!description) {
-    UI.ARIAUtils._descriptionMap.delete(element);
+    _descriptionMap.delete(element);
     element.removeAttribute('aria-describedby');
     return;
   }
@@ -363,9 +362,9 @@
   const descriptionElement = createElement('span');
   descriptionElement.textContent = description;
   descriptionElement.style.display = 'none';
-  UI.ARIAUtils.ensureId(descriptionElement);
+  ensureId(descriptionElement);
   element.setAttribute('aria-describedby', descriptionElement.id);
-  UI.ARIAUtils._descriptionMap.set(element, descriptionElement);
+  _descriptionMap.set(element, descriptionElement);
 
   // Now we have to actually put this description element
   // somewhere in the DOM so that we can point to it.
@@ -398,20 +397,20 @@
   element.setAttribute('data-aria-utils-animation-hack', 'sorry');
   element.addEventListener('animationend', () => {
     // Someone might have made a new description in the meantime.
-    if (UI.ARIAUtils._descriptionMap.get(element) !== descriptionElement)
+    if (_descriptionMap.get(element) !== descriptionElement)
       return;
     element.removeAttribute('data-aria-utils-animation-hack');
 
     // Try it again. This time we are in the DOM, so it *should* work.
     element.insertAdjacentElement('afterend', descriptionElement);
   }, {once: true});
-};
+}
 
 /**
  * @param {!Element} element
  * @param {?Element} activedescendant
  */
-UI.ARIAUtils.setActiveDescendant = function(element, activedescendant) {
+export function setActiveDescendant(element, activedescendant) {
   if (!activedescendant) {
     element.removeAttribute('aria-activedescendant');
     return;
@@ -419,17 +418,19 @@
 
   console.assert(element.hasSameShadowRoot(activedescendant), 'elements are not in the same shadow dom');
 
-  UI.ARIAUtils.ensureId(activedescendant);
+  ensureId(activedescendant);
   element.setAttribute('aria-activedescendant', activedescendant.id);
-};
+}
+
+const AlertElementSymbol = Symbol('AlertElementSybmol');
 
 /**
  * @param {string} message
  * @param {!Element} element
  */
-UI.ARIAUtils.alert = function(message, element) {
+export function alert(message, element) {
   const document = element.ownerDocument;
-  if (!document[UI.ARIAUtils.AlertElementSymbol]) {
+  if (!document[AlertElementSymbol]) {
     const alertElement = document.body.createChild('div');
     alertElement.style.position = 'absolute';
     alertElement.style.left = '-999em';
@@ -437,9 +438,54 @@
     alertElement.style.overflow = 'hidden';
     alertElement.setAttribute('role', 'alert');
     alertElement.setAttribute('aria-atomic', 'true');
-    document[UI.ARIAUtils.AlertElementSymbol] = alertElement;
+    document[AlertElementSymbol] = alertElement;
   }
-  document[UI.ARIAUtils.AlertElementSymbol].textContent = message.trimEndWithMaxLength(10000);
-};
 
-UI.ARIAUtils.AlertElementSymbol = Symbol('AlertElementSybmol');
+  document[AlertElementSymbol].textContent = message.trimEndWithMaxLength(10000);
+}
+
+/** Legacy exported object @suppress {const} */
+self.UI = self.UI || {};
+self.UI.ARIAUtils = {
+  nextId,
+  bindLabelToControl,
+  markAsAlert,
+  markAsButton,
+  markAsCheckbox,
+  markAsDialog,
+  markAsGroup,
+  markAsLink,
+  markAsMenuButton,
+  markAsProgressBar,
+  markAsTab,
+  markAsTree,
+  markAsTreeitem,
+  markAsTextBox,
+  markAsMenu,
+  markAsMenuItem,
+  markAsMenuItemSubMenu,
+  markAsListBox,
+  markAsMultiSelectable,
+  markAsOption,
+  markAsRadioGroup,
+  markAsHidden,
+  markAsHeading,
+  markAsPoliteLiveRegion,
+  setPlaceholder,
+  markAsPresentation,
+  markAsStatus,
+  ensureId,
+  setControls,
+  setChecked,
+  setCheckboxAsIndeterminate,
+  setExpanded,
+  unsetExpandable,
+  setSelected,
+  setInvalid,
+  setPressed,
+  setProgressBarCurrentPercentage,
+  setAccessibleName,
+  setDescription,
+  setActiveDescendant,
+  alert,
+};
diff --git a/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js b/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js
index dd28379a..12568ad 100644
--- a/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js
+++ b/third_party/blink/renderer/devtools/front_end/ui/SoftContextMenu.js
@@ -75,6 +75,14 @@
 
     if (!this._parentMenu) {
       this._hideOnUserGesture = event => {
+        // If a user clicks on any submenu, prevent the menu system from closing.
+        let subMenu = this._subMenu;
+        while (subMenu) {
+          if (subMenu._contextMenuElement === event.path[0])
+            return;
+          subMenu = subMenu._subMenu;
+        }
+
         this.discard();
         event.consume(true);
       };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/module.json b/third_party/blink/renderer/devtools/front_end/ui/module.json
index bd5f5a1e..582087b 100644
--- a/third_party/blink/renderer/devtools/front_end/ui/module.json
+++ b/third_party/blink/renderer/devtools/front_end/ui/module.json
@@ -54,13 +54,16 @@
         "SuggestBox.js",
         "TabbedPane.js",
         "UIUtils.js",
-        "ARIAUtils.js",
         "ZoomManager.js",
         "ShortcutsScreen.js",
         "Geometry.js",
         "XLink.js",
         "XWidget.js"
     ],
+    "modules": [
+        "ARIAUtils.js",
+        "ui.js"
+    ],
     "resources": [
         "checkboxTextLabel.css",
         "closeButton.css",
diff --git a/third_party/blink/renderer/devtools/front_end/ui/ui.js b/third_party/blink/renderer/devtools/front_end/ui/ui.js
new file mode 100644
index 0000000..fb1c4dc
--- /dev/null
+++ b/third_party/blink/renderer/devtools/front_end/ui/ui.js
@@ -0,0 +1,3 @@
+import * as ARIAUtils from './ARIAUtils.js';
+
+export {ARIAUtils};
\ No newline at end of file
diff --git a/third_party/blink/renderer/devtools/front_end/worker_app.html b/third_party/blink/renderer/devtools/front_end/worker_app.html
index e5827b5e..c041d37 100644
--- a/third_party/blink/renderer/devtools/front_end/worker_app.html
+++ b/third_party/blink/renderer/devtools/front_end/worker_app.html
@@ -9,8 +9,9 @@
     <meta charset="utf-8">
     <meta http-equiv="Content-Security-Policy" content="object-src 'none'; script-src 'self' 'unsafe-eval' 'unsafe-inline' https://chrome-devtools-frontend.appspot.com">
     <meta name="referrer" content="no-referrer">
-    <script src="Runtime.js"></script>
-    <script src="worker_app.js"></script>
+    <script type="module" src="root.js"></script>
+    <script defer src="Runtime.js"></script>
+    <script defer src="worker_app.js"></script>
 </head>
 <body class="undocked" id="-blink-dev-tools"></body>
 </html>
diff --git a/third_party/blink/renderer/devtools/scripts/build/build_release_applications.py b/third_party/blink/renderer/devtools/scripts/build/build_release_applications.py
index 74e1c10..db32b006 100755
--- a/third_party/blink/renderer/devtools/scripts/build/build_release_applications.py
+++ b/third_party/blink/renderer/devtools/scripts/build/build_release_applications.py
@@ -133,13 +133,13 @@
         output = StringIO()
         with open(join(self.application_dir, html_name), 'r') as app_input_html:
             for line in app_input_html:
-                if '<script ' in line or '<link ' in line:
+                if ('<script ' in line and 'type="module"' not in line) or '<link ' in line:
                     continue
                 if '</head>' in line:
                     self._write_include_tags(self.descriptors, output)
                     js_file = join(self.application_dir, self.app_file('js'))
                     if path.exists(js_file):
-                        output.write('    <script>%s</script>\n' % minify_js(read_file(js_file)))
+                        output.write('    <script type="module">%s</script>\n' % minify_js(read_file(js_file)))
                 output.write(line)
 
         write_file(join(self.output_dir, html_name), output.getvalue())
@@ -154,7 +154,7 @@
 
     def _generate_include_tag(self, resource_path):
         if resource_path.endswith('.js'):
-            return '    <script type="text/javascript" src="%s"></script>\n' % resource_path
+            return '    <script defer src="%s"></script>\n' % resource_path
         else:
             assert resource_path
 
diff --git a/third_party/blink/renderer/devtools/scripts/build/copy_devtools_modules.py b/third_party/blink/renderer/devtools/scripts/build/copy_devtools_modules.py
new file mode 100755
index 0000000..10d9ee235
--- /dev/null
+++ b/third_party/blink/renderer/devtools/scripts/build/copy_devtools_modules.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python
+# -*- coding: UTF-8 -*-
+#
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+"""
+Copies the modules into the resources folder
+"""
+
+from os.path import join, relpath
+import shutil
+import sys
+
+
+def main(argv):
+    try:
+        input_path_flag_index = argv.index('--input_path')
+        input_path = argv[input_path_flag_index + 1]
+        output_path_flag_index = argv.index('--output_path')
+        output_path = argv[output_path_flag_index + 1]
+        devtools_modules = argv[1:input_path_flag_index]
+    except:
+        print 'Usage: %s module_1 module_2 ... module_N --input_path <input_path> --output_path <output_path>' % argv[0]
+        raise
+
+    for file_name in devtools_modules:
+        shutil.copy(join(input_path, file_name), join(output_path, relpath(file_name, 'front_end')))
+
+
+if __name__ == '__main__':
+    sys.exit(main(sys.argv))
diff --git a/third_party/blink/renderer/devtools/scripts/build/modular_build.py b/third_party/blink/renderer/devtools/scripts/build/modular_build.py
index 90d6697..c818ad95 100755
--- a/third_party/blink/renderer/devtools/scripts/build/modular_build.py
+++ b/third_party/blink/renderer/devtools/scripts/build/modular_build.py
@@ -76,7 +76,7 @@
         for name in self.sorted_modules():
             module = self.modules[name]
             skipped_files = set(module.get('skip_compilation', []))
-            for script in module.get('scripts', []):
+            for script in module.get('scripts', []) + module.get('modules', []):
                 if script not in skipped_files:
                     files[path.normpath(path.join(self.application_dir, name, script))] = True
         return files.keys()
diff --git a/third_party/blink/renderer/devtools/scripts/check_localizability.js b/third_party/blink/renderer/devtools/scripts/check_localizability.js
index f71a713..98e695c 100644
--- a/third_party/blink/renderer/devtools/scripts/check_localizability.js
+++ b/third_party/blink/renderer/devtools/scripts/check_localizability.js
@@ -285,7 +285,7 @@
   if (path.extname(filePath) === '.grdp')
     return auditGrdpFile(filePath, fileContent, errors);
 
-  const ast = esprima.parse(fileContent, {loc: true});
+  const ast = esprima.parseModule(fileContent, {loc: true});
 
   const relativeFilePath = localizationUtils.getRelativeFilePathFromSrc(filePath);
   for (const node of ast.body)
diff --git a/third_party/blink/renderer/devtools/scripts/check_localizable_resources.js b/third_party/blink/renderer/devtools/scripts/check_localizable_resources.js
index 50a2859..acf7e72 100644
--- a/third_party/blink/renderer/devtools/scripts/check_localizable_resources.js
+++ b/third_party/blink/renderer/devtools/scripts/check_localizable_resources.js
@@ -32,6 +32,7 @@
     else
       await getErrors();
   } catch (e) {
+    console.log(e.stack);
     console.log(`Error: ${e.message}`);
     process.exit(1);
   }
diff --git a/third_party/blink/renderer/devtools/scripts/compile_frontend.py b/third_party/blink/renderer/devtools/scripts/compile_frontend.py
index 53ad724f..78a553da 100755
--- a/third_party/blink/renderer/devtools/scripts/compile_frontend.py
+++ b/third_party/blink/renderer/devtools/scripts/compile_frontend.py
@@ -77,6 +77,7 @@
 GLOBAL_EXTERNS_FILE = to_platform_path(path.join(DEVTOOLS_FRONTEND_PATH, 'externs.js'))
 DEFAULT_PROTOCOL_EXTERNS_FILE = path.join(DEVTOOLS_FRONTEND_PATH, 'protocol_externs.js')
 RUNTIME_FILE = to_platform_path(path.join(DEVTOOLS_FRONTEND_PATH, 'Runtime.js'))
+ROOT_MODULE_FILE = to_platform_path(path.join(DEVTOOLS_FRONTEND_PATH, 'root.js'))
 
 CLOSURE_COMPILER_JAR = to_platform_path(path.join(SCRIPTS_PATH, 'closure', 'compiler.jar'))
 CLOSURE_RUNNER_JAR = to_platform_path(path.join(SCRIPTS_PATH, 'closure', 'closure_runner', 'closure_runner.jar'))
@@ -279,6 +280,8 @@
         namespace_externs_path,
         '--js',
         RUNTIME_FILE,
+        '--js',
+        ROOT_MODULE_FILE,
     ]
 
     all_files = descriptors.all_compiled_files()
diff --git a/third_party/blink/renderer/devtools/scripts/migration/refactor-folder-to-es-modules.sh b/third_party/blink/renderer/devtools/scripts/migration/refactor-folder-to-es-modules.sh
index 55c9c7c..3fa1f37 100755
--- a/third_party/blink/renderer/devtools/scripts/migration/refactor-folder-to-es-modules.sh
+++ b/third_party/blink/renderer/devtools/scripts/migration/refactor-folder-to-es-modules.sh
@@ -1,5 +1,9 @@
 #!/bin/bash
 
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
 if [ -z "$1" ]; then
   echo "Must supply folder name"
   exit
@@ -21,6 +25,15 @@
 
 npm run build
 
+MODULE_FILE="$FRONT_END_PATH/$1/$1.js"
+
+touch "$MODULE_FILE"
+
+echo "// Copyright 2019 The Chromium Authors. All rights reserved." >> $MODULE_FILE
+echo "// Use of this source code is governed by a BSD-style license that can be" >> $MODULE_FILE
+echo "// found in the LICENSE file." >> $MODULE_FILE
+echo "" >> $MODULE_FILE
+
 for FILE in $FILES
 do
   npm run migrate -- $1 $FILE
@@ -32,6 +45,18 @@
   sed -i -e "s/all\_devtools\_modules = \[/all\_devtools\_modules = \[ \"front\_end\/$1\/$FILE.js\"\,/" "$BUILD_GN_PATH"
   # Add to copied_devtools_modules
   sed -i -e "s/copied\_devtools\_modules = \[/copied\_devtools\_modules = \[ \"\$resources\_out\_dir\/$1\/$FILE.js\"\,/" "$BUILD_GN_PATH"
+
+  echo "import * as $FILE from './$FILE.js';" >> $MODULE_FILE
 done
 
+echo "" >> $MODULE_FILE
+echo "export {" >> $MODULE_FILE
+
+for FILE in $FILES
+do
+  echo "  $FILE," >> $MODULE_FILE
+done
+
+echo "};" >> $MODULE_FILE
+
 git cl format
diff --git a/third_party/blink/renderer/devtools/scripts/migration/refactor-to-es-module.ts b/third_party/blink/renderer/devtools/scripts/migration/refactor-to-es-module.ts
index 54da3fe..6e2f2fea 100644
--- a/third_party/blink/renderer/devtools/scripts/migration/refactor-to-es-module.ts
+++ b/third_party/blink/renderer/devtools/scripts/migration/refactor-to-es-module.ts
@@ -1,3 +1,7 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
 import { parse, print, types } from 'recast';
 import fs from 'fs';
 import path from 'path';
@@ -16,9 +20,11 @@
 const b = types.builders;
 
 function createReplacementDeclaration(propertyName: IdentifierKind, declaration: any): any {
+  // UI.ARIAUtils.Foo = class {} -> export class Foo {}
   if (declaration.type === 'ClassExpression') {
     return b.exportDeclaration(false, b.classDeclaration(propertyName, declaration.body));
   }
+  // UI.ARIAUtils.Foo = expression; -> export const Foo = expression;
   if (declaration.type === 'Literal' || declaration.type.endsWith('Expression')) {
     return b.exportNamedDeclaration(b.variableDeclaration("const", [b.variableDeclarator(propertyName, declaration)]));
   }
@@ -39,10 +45,16 @@
   const ast = parse(source);
 
   ast.program.body = ast.program.body.map((expression: any) => {
+    // UI.ARIAUtils.Foo = 5;
     if (expression.type === 'ExpressionStatement') {
+      // UI.ARIAUtils.Foo = 5
       if (expression.expression.type === 'AssignmentExpression') {
         const assignment = expression.expression;
+
+        // UI.ARIAUtils.Foo
         if (assignment.left.type === 'MemberExpression') {
+          // UI.ARIAUtils.Foo -> UI.ARIAUtils
+          // UI.ARIAUtils.Nested.Foo -> UI.ARIAUtils
           const topLevelAssignment = getTopLevelMemberExpression(assignment.left);
 
           // If there is a nested export, such as `UI.ARIAUtils.Nested.Field`
@@ -50,27 +62,33 @@
             // Exports itself. E.g. `UI.ARIAUtils = <...>`
             if (assignment.left.object.name === refactoringNamespace && assignment.left.property.name === refactoringFileName) {
               const {declaration} = createReplacementDeclaration(assignment.left.property, assignment.right);
+              // If it is a variable declaration, we need to use the actual variabledeclator. E.g.:
+              // UI.ARIAUtils = 5; -> export ARIAUtils = 5; instead of "export const ARIAUtils = 5;"
               const declarationStatement = b.exportDefaultDeclaration(declaration.type === 'VariableDeclaration' ? declaration.declarations[0].init : declaration);
-              
+
               declarationStatement.comments = expression.comments;
 
               if (needToObjectAssign) {
                 console.error(`Multiple exports with the same name is invalid!`);
               }
 
+              // Since there is a default export (E.g. UI.ARIAUtils and UI.ARIAUtils.Foo), we need to assign Foo to UI.ARIAUtils to make sure that reference keeps on working
               needToObjectAssign = true;
 
               return declarationStatement;
             }
+
             console.error(`Nested field "${assignment.left.property.name}" detected! Requires manual changes.`);
             return expression;
           }
-          
+
           const propertyName = assignment.left.property;
           const {object, property} = topLevelAssignment;
 
           if (object.type === 'Identifier' && property.type === 'Identifier') {
+            // UI
             const namespace = object.name;
+            // ARIAUtils
             const fileName = property.name;
 
             if (namespace === refactoringNamespace && fileName === refactoringFileName) {
@@ -94,18 +112,18 @@
   const legacyNamespaceName = b.memberExpression(b.identifier('self'), b.identifier(refactoringNamespace), false);
   const legacyNamespaceOr = b.logicalExpression("||", legacyNamespaceName, b.objectExpression([]));
   ast.program.body.push(b.expressionStatement.from({expression: b.assignmentExpression('=', legacyNamespaceName, legacyNamespaceOr), comments: [b.commentBlock('Legacy exported object', true, false)]}));
-  
+
   // self.UI.ARIAUtils = {properties};
   const legacyNamespaceExport = b.memberExpression(b.identifier('self'), b.memberExpression(b.identifier(refactoringNamespace), b.identifier(refactoringFileName), false), false);
   let exportedObjectProperties: ExpressionKind = b.objectExpression(exportedMembers.map(prop => b.objectProperty.from({key: prop, value: prop, shorthand: true })));
 
-  // self.UI.ARIAUtils = Object.assign(ARIAUtils, {properties})
   if (needToObjectAssign) {
+    // self.UI.ARIAUtils = Object.assign(ARIAUtils, {properties})
     exportedObjectProperties = b.callExpression(b.memberExpression(b.identifier('Object'), b.identifier('assign'), false), [b.identifier(refactoringFileName), exportedObjectProperties]);
   }
 
   ast.program.body.push(b.expressionStatement(b.assignmentExpression('=', legacyNamespaceExport, exportedObjectProperties)));
-  
+
   return print(ast).code;
 }
 
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn
index 8e811807..b41b2d36 100644
--- a/third_party/blink/renderer/modules/BUILD.gn
+++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -175,7 +175,6 @@
   deps = [
     ":make_modules_generated",
     ":module_names",
-    "//jingle:webrtc_glue",
     "//net:net",
     "//third_party/blink/renderer/bindings/modules:generated",
     "//third_party/blink/renderer/bindings/modules/v8:bindings_modules_impl",
@@ -183,9 +182,6 @@
     "//third_party/blink/renderer/core",
     "//third_party/icu",
     "//third_party/webrtc/api/audio:aec3_config_json",
-    "//third_party/webrtc/api/rtc_event_log:rtc_event_log_factory",
-    "//third_party/webrtc/media:rtc_internal_video_codecs",
-    "//third_party/webrtc/modules/video_coding:webrtc_h264",
     "//third_party/webrtc/pc:libjingle_peerconnection",
     "//third_party/webrtc/rtc_base:rtc_base",
     "//third_party/webrtc_overrides:init_webrtc",
diff --git a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
index 0ca5726..c8f1af1 100644
--- a/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
+++ b/third_party/blink/renderer/modules/canvas/offscreencanvas2d/offscreen_canvas_rendering_context_2d.cc
@@ -132,6 +132,8 @@
 
 bool OffscreenCanvasRenderingContext2D::CanCreateCanvas2dResourceProvider()
     const {
+  if (!Host() || Host()->Size().IsEmpty())
+    return false;
   return !!offscreenCanvasForBinding()->GetOrCreateResourceProvider();
 }
 
diff --git a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
index 8fed659..90e8e710 100644
--- a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
+++ b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
@@ -73,19 +73,11 @@
 // static
 std::unique_ptr<WebEmbeddedWorker> WebEmbeddedWorker::Create(
     WebServiceWorkerContextClient* client,
-    std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>
-        installed_scripts_manager_params,
-    mojo::ScopedMessagePipeHandle content_settings_handle,
     mojo::ScopedMessagePipeHandle cache_storage,
     mojo::ScopedMessagePipeHandle interface_provider,
     mojo::ScopedMessagePipeHandle browser_interface_broker) {
   return std::make_unique<WebEmbeddedWorkerImpl>(
-      std::move(client), std::move(installed_scripts_manager_params),
-      std::make_unique<ServiceWorkerContentSettingsProxy>(
-          // Chrome doesn't use interface versioning.
-          // TODO(falken): Is that comment about versioning correct?
-          mojo::PendingRemote<mojom::blink::WorkerContentSettingsProxy>(
-              std::move(content_settings_handle), 0u)),
+      std::move(client),
       mojo::PendingRemote<mojom::blink::CacheStorage>(
           std::move(cache_storage), mojom::blink::CacheStorage::Version_),
       service_manager::mojom::blink::InterfaceProviderPtrInfo(
@@ -98,36 +90,42 @@
 
 // static
 std::unique_ptr<WebEmbeddedWorkerImpl> WebEmbeddedWorkerImpl::CreateForTesting(
-    WebServiceWorkerContextClient* client,
-    std::unique_ptr<ServiceWorkerInstalledScriptsManager>
-        installed_scripts_manager) {
+    WebServiceWorkerContextClient* client) {
   auto worker_impl = std::make_unique<WebEmbeddedWorkerImpl>(
-      client, nullptr /* installed_scripts_manager_params */,
-      std::make_unique<ServiceWorkerContentSettingsProxy>(
-          mojo::NullRemote() /* host_info */),
-      mojo::NullRemote() /* cache_storage */,
+      client, mojo::NullRemote() /* cache_storage */,
       nullptr /* interface_provider_info */,
       mojo::NullRemote() /* browser_interface_broker */);
-  worker_impl->installed_scripts_manager_ =
-      std::move(installed_scripts_manager);
   return worker_impl;
 }
 
 WebEmbeddedWorkerImpl::WebEmbeddedWorkerImpl(
     WebServiceWorkerContextClient* client,
-    std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>
-        installed_scripts_manager_params,
-    std::unique_ptr<ServiceWorkerContentSettingsProxy> content_settings_client,
     mojo::PendingRemote<mojom::blink::CacheStorage> cache_storage_remote,
     service_manager::mojom::blink::InterfaceProviderPtrInfo
         interface_provider_info,
     mojo::PendingRemote<mojom::blink::BrowserInterfaceBroker>
         browser_interface_broker)
     : worker_context_client_(client),
-      content_settings_client_(std::move(content_settings_client)),
       cache_storage_remote_(std::move(cache_storage_remote)),
       interface_provider_info_(std::move(interface_provider_info)),
-      browser_interface_broker_(std::move(browser_interface_broker)) {
+      browser_interface_broker_(std::move(browser_interface_broker)) {}
+
+WebEmbeddedWorkerImpl::~WebEmbeddedWorkerImpl() {
+  // TerminateWorkerContext() must be called before the destructor.
+  DCHECK(asked_to_terminate_);
+}
+
+void WebEmbeddedWorkerImpl::StartWorkerContext(
+    const WebEmbeddedWorkerStartData& data,
+    std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>
+        installed_scripts_manager_params,
+    mojo::ScopedMessagePipeHandle content_settings_handle,
+    scoped_refptr<base::SingleThreadTaskRunner> initiator_thread_task_runner) {
+  DCHECK(!asked_to_terminate_);
+  worker_start_data_ = data;
+
+  std::unique_ptr<ServiceWorkerInstalledScriptsManager>
+      installed_scripts_manager;
   if (installed_scripts_manager_params) {
     DCHECK(installed_scripts_manager_params->manager_receiver.is_valid());
     DCHECK(installed_scripts_manager_params->manager_host_remote.is_valid());
@@ -135,7 +133,7 @@
     installed_scripts_urls.AppendRange(
         installed_scripts_manager_params->installed_scripts_urls.begin(),
         installed_scripts_manager_params->installed_scripts_urls.end());
-    installed_scripts_manager_ = std::make_unique<
+    installed_scripts_manager = std::make_unique<
         ServiceWorkerInstalledScriptsManager>(
         installed_scripts_urls,
         mojo::PendingReceiver<
@@ -147,18 +145,6 @@
             mojom::blink::ServiceWorkerInstalledScriptsManagerHost::Version_),
         Platform::Current()->GetIOTaskRunner());
   }
-}
-
-WebEmbeddedWorkerImpl::~WebEmbeddedWorkerImpl() {
-  // TerminateWorkerContext() must be called before the destructor.
-  DCHECK(asked_to_terminate_);
-}
-
-void WebEmbeddedWorkerImpl::StartWorkerContext(
-    const WebEmbeddedWorkerStartData& data,
-    scoped_refptr<base::SingleThreadTaskRunner> initiator_thread_task_runner) {
-  DCHECK(!asked_to_terminate_);
-  worker_start_data_ = data;
 
   // TODO(mkwst): This really needs to be piped through from the requesting
   // document, like we're doing for SharedWorkers. That turns out to be
@@ -177,7 +163,14 @@
 
   devtools_worker_token_ = data.devtools_worker_token;
   wait_for_debugger_mode_ = worker_start_data_.wait_for_debugger_mode;
-  StartWorkerThread(std::move(initiator_thread_task_runner));
+  StartWorkerThread(
+      std::move(installed_scripts_manager),
+      std::make_unique<ServiceWorkerContentSettingsProxy>(
+          // Chrome doesn't use interface versioning.
+          // TODO(falken): Is that comment about versioning correct?
+          mojo::PendingRemote<mojom::blink::WorkerContentSettingsProxy>(
+              std::move(content_settings_handle), 0u)),
+      std::move(initiator_thread_task_runner));
 }
 
 void WebEmbeddedWorkerImpl::TerminateWorkerContext() {
@@ -202,6 +195,9 @@
 }
 
 void WebEmbeddedWorkerImpl::StartWorkerThread(
+    std::unique_ptr<ServiceWorkerInstalledScriptsManager>
+        installed_scripts_manager,
+    std::unique_ptr<ServiceWorkerContentSettingsProxy> content_settings_proxy,
     scoped_refptr<base::SingleThreadTaskRunner> initiator_thread_task_runner) {
   DCHECK(!asked_to_terminate_);
 
@@ -242,9 +238,9 @@
   String source_code;
   std::unique_ptr<Vector<uint8_t>> cached_meta_data;
 
-  bool is_script_installed = installed_scripts_manager_ &&
-                             installed_scripts_manager_->IsScriptInstalled(
-                                 worker_start_data_.script_url);
+  bool is_script_installed =
+      installed_scripts_manager && installed_scripts_manager->IsScriptInstalled(
+                                       worker_start_data_.script_url);
 
   // We don't have to set ContentSecurityPolicy and ReferrerPolicy. They're
   // served by the worker script loader or the installed scripts manager on the
@@ -255,7 +251,7 @@
       worker_start_data_.user_agent, std::move(web_worker_fetch_context),
       Vector<CSPHeaderAndType>(), network::mojom::ReferrerPolicy::kDefault,
       starter_origin.get(), starter_secure_context, starter_https_state,
-      nullptr /* worker_clients */, std::move(content_settings_client_),
+      nullptr /* worker_clients */, std::move(content_settings_proxy),
       base::nullopt /* response_address_space */,
       nullptr /* OriginTrialTokens */, devtools_worker_token_,
       std::move(worker_settings),
@@ -272,7 +268,7 @@
   worker_thread_ = std::make_unique<ServiceWorkerThread>(
       std::make_unique<ServiceWorkerGlobalScopeProxy>(
           *this, *worker_context_client_, initiator_thread_task_runner),
-      std::move(installed_scripts_manager_), std::move(cache_storage_remote_),
+      std::move(installed_scripts_manager), std::move(cache_storage_remote_),
       initiator_thread_task_runner);
 
   auto devtools_params = std::make_unique<WorkerDevToolsParams>();
diff --git a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
index c4e8c18..c4d15f3 100644
--- a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
+++ b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
@@ -63,28 +63,31 @@
  public:
   WebEmbeddedWorkerImpl(
       WebServiceWorkerContextClient*,
-      std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>,
-      std::unique_ptr<ServiceWorkerContentSettingsProxy>,
       mojo::PendingRemote<mojom::blink::CacheStorage>,
       service_manager::mojom::blink::InterfaceProviderPtrInfo,
       mojo::PendingRemote<mojom::blink::BrowserInterfaceBroker>);
   ~WebEmbeddedWorkerImpl() override;
 
   // WebEmbeddedWorker overrides.
-  void StartWorkerContext(const WebEmbeddedWorkerStartData&,
-                          scoped_refptr<base::SingleThreadTaskRunner>
-                              initiator_thread_task_runner) override;
+  void StartWorkerContext(
+      const WebEmbeddedWorkerStartData&,
+      std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>,
+      mojo::ScopedMessagePipeHandle content_settings_handle,
+      scoped_refptr<base::SingleThreadTaskRunner> initiator_thread_task_runner)
+      override;
   void TerminateWorkerContext() override;
   void ResumeAfterDownload() override;
 
   static std::unique_ptr<WebEmbeddedWorkerImpl> CreateForTesting(
-      WebServiceWorkerContextClient*,
-      std::unique_ptr<ServiceWorkerInstalledScriptsManager>);
+      WebServiceWorkerContextClient*);
 
   void WaitForShutdownForTesting();
 
  private:
-  void StartWorkerThread(scoped_refptr<base::SingleThreadTaskRunner>);
+  void StartWorkerThread(
+      std::unique_ptr<ServiceWorkerInstalledScriptsManager>,
+      std::unique_ptr<ServiceWorkerContentSettingsProxy>,
+      scoped_refptr<base::SingleThreadTaskRunner> initiator_thread_task_runner);
 
   // Creates a cross-thread copyable outside settings object for top-level
   // worker script fetch.
@@ -96,12 +99,6 @@
   // Client must remain valid through the entire life time of the worker.
   WebServiceWorkerContextClient* const worker_context_client_;
 
-  // These are valid until StartWorkerThread() is called. After the worker
-  // thread is created, these are passed to the worker thread.
-  std::unique_ptr<ServiceWorkerInstalledScriptsManager>
-      installed_scripts_manager_;
-  std::unique_ptr<ServiceWorkerContentSettingsProxy> content_settings_client_;
-
   std::unique_ptr<ServiceWorkerThread> worker_thread_;
 
   bool asked_to_terminate_ = false;
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_audio_test.cc b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_audio_test.cc
index a1028f4..e5605bb 100644
--- a/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_audio_test.cc
+++ b/third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_audio_test.cc
@@ -34,6 +34,22 @@
 using blink::AudioProcessingProperties;
 using EchoCancellationType = AudioProcessingProperties::EchoCancellationType;
 
+// Test blink::Platform imlementation that overrides the known methods needed
+// by the tests, including creation of WebRtcAudioDevice instances.
+class WebRtcAudioDeviceTestingPlatformSupport
+    : public IOTaskRunnerTestingPlatformSupport {
+ public:
+  WebRtcAudioDeviceTestingPlatformSupport()
+      : webrtc_audio_device_(
+            new rtc::RefCountedObject<WebRtcAudioDeviceImpl>()) {}
+  blink::WebRtcAudioDeviceImpl* GetWebRtcAudioDevice() override {
+    return webrtc_audio_device_.get();
+  }
+
+ private:
+  scoped_refptr<WebRtcAudioDeviceImpl> webrtc_audio_device_;
+};
+
 namespace {
 
 using BoolSetFunction = void (blink::BooleanConstraint::*)(bool);
@@ -434,7 +450,8 @@
       blink::WebString::FromASCII("system")};
 
  private:
-  ScopedTestingPlatformSupport<IOTaskRunnerTestingPlatformSupport> platform_;
+  ScopedTestingPlatformSupport<WebRtcAudioDeviceTestingPlatformSupport>
+      platform_;
 };
 
 class MediaStreamConstraintsUtilAudioTest
diff --git a/third_party/blink/renderer/modules/mediastream/media_stream_renderer_factory_impl.cc b/third_party/blink/renderer/modules/mediastream/media_stream_renderer_factory_impl.cc
index 57715ca..fdab8d4 100644
--- a/third_party/blink/renderer/modules/mediastream/media_stream_renderer_factory_impl.cc
+++ b/third_party/blink/renderer/modules/mediastream/media_stream_renderer_factory_impl.cc
@@ -11,7 +11,6 @@
 #include "third_party/blink/public/platform/platform.h"
 #include "third_party/blink/public/platform/web_media_stream.h"
 #include "third_party/blink/public/web/modules/mediastream/media_stream_video_track.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
 #include "third_party/blink/public/web/modules/webrtc/webrtc_audio_device_impl.h"
 #include "third_party/blink/public/web/modules/webrtc/webrtc_audio_renderer.h"
 #include "third_party/blink/public/web/web_local_frame.h"
@@ -33,7 +32,7 @@
 // will not be able to pick an appropriate device and return 0.
 base::UnguessableToken GetSessionIdForWebRtcAudioRenderer() {
   WebRtcAudioDeviceImpl* audio_device =
-      PeerConnectionDependencyFactory::GetInstance()->GetWebRtcAudioDevice();
+      Platform::Current()->GetWebRtcAudioDevice();
   return audio_device
              ? audio_device->GetAuthorizedDeviceSessionIdForAudioRenderer()
              : base::UnguessableToken();
@@ -118,7 +117,7 @@
 
   // This is a remote WebRTC media stream.
   WebRtcAudioDeviceImpl* audio_device =
-      PeerConnectionDependencyFactory::GetInstance()->GetWebRtcAudioDevice();
+      Platform::Current()->GetWebRtcAudioDevice();
   DCHECK(audio_device);
 
   // Share the existing renderer if any, otherwise create a new one.
diff --git a/third_party/blink/renderer/modules/mediastream/processed_local_audio_source.cc b/third_party/blink/renderer/modules/mediastream/processed_local_audio_source.cc
index 740459b9..7dee523 100644
--- a/third_party/blink/renderer/modules/mediastream/processed_local_audio_source.cc
+++ b/third_party/blink/renderer/modules/mediastream/processed_local_audio_source.cc
@@ -21,7 +21,6 @@
 #include "third_party/blink/public/platform/modules/webrtc/webrtc_logging.h"
 #include "third_party/blink/public/platform/platform.h"
 #include "third_party/blink/public/web/modules/mediastream/media_stream_constraints_util.h"
-#include "third_party/blink/public/web/modules/peerconnection/peer_connection_dependency_factory.h"
 #include "third_party/blink/public/web/modules/webrtc/webrtc_audio_device_impl.h"
 #include "third_party/blink/renderer/modules/mediastream/media_stream_audio_processor.h"
 #include "third_party/blink/renderer/modules/mediastream/media_stream_local_frame_wrapper.h"
@@ -203,7 +202,7 @@
   // Create the MediaStreamAudioProcessor, bound to the WebRTC audio device
   // module.
   WebRtcAudioDeviceImpl* const rtc_audio_device =
-      PeerConnectionDependencyFactory::GetInstance()->GetWebRtcAudioDevice();
+      Platform::Current()->GetWebRtcAudioDevice();
   if (!rtc_audio_device) {
     blink::WebRtcLogMessage(
         "ProcessedLocalAudioSource::EnsureSourceIsStarted() fails"
@@ -327,8 +326,7 @@
   scoped_refptr<media::AudioCapturerSource> source_to_stop(std::move(source_));
 
   if (WebRtcAudioDeviceImpl* rtc_audio_device =
-          PeerConnectionDependencyFactory::GetInstance()
-              ->GetWebRtcAudioDevice()) {
+          Platform::Current()->GetWebRtcAudioDevice()) {
     rtc_audio_device->RemoveAudioCapturer(this);
   }
 
diff --git a/third_party/blink/renderer/modules/mediastream/processed_local_audio_source_test.cc b/third_party/blink/renderer/modules/mediastream/processed_local_audio_source_test.cc
index 9ea18522..3a6d0a9e 100644
--- a/third_party/blink/renderer/modules/mediastream/processed_local_audio_source_test.cc
+++ b/third_party/blink/renderer/modules/mediastream/processed_local_audio_source_test.cc
@@ -69,11 +69,14 @@
 MockAudioCapturerSource::~MockAudioCapturerSource() {}
 
 // Test Platform implementation that overrides the known methods needed
-// by the tests, including creation of AudioCapturerSource instances.
-class AudioCapturerSourceTestingPlatformSupport
-    : public TestingPlatformSupport {
+// by the tests, including creation of WebRtcAudioDevice and
+// AudioCapturerSource instances.
+class WebRtcAudioDeviceTestingPlatformSupport : public TestingPlatformSupport {
  public:
-  AudioCapturerSourceTestingPlatformSupport() = default;
+  WebRtcAudioDeviceTestingPlatformSupport() = default;
+  WebRtcAudioDeviceImpl* GetWebRtcAudioDevice() override {
+    return audio_device_.get();
+  }
 
   scoped_refptr<media::AudioCapturerSource> NewAudioCapturerSource(
       WebLocalFrame* web_frame,
@@ -88,6 +91,8 @@
   }
 
  private:
+  scoped_refptr<blink::WebRtcAudioDeviceImpl> audio_device_ =
+      new rtc::RefCountedObject<blink::WebRtcAudioDeviceImpl>();
   scoped_refptr<MockAudioCapturerSource> mock_audio_capturer_source_ =
       base::MakeRefCounted<MockAudioCapturerSource>();
 };
@@ -183,7 +188,7 @@
   }
 
  private:
-  ScopedTestingPlatformSupport<AudioCapturerSourceTestingPlatformSupport>
+  ScopedTestingPlatformSupport<WebRtcAudioDeviceTestingPlatformSupport>
       webrtc_audio_device_platform_support_;
   WebMediaStreamSource blink_audio_source_;
   WebMediaStreamTrack blink_audio_track_;
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc
index b85a9f3..59dfc40 100644
--- a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc
+++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.cc
@@ -191,10 +191,10 @@
   return result;
 }
 
-mojom::blink::NativeFileSystemTransferTokenPtr
+mojo::PendingRemote<mojom::blink::NativeFileSystemTransferToken>
 NativeFileSystemDirectoryHandle::Transfer() {
-  mojom::blink::NativeFileSystemTransferTokenPtr result;
-  mojo_ptr_->Transfer(mojo::MakeRequest(&result));
+  mojo::PendingRemote<mojom::blink::NativeFileSystemTransferToken> result;
+  mojo_ptr_->Transfer(result.InitWithNewPipeAndPassReceiver());
   return result;
 }
 
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h
index 14e9b3e..562274b 100644
--- a/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h
+++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h
@@ -5,6 +5,7 @@
 #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_HANDLE_H_
 #define THIRD_PARTY_BLINK_RENDERER_MODULES_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_DIRECTORY_HANDLE_H_
 
+#include "mojo/public/cpp/bindings/pending_remote.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom-blink.h"
 #include "third_party/blink/renderer/modules/native_file_system/native_file_system_handle.h"
 #include "third_party/blink/renderer/platform/mojo/revocable_interface_ptr.h"
@@ -39,7 +40,8 @@
   static ScriptPromise getSystemDirectory(ScriptState*,
                                           const GetSystemDirectoryOptions*);
 
-  mojom::blink::NativeFileSystemTransferTokenPtr Transfer() override;
+  mojo::PendingRemote<mojom::blink::NativeFileSystemTransferToken> Transfer()
+      override;
 
   mojom::blink::NativeFileSystemDirectoryHandle* MojoHandle() {
     return mojo_ptr_.get();
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.cc b/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.cc
index 8dd25fc..4aa7bd1 100644
--- a/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.cc
+++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.cc
@@ -76,10 +76,10 @@
   return result;
 }
 
-mojom::blink::NativeFileSystemTransferTokenPtr
+mojo::PendingRemote<mojom::blink::NativeFileSystemTransferToken>
 NativeFileSystemFileHandle::Transfer() {
-  mojom::blink::NativeFileSystemTransferTokenPtr result;
-  mojo_ptr_->Transfer(mojo::MakeRequest(&result));
+  mojo::PendingRemote<mojom::blink::NativeFileSystemTransferToken> result;
+  mojo_ptr_->Transfer(result.InitWithNewPipeAndPassReceiver());
   return result;
 }
 
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.h b/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.h
index 4f7abf5b..8eab490 100644
--- a/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.h
+++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.h
@@ -5,6 +5,7 @@
 #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_FILE_HANDLE_H_
 #define THIRD_PARTY_BLINK_RENDERER_MODULES_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_FILE_HANDLE_H_
 
+#include "mojo/public/cpp/bindings/pending_remote.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_file_handle.mojom-blink.h"
 #include "third_party/blink/renderer/modules/native_file_system/native_file_system_handle.h"
 #include "third_party/blink/renderer/platform/mojo/revocable_interface_ptr.h"
@@ -26,7 +27,8 @@
                              const FileSystemCreateWriterOptions* options);
   ScriptPromise getFile(ScriptState*);
 
-  mojom::blink::NativeFileSystemTransferTokenPtr Transfer() override;
+  mojo::PendingRemote<mojom::blink::NativeFileSystemTransferToken> Transfer()
+      override;
 
   mojom::blink::NativeFileSystemFileHandle* MojoHandle() {
     return mojo_ptr_.get();
diff --git a/third_party/blink/renderer/modules/native_file_system/native_file_system_handle.h b/third_party/blink/renderer/modules/native_file_system/native_file_system_handle.h
index b93edad2..fb6ed67 100644
--- a/third_party/blink/renderer/modules/native_file_system/native_file_system_handle.h
+++ b/third_party/blink/renderer/modules/native_file_system/native_file_system_handle.h
@@ -5,6 +5,7 @@
 #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_HANDLE_H_
 #define THIRD_PARTY_BLINK_RENDERER_MODULES_NATIVE_FILE_SYSTEM_NATIVE_FILE_SYSTEM_HANDLE_H_
 
+#include "mojo/public/cpp/bindings/pending_remote.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom-blink-forward.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_error.mojom-blink-forward.h"
 #include "third_party/blink/public/mojom/native_file_system/native_file_system_transfer_token.mojom-blink-forward.h"
@@ -37,7 +38,8 @@
   ScriptPromise requestPermission(ScriptState*,
                                   const FileSystemHandlePermissionDescriptor*);
 
-  virtual mojom::blink::NativeFileSystemTransferTokenPtr Transfer() = 0;
+  virtual mojo::PendingRemote<mojom::blink::NativeFileSystemTransferToken>
+  Transfer() = 0;
 
  private:
   virtual void QueryPermissionImpl(
diff --git a/third_party/blink/renderer/modules/peerconnection/BUILD.gn b/third_party/blink/renderer/modules/peerconnection/BUILD.gn
index 0e6bfea..57d4956 100644
--- a/third_party/blink/renderer/modules/peerconnection/BUILD.gn
+++ b/third_party/blink/renderer/modules/peerconnection/BUILD.gn
@@ -53,7 +53,6 @@
     "call_setup_state_tracker.cc",
     "call_setup_state_tracker.h",
     "media_stream_remote_video_source.cc",
-    "peer_connection_dependency_factory.cc",
     "rtc_certificate.cc",
     "rtc_certificate.h",
     "rtc_data_channel.cc",
diff --git a/third_party/blink/renderer/modules/peerconnection/DEPS b/third_party/blink/renderer/modules/peerconnection/DEPS
index 0206484..f84dc56 100644
--- a/third_party/blink/renderer/modules/peerconnection/DEPS
+++ b/third_party/blink/renderer/modules/peerconnection/DEPS
@@ -1,4 +1,5 @@
 include_rules = [
+    "+services/metrics/public/cpp/ukm_builders.h",
     "-third_party/blink/renderer/modules",
     "+third_party/blink/renderer/modules/crypto",
     "+third_party/blink/renderer/modules/event_modules.h",
@@ -6,17 +7,11 @@
     "+third_party/blink/renderer/modules/mediastream",
     "+third_party/blink/renderer/modules/modules_export.h",
     "+third_party/blink/renderer/modules/peerconnection",
-
-    "+crypto/openssl_util.h",
-    "+jingle/glue/thread_wrapper.h",
     "+media/base",
-    "+media/media_buildflags.h",
-    "+media/video/gpu_video_accelerator_factories.h",
     "+net/third_party/quiche/src/quic",
     "+net/quic/chromium",
     "+net/quic",
     "+net/test",
-    "+services/metrics/public/cpp/ukm_builders.h",
 ]
 
 specific_include_rules = {
diff --git a/third_party/blink/renderer/modules/service_worker/fetch_event.cc b/third_party/blink/renderer/modules/service_worker/fetch_event.cc
index 78d1139..cf4f35e 100644
--- a/third_party/blink/renderer/modules/service_worker/fetch_event.cc
+++ b/third_party/blink/renderer/modules/service_worker/fetch_event.cc
@@ -20,6 +20,7 @@
 #include "third_party/blink/renderer/modules/service_worker/service_worker_global_scope.h"
 #include "third_party/blink/renderer/platform/bindings/script_state.h"
 #include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
 #include "third_party/blink/renderer/platform/network/network_utils.h"
 
diff --git a/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc b/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
index 5841f33b..fe572faf 100644
--- a/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
+++ b/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
@@ -18,7 +18,6 @@
 #include "third_party/blink/public/common/messaging/message_port_channel.h"
 #include "third_party/blink/public/mojom/service_worker/controller_service_worker_mode.mojom-blink.h"
 #include "third_party/blink/public/mojom/service_worker/service_worker.mojom-blink.h"
-#include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom-blink.h"
 #include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom-blink.h"
 #include "third_party/blink/public/platform/platform.h"
 #include "third_party/blink/public/platform/web_content_settings_client.h"
@@ -29,8 +28,6 @@
 #include "third_party/blink/public/web/modules/service_worker/web_service_worker_context_proxy.h"
 #include "third_party/blink/public/web/web_embedded_worker_start_data.h"
 #include "third_party/blink/public/web/web_settings.h"
-#include "third_party/blink/renderer/modules/service_worker/service_worker_installed_scripts_manager.h"
-#include "third_party/blink/renderer/modules/service_worker/thread_safe_script_container.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
 #include "third_party/blink/renderer/platform/runtime_enabled_features.h"
 #include "third_party/blink/renderer/platform/scheduler/test/fake_task_runner.h"
@@ -194,41 +191,11 @@
   base::WaitableEvent classic_script_load_failure_event_;
 };
 
-class MockServiceWorkerInstalledScriptsManager
-    : public ServiceWorkerInstalledScriptsManager {
- public:
-  MockServiceWorkerInstalledScriptsManager()
-      : ServiceWorkerInstalledScriptsManager(
-            Vector<KURL>() /* installed_urls */,
-            mojo::PendingReceiver<
-                mojom::blink::ServiceWorkerInstalledScriptsManager>(
-                mojo::MessagePipe().handle1),
-            mojo::PendingRemote<
-                mojom::blink::ServiceWorkerInstalledScriptsManagerHost>(
-                mojo::MessagePipe().handle0,
-                mojom::blink::ServiceWorkerInstalledScriptsManagerHost::
-                    Version_),
-            // Pass a temporary task runner to ensure
-            // ServiceWorkerInstalledScriptsManager construction succeeds.
-            Platform::Current()
-                ->CreateThread(ThreadCreationParams(WebThreadType::kTestThread)
-                                   .SetThreadNameForTest("io thread"))
-                ->GetTaskRunner()) {}
-  MOCK_CONST_METHOD1(IsScriptInstalled, bool(const KURL& script_url));
-  MOCK_METHOD1(GetRawScriptData,
-               std::unique_ptr<ThreadSafeScriptContainer::RawScriptData>(
-                   const KURL& script_url));
-};
-
 class WebEmbeddedWorkerImplTest : public testing::Test {
  protected:
   void SetUp() override {
-    auto installed_scripts_manager =
-        std::make_unique<MockServiceWorkerInstalledScriptsManager>();
-    mock_installed_scripts_manager_ = installed_scripts_manager.get();
     mock_client_ = std::make_unique<MockServiceWorkerContextClient>();
-    worker_ = WebEmbeddedWorkerImpl::CreateForTesting(
-        mock_client_.get(), std::move(installed_scripts_manager));
+    worker_ = WebEmbeddedWorkerImpl::CreateForTesting(mock_client_.get());
 
     WebURL script_url =
         url_test_helpers::ToKURL("https://www.example.com/sw.js");
@@ -254,14 +221,17 @@
 
   WebEmbeddedWorkerStartData start_data_;
   std::unique_ptr<MockServiceWorkerContextClient> mock_client_;
-  MockServiceWorkerInstalledScriptsManager* mock_installed_scripts_manager_;
   std::unique_ptr<WebEmbeddedWorkerImpl> worker_;
 };
 
 }  // namespace
 
 TEST_F(WebEmbeddedWorkerImplTest, TerminateSoonAfterStart) {
-  worker_->StartWorkerContext(start_data_, Thread::Current()->GetTaskRunner());
+  worker_->StartWorkerContext(
+      start_data_,
+      /*installed_scripts_manager_params=*/nullptr,
+      /*content_settings_proxy=*/mojo::ScopedMessagePipeHandle(),
+      Thread::Current()->GetTaskRunner());
   testing::Mock::VerifyAndClearExpectations(mock_client_.get());
 
   worker_->TerminateWorkerContext();
@@ -272,7 +242,11 @@
 TEST_F(WebEmbeddedWorkerImplTest, TerminateWhileWaitingForDebugger) {
   start_data_.wait_for_debugger_mode =
       WebEmbeddedWorkerStartData::kWaitForDebugger;
-  worker_->StartWorkerContext(start_data_, Thread::Current()->GetTaskRunner());
+  worker_->StartWorkerContext(
+      start_data_,
+      /*installed_scripts_manager_params=*/nullptr,
+      /*content_settings_proxy=*/mojo::ScopedMessagePipeHandle(),
+      Thread::Current()->GetTaskRunner());
   testing::Mock::VerifyAndClearExpectations(mock_client_.get());
 
   worker_->TerminateWorkerContext();
@@ -281,13 +255,12 @@
 
 TEST_F(WebEmbeddedWorkerImplTest, TerminateWhileLoadingScript) {
   // Load the shadow page.
-  EXPECT_CALL(*mock_installed_scripts_manager_,
-              IsScriptInstalled(KURL(start_data_.script_url)))
-      .Times(testing::AtLeast(1))
-      .WillRepeatedly(testing::Return(false));
-  worker_->StartWorkerContext(start_data_, Thread::Current()->GetTaskRunner());
+  worker_->StartWorkerContext(
+      start_data_,
+      /*installed_scripts_manager_params=*/nullptr,
+      /*content_settings_proxy=*/mojo::ScopedMessagePipeHandle(),
+      Thread::Current()->GetTaskRunner());
   testing::Mock::VerifyAndClearExpectations(mock_client_.get());
-  testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_);
 
   // Terminate before finishing the script load.
   worker_->TerminateWorkerContext();
@@ -305,14 +278,14 @@
   Platform::Current()->GetURLLoaderMockFactory()->RegisterErrorURL(
       script_url, response, error);
   start_data_.script_url = script_url;
-  EXPECT_CALL(*mock_installed_scripts_manager_,
-              IsScriptInstalled(KURL(start_data_.script_url)))
-      .Times(testing::AtLeast(1))
-      .WillRepeatedly(testing::Return(false));
+
   // Start worker and load the script.
-  worker_->StartWorkerContext(start_data_, Thread::Current()->GetTaskRunner());
+  worker_->StartWorkerContext(
+      start_data_,
+      /*installed_scripts_manager_params=*/nullptr,
+      /*content_settings_proxy=*/mojo::ScopedMessagePipeHandle(),
+      Thread::Current()->GetTaskRunner());
   testing::Mock::VerifyAndClearExpectations(mock_client_.get());
-  testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_);
 
   mock_client_->WaitUntilFailedToLoadClassicScript();
 
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc b/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc
index 1af046f..728ce1d 100644
--- a/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc
+++ b/third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.cc
@@ -177,6 +177,9 @@
     // stopped appending to the vector so the pointers aren't invalidated.
     uint32_t attributeIndex = 0;
     for (DawnVertexBufferDescriptor& buffer : dawn_vertex_buffers) {
+      if (buffer.attributeCount == 0) {
+        continue;
+      }
       buffer.attributes = &dawn_vertex_attributes[attributeIndex];
       attributeIndex += buffer.attributeCount;
     }
diff --git a/third_party/blink/renderer/modules/xr/xr.cc b/third_party/blink/renderer/modules/xr/xr.cc
index f0b3f495..1c70a5e5 100644
--- a/third_party/blink/renderer/modules/xr/xr.cc
+++ b/third_party/blink/renderer/modules/xr/xr.cc
@@ -554,15 +554,6 @@
     did_log_request_immersive_session_ = true;
   }
 
-  // If its an immersive AR session, make sure that feature is enabled
-  if (query->mode() == XRSession::kModeImmersiveAR &&
-      !RuntimeEnabledFeatures::WebXRARModuleEnabled(doc)) {
-    query->RejectWithTypeError(
-        String::Format(kImmersiveArModeNotValid, "requestSession"),
-        exception_state);
-    return;
-  }
-
   // Make sure the request is allowed
   auto* immersive_session_request_error =
       CheckImmersiveSessionRequestAllowed(frame, doc);
@@ -669,6 +660,22 @@
 
   XRSession::SessionMode session_mode = stringToSessionMode(mode);
 
+  // If the request is for immersive-ar, ensure that feature is enabled.
+  if (session_mode == XRSession::kModeImmersiveAR &&
+      !RuntimeEnabledFeatures::WebXRARModuleEnabled(doc)) {
+    exception_state.ThrowTypeError(
+        String::Format(kImmersiveArModeNotValid, "requestSession"));
+
+    // We haven't created the query yet, so we can't use it to implicitly log
+    // our metrics for us, so explicitly log it here, as the query requires the
+    // features to be parsed before it can be built.
+    ukm::builders::XR_WebXR_SessionRequest(GetSourceId())
+        .SetMode(static_cast<int64_t>(session_mode))
+        .SetStatus(static_cast<int64_t>(SessionRequestStatus::kOtherError))
+        .Record(doc->UkmRecorder());
+    return ScriptPromise();
+  }
+
   // Parse required feature strings
   RequestedXRSessionFeatureSet required_features;
   if (session_init && session_init->hasRequiredFeatures()) {
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn
index c891f629..70b2115 100644
--- a/third_party/blink/renderer/platform/BUILD.gn
+++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -1230,29 +1230,9 @@
     "mojo/string16_mojom_traits.cc",
     "mojo/string16_mojom_traits.h",
     "p2p/empty_network_manager.cc",
-    "p2p/empty_network_manager.h",
     "p2p/filtering_network_manager.cc",
-    "p2p/filtering_network_manager.h",
-    "p2p/host_address_request.cc",
-    "p2p/host_address_request.h",
     "p2p/ipc_network_manager.cc",
-    "p2p/ipc_network_manager.h",
-    "p2p/ipc_socket_factory.cc",
-    "p2p/ipc_socket_factory.h",
-    "p2p/mdns_responder_adapter.cc",
-    "p2p/mdns_responder_adapter.h",
-    "p2p/network_list_manager.h",
-    "p2p/network_list_observer.h",
     "p2p/network_manager_uma.cc",
-    "p2p/network_manager_uma.h",
-    "p2p/port_allocator.cc",
-    "p2p/port_allocator.h",
-    "p2p/socket_client.h",
-    "p2p/socket_client_delegate.h",
-    "p2p/socket_client_impl.cc",
-    "p2p/socket_client_impl.h",
-    "p2p/socket_dispatcher.cc",
-    "p2p/socket_dispatcher.h",
     "peerconnection/audio_codec_factory.cc",
     "peerconnection/rtc_answer_options_platform.h",
     "peerconnection/rtc_dtmf_sender_handler.cc",
@@ -1277,11 +1257,9 @@
     "peerconnection/rtc_video_encoder_factory.h",
     "peerconnection/rtc_void_request.h",
     "peerconnection/stun_field_trial.cc",
-    "peerconnection/stun_field_trial.h",
     "peerconnection/transmission_encoding_info_handler.cc",
     "peerconnection/transmission_encoding_info_handler.h",
     "peerconnection/video_codec_factory.cc",
-    "peerconnection/video_codec_factory.h",
     "peerconnection/webrtc_audio_sink.cc",
     "peerconnection/webrtc_video_track_source.cc",
     "prerender.cc",
diff --git a/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
index 5d4d046f..69aeb35e 100644
--- a/third_party/blink/renderer/platform/exported/web_runtime_features.cc
+++ b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -637,8 +637,8 @@
   RuntimeEnabledFeatures::SetGetDisplayMediaEnabled(enable);
 }
 
-void WebRuntimeFeatures::EnableForbidSyncXHRInPageDismissal(bool enable) {
-  RuntimeEnabledFeatures::SetForbidSyncXHRInPageDismissalEnabled(enable);
+void WebRuntimeFeatures::EnableAllowSyncXHRInPageDismissal(bool enable) {
+  RuntimeEnabledFeatures::SetAllowSyncXHRInPageDismissalEnabled(enable);
 }
 
 void WebRuntimeFeatures::EnableShadowDOMV0(bool enable) {
diff --git a/third_party/blink/renderer/platform/exported/web_url_response.cc b/third_party/blink/renderer/platform/exported/web_url_response.cc
index d39db582..9c5957e 100644
--- a/third_party/blink/renderer/platform/exported/web_url_response.cc
+++ b/third_party/blink/renderer/platform/exported/web_url_response.cc
@@ -41,6 +41,7 @@
 #include "third_party/blink/public/platform/web_string.h"
 #include "third_party/blink/public/platform/web_url.h"
 #include "third_party/blink/public/platform/web_url_load_timing.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_info.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
 #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
diff --git a/third_party/blink/renderer/platform/graphics/bitmap_image.cc b/third_party/blink/renderer/platform/graphics/bitmap_image.cc
index b52d106c..effb974 100644
--- a/third_party/blink/renderer/platform/graphics/bitmap_image.cc
+++ b/third_party/blink/renderer/platform/graphics/bitmap_image.cc
@@ -451,14 +451,14 @@
 }
 
 DarkModeClassification BitmapImage::CheckTypeSpecificConditionsForDarkMode(
-    const FloatRect& src_rect,
+    const FloatRect& dest_rect,
     DarkModeImageClassifier* classifier) {
-  if (src_rect.Width() < kMinImageSizeForClassification1D ||
-      src_rect.Height() < kMinImageSizeForClassification1D)
+  if (dest_rect.Width() < kMinImageSizeForClassification1D ||
+      dest_rect.Height() < kMinImageSizeForClassification1D)
     return DarkModeClassification::kApplyFilter;
 
-  if (src_rect.Width() > kMaxImageSizeForClassification1D ||
-      src_rect.Height() > kMaxImageSizeForClassification1D) {
+  if (dest_rect.Width() > kMaxImageSizeForClassification1D ||
+      dest_rect.Height() > kMaxImageSizeForClassification1D) {
     return DarkModeClassification::kDoNotApplyFilter;
   }
 
diff --git a/third_party/blink/renderer/platform/graphics/bitmap_image.h b/third_party/blink/renderer/platform/graphics/bitmap_image.h
index 06e3461..b73b4ca 100644
--- a/third_party/blink/renderer/platform/graphics/bitmap_image.h
+++ b/third_party/blink/renderer/platform/graphics/bitmap_image.h
@@ -102,7 +102,7 @@
   }
 
   DarkModeClassification CheckTypeSpecificConditionsForDarkMode(
-      const FloatRect& src_rect,
+      const FloatRect& dest_rect,
       DarkModeImageClassifier* classifier) override;
 
  protected:
diff --git a/third_party/blink/renderer/platform/graphics/dark_mode_filter.cc b/third_party/blink/renderer/platform/graphics/dark_mode_filter.cc
index 9d9a97e4..0a10700 100644
--- a/third_party/blink/renderer/platform/graphics/dark_mode_filter.cc
+++ b/third_party/blink/renderer/platform/graphics/dark_mode_filter.cc
@@ -45,6 +45,7 @@
 
 bool ShouldApplyToImage(const DarkModeSettings& settings,
                         const FloatRect& src_rect,
+                        const FloatRect& dest_rect,
                         Image* image) {
   switch (settings.image_policy) {
     case DarkModeImagePolicy::kFilterSmart: {
@@ -61,7 +62,8 @@
           break;
         }
       }
-      DarkModeClassification result = classifier->Classify(image, src_rect);
+      DarkModeClassification result =
+          classifier->Classify(image, src_rect, dest_rect);
       return result == DarkModeClassification::kApplyFilter;
     }
     case DarkModeImagePolicy::kFilterNone:
@@ -133,9 +135,11 @@
 }
 
 void DarkModeFilter::ApplyToImageFlagsIfNeeded(const FloatRect& src_rect,
+                                               const FloatRect& dest_rect,
                                                Image* image,
                                                cc::PaintFlags* flags) {
-  if (!image_filter_ || !ShouldApplyToImage(settings(), src_rect, image))
+  if (!image_filter_ ||
+      !ShouldApplyToImage(settings(), src_rect, dest_rect, image))
     return;
   flags->setColorFilter(image_filter_);
 }
diff --git a/third_party/blink/renderer/platform/graphics/dark_mode_filter.h b/third_party/blink/renderer/platform/graphics/dark_mode_filter.h
index 81ccf428..6c96642 100644
--- a/third_party/blink/renderer/platform/graphics/dark_mode_filter.h
+++ b/third_party/blink/renderer/platform/graphics/dark_mode_filter.h
@@ -45,6 +45,7 @@
 
   // |image| and |flags| must not be null.
   void ApplyToImageFlagsIfNeeded(const FloatRect& src_rect,
+                                 const FloatRect& dest_rect,
                                  Image* image,
                                  cc::PaintFlags* flags);
 
diff --git a/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.cc b/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.cc
index db10ff1..906b4e78 100644
--- a/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.cc
+++ b/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.cc
@@ -39,12 +39,13 @@
 
 DarkModeClassification DarkModeImageClassifier::Classify(
     Image* image,
-    const FloatRect& src_rect) {
+    const FloatRect& src_rect,
+    const FloatRect& dest_rect) {
   DarkModeClassification result = image->GetDarkModeClassification(src_rect);
   if (result != DarkModeClassification::kNotClassified)
     return result;
 
-  result = image->CheckTypeSpecificConditionsForDarkMode(src_rect, this);
+  result = image->CheckTypeSpecificConditionsForDarkMode(dest_rect, this);
   if (result != DarkModeClassification::kNotClassified) {
     image->AddDarkModeClassification(src_rect, result);
     return result;
diff --git a/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.h b/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.h
index 445379c..a54f2593 100644
--- a/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.h
+++ b/third_party/blink/renderer/platform/graphics/dark_mode_image_classifier.h
@@ -22,7 +22,9 @@
   DarkModeImageClassifier();
   ~DarkModeImageClassifier() = default;
 
-  DarkModeClassification Classify(Image* image, const FloatRect& src_rect);
+  DarkModeClassification Classify(Image* image,
+                                  const FloatRect& src_rect,
+                                  const FloatRect& dest_rect);
 
   struct Features {
     // True if the image is in color, false if it is grayscale.
diff --git a/third_party/blink/renderer/platform/graphics/gradient_generated_image.h b/third_party/blink/renderer/platform/graphics/gradient_generated_image.h
index 94b047d..66641fb 100644
--- a/third_party/blink/renderer/platform/graphics/gradient_generated_image.h
+++ b/third_party/blink/renderer/platform/graphics/gradient_generated_image.h
@@ -46,7 +46,7 @@
   bool ApplyShader(PaintFlags&, const SkMatrix&) override;
 
   DarkModeClassification CheckTypeSpecificConditionsForDarkMode(
-      const FloatRect& src_rect,
+      const FloatRect& dest_rect,
       DarkModeImageClassifier* classifier) override {
     return DarkModeClassification::kApplyFilter;
   }
diff --git a/third_party/blink/renderer/platform/graphics/graphics_context.cc b/third_party/blink/renderer/platform/graphics/graphics_context.cc
index 77eaebd..883de3be 100644
--- a/third_party/blink/renderer/platform/graphics/graphics_context.cc
+++ b/third_party/blink/renderer/platform/graphics/graphics_context.cc
@@ -928,7 +928,7 @@
   image_flags.setColor(SK_ColorBLACK);
   image_flags.setFilterQuality(ComputeFilterQuality(image, dest, src));
 
-  dark_mode_filter_.ApplyToImageFlagsIfNeeded(src, image, &image_flags);
+  dark_mode_filter_.ApplyToImageFlagsIfNeeded(src, dest, image, &image_flags);
 
   image->Draw(canvas_, image_flags, dest, src, should_respect_image_orientation,
               Image::kClampImageToSourceRect, decode_mode);
@@ -964,7 +964,8 @@
   image_flags.setFilterQuality(
       ComputeFilterQuality(image, dest.Rect(), src_rect));
 
-  dark_mode_filter_.ApplyToImageFlagsIfNeeded(src_rect, image, &image_flags);
+  dark_mode_filter_.ApplyToImageFlagsIfNeeded(src_rect, dest.Rect(), image,
+                                              &image_flags);
 
   bool use_shader = (visible_src == src_rect) &&
                     (respect_orientation == kDoNotRespectImageOrientation);
diff --git a/third_party/blink/renderer/platform/graphics/image.h b/third_party/blink/renderer/platform/graphics/image.h
index eb1a444e..445dbd8f 100644
--- a/third_party/blink/renderer/platform/graphics/image.h
+++ b/third_party/blink/renderer/platform/graphics/image.h
@@ -241,7 +241,7 @@
   // need to be checked before the classification algorithms are applied
   // on the image.
   virtual DarkModeClassification CheckTypeSpecificConditionsForDarkMode(
-      const FloatRect& src_rect,
+      const FloatRect& dest_rect,
       DarkModeImageClassifier* classifier) {
     return DarkModeClassification::kDoNotApplyFilter;
   }
diff --git a/third_party/blink/renderer/platform/heap/heap.cc b/third_party/blink/renderer/platform/heap/heap.cc
index cf51d3a..ee036d0a 100644
--- a/third_party/blink/renderer/platform/heap/heap.cc
+++ b/third_party/blink/renderer/platform/heap/heap.cc
@@ -547,29 +547,25 @@
 #undef SNAPSHOT_ARENA
 }
 
-bool ThreadHeap::AdvanceLazySweep(base::TimeTicks deadline) {
-  static const base::TimeDelta slack = base::TimeDelta::FromSecondsD(0.001);
-  for (int i = 0; i < BlinkGC::kNumberOfArenas; i++) {
+bool ThreadHeap::AdvanceSweep(SweepingType sweeping_type,
+                              base::TimeTicks deadline) {
+  static constexpr base::TimeDelta slack = base::TimeDelta::FromSecondsD(0.001);
+  auto sweeping_function = sweeping_type == SweepingType::kMutator
+                               ? &BaseArena::LazySweepWithDeadline
+                               : &BaseArena::ConcurrentSweepWithDeadline;
+  for (size_t i = 0; i < BlinkGC::kNumberOfArenas; i++) {
     // lazySweepWithDeadline() won't check the deadline until it sweeps
     // 10 pages. So we give a small slack for safety.
     const base::TimeDelta remaining_budget =
         deadline - slack - base::TimeTicks::Now();
     if (remaining_budget <= base::TimeDelta() ||
-        !arenas_[i]->LazySweepWithDeadline(deadline)) {
+        !(arenas_[i]->*sweeping_function)(deadline)) {
       return false;
     }
   }
   return true;
 }
 
-void ThreadHeap::ConcurrentSweep() {
-  // Concurrent sweep simply sweeps pages not calling finalizers.
-  for (size_t i = BlinkGC::kNormalPage1ArenaIndex;
-       i < BlinkGC::kNumberOfArenas; i++) {
-    arenas_[i]->SweepOnConcurrentThread();
-  }
-}
-
 // TODO(omerkatz): Temporary solution until concurrent marking is ready. see
 // https://crrev.com/c/1730054 for details. Eventually this will be removed.
 void ThreadHeap::FlushV8References() {
diff --git a/third_party/blink/renderer/platform/heap/heap.h b/third_party/blink/renderer/platform/heap/heap.h
index 2bde952..e5a7316a 100644
--- a/third_party/blink/renderer/platform/heap/heap.h
+++ b/third_party/blink/renderer/platform/heap/heap.h
@@ -386,9 +386,8 @@
 
   void Compact();
 
-  bool AdvanceLazySweep(base::TimeTicks deadline);
-
-  void ConcurrentSweep();
+  enum class SweepingType : uint8_t { kMutator, kConcurrent };
+  bool AdvanceSweep(SweepingType sweeping_type, base::TimeTicks deadline);
 
   void PrepareForSweep();
   void RemoveAllPages();
diff --git a/third_party/blink/renderer/platform/heap/heap_page.cc b/third_party/blink/renderer/platform/heap/heap_page.cc
index 7c4ac6d..abb957b 100644
--- a/third_party/blink/renderer/platform/heap/heap_page.cc
+++ b/third_party/blink/renderer/platform/heap/heap_page.cc
@@ -312,13 +312,13 @@
   // Platform::current()->monotonicallyIncreasingTimeSeconds() per page (i.e.,
   // 128 KB sweep or one LargeObject sweep), so we check the deadline per 10
   // pages.
-  static const int kDeadlineCheckInterval = 10;
+  static constexpr size_t kDeadlineCheckInterval = 10;
 
   CHECK(GetThreadState()->IsSweepingInProgress());
   DCHECK(GetThreadState()->SweepForbidden());
   DCHECK(ScriptForbiddenScope::IsScriptForbidden());
 
-  int page_count = 1;
+  size_t page_count = 1;
   // TODO(bikineev): We should probably process pages in the reverse order. This
   // will leave more work for concurrent sweeper and reduce memory footprint
   // faster.
@@ -370,10 +370,18 @@
   }
 }
 
-void BaseArena::SweepOnConcurrentThread() {
+bool BaseArena::ConcurrentSweepWithDeadline(base::TimeTicks deadline) {
+  static constexpr size_t kDeadlineCheckInterval = 10;
+  size_t page_count = 1;
   while (BasePage* page = unswept_pages_.PopLocked()) {
     SweepUnsweptPageOnConcurrentThread(page);
+    if (page_count % kDeadlineCheckInterval == 0 &&
+        deadline <= base::TimeTicks::Now()) {
+      return SweepingCompleted();
+    }
+    ++page_count;
   }
+  return true;
 }
 
 void BaseArena::CompleteSweep() {
diff --git a/third_party/blink/renderer/platform/heap/heap_page.h b/third_party/blink/renderer/platform/heap/heap_page.h
index 644ea9a..19f301e 100644
--- a/third_party/blink/renderer/platform/heap/heap_page.h
+++ b/third_party/blink/renderer/platform/heap/heap_page.h
@@ -907,8 +907,8 @@
   // Returns true if we have swept all pages within the deadline. Returns false
   // otherwise.
   bool LazySweepWithDeadline(base::TimeTicks deadline);
+  bool ConcurrentSweepWithDeadline(base::TimeTicks deadline);
   void CompleteSweep();
-  void SweepOnConcurrentThread();
   void InvokeFinalizersOnSweptPages();
 
   ThreadState* GetThreadState() { return thread_state_; }
diff --git a/third_party/blink/renderer/platform/heap/heap_test.cc b/third_party/blink/renderer/platform/heap/heap_test.cc
index 9fbcf444..a3b0d0a 100644
--- a/third_party/blink/renderer/platform/heap/heap_test.cc
+++ b/third_party/blink/renderer/platform/heap/heap_test.cc
@@ -6093,7 +6093,7 @@
   }
   BaseArena* map_arena = PageFromObject(map)->Arena();
   // Sweep normal arena, but don't call finalizers.
-  map_arena->SweepOnConcurrentThread();
+  map_arena->ConcurrentSweepWithDeadline(base::TimeTicks::Max());
   // Now complete sweeping with PerformIdleLazySweep and call finalizers.
   while (thread_state->IsSweepingInProgress()) {
     thread_state->PerformIdleLazySweep(base::TimeTicks::Max());
diff --git a/third_party/blink/renderer/platform/heap/thread_state.cc b/third_party/blink/renderer/platform/heap/thread_state.cc
index e64aebb2..026f3e7 100644
--- a/third_party/blink/renderer/platform/heap/thread_state.cc
+++ b/third_party/blink/renderer/platform/heap/thread_state.cc
@@ -426,7 +426,8 @@
     ThreadHeapStatsCollector::EnabledScope stats_scope(
         Heap().stats_collector(), ThreadHeapStatsCollector::kLazySweepInIdle,
         "idleDeltaInSeconds", (deadline - base::TimeTicks::Now()).InSecondsF());
-    sweep_completed = Heap().AdvanceLazySweep(deadline);
+    sweep_completed =
+        Heap().AdvanceSweep(ThreadHeap::SweepingType::kMutator, deadline);
     // We couldn't finish the sweeping within the deadline.
     // We request another idle task for the remaining sweeping.
     if (sweep_completed) {
@@ -444,11 +445,25 @@
 void ThreadState::PerformConcurrentSweep() {
   VLOG(2) << "[state:" << this << "] [threadid:" << CurrentThread() << "] "
           << "ConcurrentSweep";
+  // As opposed to PerformIdleLazySweep, this function doesn't receive deadline
+  // from the scheduler, but defines it itself.
+  static constexpr base::TimeDelta kConcurrentSweepStepDuration =
+      base::TimeDelta::FromMilliseconds(2);
   // Concurrent sweeper doesn't call finalizers - this guarantees that sweeping
   // is not called recursively.
   ThreadHeapStatsCollector::EnabledConcurrentScope stats_scope(
       Heap().stats_collector(), ThreadHeapStatsCollector::kConcurrentSweep);
-  Heap().ConcurrentSweep();
+  const bool finished = Heap().AdvanceSweep(
+      ThreadHeap::SweepingType::kConcurrent,
+      base::TimeTicks::Now() + kConcurrentSweepStepDuration);
+  if (!finished) {
+    // Reschedule itself. It is safe even if the task timeouts and reposts
+    // itself while the mutator thread is waiting on CancelAndWait(). The
+    // mutator thread will simply wake up and cancel the newly post task itself.
+    sweeper_scheduler_->ScheduleTask(
+        WTF::CrossThreadBindOnce(&ThreadState::PerformConcurrentSweep,
+                                 WTF::CrossThreadUnretained(this)));
+  }
 }
 
 void ThreadState::ScheduleIncrementalMarkingStep() {
diff --git a/third_party/blink/renderer/platform/loader/allowed_by_nosniff.cc b/third_party/blink/renderer/platform/loader/allowed_by_nosniff.cc
index 7c53cfe..927f24b 100644
--- a/third_party/blink/renderer/platform/loader/allowed_by_nosniff.cc
+++ b/third_party/blink/renderer/platform/loader/allowed_by_nosniff.cc
@@ -4,6 +4,7 @@
 
 #include "third_party/blink/renderer/platform/loader/allowed_by_nosniff.h"
 
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
 #include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
 #include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h"
 #include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
diff --git a/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc b/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc
index 9e9914f..13b03795 100644
--- a/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc
+++ b/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc
@@ -236,6 +236,10 @@
   return static_cast<SingleCachedMetadataHandler*>(Resource::CacheHandler());
 }
 
+scoped_refptr<BlobDataHandle> RawResource::DownloadedBlob() const {
+  return downloaded_blob_;
+}
+
 void RawResource::Trace(Visitor* visitor) {
   visitor->Trace(bytes_consumer_for_preload_);
   Resource::Trace(visitor);
@@ -403,6 +407,9 @@
   return Resource::CanReuse(new_fetch_parameters);
 }
 
+void RawResourceClient::DidDownloadToBlob(Resource*,
+                                          scoped_refptr<BlobDataHandle>) {}
+
 RawResourceClientStateChecker::RawResourceClientStateChecker()
     : state_(kNotAddedAsClient) {}
 
diff --git a/third_party/blink/renderer/platform/loader/fetch/raw_resource.h b/third_party/blink/renderer/platform/loader/fetch/raw_resource.h
index 6108bd35..8dcb65c 100644
--- a/third_party/blink/renderer/platform/loader/fetch/raw_resource.h
+++ b/third_party/blink/renderer/platform/loader/fetch/raw_resource.h
@@ -92,9 +92,7 @@
   // type is kRaw.
   SingleCachedMetadataHandler* ScriptCacheHandler();
 
-  scoped_refptr<BlobDataHandle> DownloadedBlob() const {
-    return downloaded_blob_;
-  }
+  scoped_refptr<BlobDataHandle> DownloadedBlob() const;
 
   void Trace(Visitor* visitor) override;
 
@@ -201,7 +199,7 @@
   // null if creating the blob failed for some reason (but the download itself
   // otherwise succeeded). Could also not be called at all if the downloaded
   // resource ended up being zero bytes.
-  virtual void DidDownloadToBlob(Resource*, scoped_refptr<BlobDataHandle>) {}
+  virtual void DidDownloadToBlob(Resource*, scoped_refptr<BlobDataHandle>);
 };
 
 // Checks the sequence of callbacks of RawResourceClient. This can be used only
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource.cc b/third_party/blink/renderer/platform/loader/fetch/resource.cc
index a76ad93..d1e114b 100644
--- a/third_party/blink/renderer/platform/loader/fetch/resource.cc
+++ b/third_party/blink/renderer/platform/loader/fetch/resource.cc
@@ -50,6 +50,7 @@
 #include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_finish_observer.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_loader.h"
 #include "third_party/blink/renderer/platform/network/http_parsers.h"
 #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
@@ -393,6 +394,8 @@
   return LastResourceRequest().RequestorOrigin();
 }
 
+void Resource::DidDownloadToBlob(scoped_refptr<BlobDataHandle>) {}
+
 static base::TimeDelta CurrentAge(const ResourceResponse& response,
                                   base::Time response_timestamp) {
   // RFC2616 13.2.3
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource.h b/third_party/blink/renderer/platform/loader/fetch/resource.h
index b8ae4568..c5f00ea 100644
--- a/third_party/blink/renderer/platform/loader/fetch/resource.h
+++ b/third_party/blink/renderer/platform/loader/fetch/resource.h
@@ -349,7 +349,7 @@
   virtual void DidSendData(uint64_t /* bytesSent */,
                            uint64_t /* totalBytesToBeSent */) {}
   virtual void DidDownloadData(uint64_t) {}
-  virtual void DidDownloadToBlob(scoped_refptr<BlobDataHandle>) {}
+  virtual void DidDownloadToBlob(scoped_refptr<BlobDataHandle>);
 
   base::TimeTicks LoadResponseEnd() const { return load_response_end_; }
 
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
index c82689a..9aa36b58 100644
--- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
+++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
@@ -63,6 +63,7 @@
 #include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_load_observer.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_loader.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_loading_log.h"
 #include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_response.cc b/third_party/blink/renderer/platform/loader/fetch/resource_response.cc
index 2a6ebc62..d258b67 100644
--- a/third_party/blink/renderer/platform/loader/fetch/resource_response.cc
+++ b/third_party/blink/renderer/platform/loader/fetch/resource_response.cc
@@ -31,7 +31,11 @@
 #include <memory>
 #include <string>
 
+#include "services/network/public/cpp/cors/cors.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
 #include "third_party/blink/public/platform/web_url_response.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_info.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/network/http_names.h"
 #include "third_party/blink/renderer/platform/network/http_parsers.h"
 #include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -76,15 +80,21 @@
       signature_data_.IsolatedCopy());
 }
 
-ResourceResponse::ResourceResponse() : is_null_(true) {}
+ResourceResponse::ResourceResponse()
+    : is_null_(true),
+      response_type_(network::mojom::FetchResponseType::kDefault) {}
 
 ResourceResponse::ResourceResponse(const KURL& current_request_url)
-    : current_request_url_(current_request_url), is_null_(false) {}
+    : current_request_url_(current_request_url),
+      is_null_(false),
+      response_type_(network::mojom::FetchResponseType::kDefault) {}
 
 ResourceResponse::ResourceResponse(const ResourceResponse&) = default;
 ResourceResponse& ResourceResponse::operator=(const ResourceResponse&) =
     default;
 
+ResourceResponse::~ResourceResponse() = default;
+
 bool ResourceResponse::IsHTTP() const {
   return current_request_url_.ProtocolIsInHTTPFamily();
 }
@@ -229,6 +239,14 @@
       san_list, issuer, valid_from, valid_to, certificate, sct_list);
 }
 
+bool ResourceResponse::IsCorsSameOrigin() const {
+  return network::cors::IsCorsSameOriginResponseType(response_type_);
+}
+
+bool ResourceResponse::IsCorsCrossOrigin() const {
+  return network::cors::IsCorsCrossOriginResponseType(response_type_);
+}
+
 void ResourceResponse::SetHttpHeaderField(const AtomicString& name,
                                           const AtomicString& value) {
   UpdateHeaderParsedState(name);
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_response.h b/third_party/blink/renderer/platform/loader/fetch/resource_response.h
index 9ab904b..3c6bc71c 100644
--- a/third_party/blink/renderer/platform/loader/fetch/resource_response.h
+++ b/third_party/blink/renderer/platform/loader/fetch/resource_response.h
@@ -33,12 +33,7 @@
 #include "base/memory/scoped_refptr.h"
 #include "base/optional.h"
 #include "base/time/time.h"
-#include "services/network/public/cpp/cors/cors.h"
-#include "services/network/public/mojom/fetch_api.mojom-blink.h"
 #include "third_party/blink/public/platform/web_url_response.h"
-#include "third_party/blink/renderer/platform/blob/blob_data.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_load_info.h"
-#include "third_party/blink/renderer/platform/loader/fetch/resource_load_timing.h"
 #include "third_party/blink/renderer/platform/network/http_header_map.h"
 #include "third_party/blink/renderer/platform/network/http_parsers.h"
 #include "third_party/blink/renderer/platform/platform_export.h"
@@ -50,6 +45,9 @@
 
 namespace blink {
 
+class ResourceLoadTiming;
+struct ResourceLoadInfo;
+
 // A ResourceResponse is a "response" object used in blink. Conceptually
 // it is https://fetch.spec.whatwg.org/#concept-response, but it contains
 // a lot of blink specific fields. WebURLResponse is the "public version"
@@ -163,6 +161,7 @@
   explicit ResourceResponse(const KURL& current_request_url);
   ResourceResponse(const ResourceResponse&);
   ResourceResponse& operator=(const ResourceResponse&);
+  ~ResourceResponse();
 
   bool IsNull() const { return is_null_; }
   bool IsHTTP() const;
@@ -334,13 +333,9 @@
     response_type_ = value;
   }
   // https://html.spec.whatwg.org/C/#cors-same-origin
-  bool IsCorsSameOrigin() const {
-    return network::cors::IsCorsSameOriginResponseType(response_type_);
-  }
+  bool IsCorsSameOrigin() const;
   // https://html.spec.whatwg.org/C/#cors-cross-origin
-  bool IsCorsCrossOrigin() const {
-    return network::cors::IsCorsCrossOriginResponseType(response_type_);
-  }
+  bool IsCorsCrossOrigin() const;
 
   // See network::ResourceResponseInfo::url_list_via_service_worker.
   const Vector<KURL>& UrlListViaServiceWorker() const {
@@ -529,8 +524,7 @@
   bool from_archive_ = false;
 
   // https://fetch.spec.whatwg.org/#concept-response-type
-  network::mojom::FetchResponseType response_type_ =
-      network::mojom::FetchResponseType::kDefault;
+  network::mojom::FetchResponseType response_type_;
 
   // HTTP version used in the response, if known.
   HTTPVersion http_version_ = kHTTPVersionUnknown;
diff --git a/third_party/blink/renderer/platform/loader/subresource_integrity.cc b/third_party/blink/renderer/platform/loader/subresource_integrity.cc
index 83b457f..e3333add 100644
--- a/third_party/blink/renderer/platform/loader/subresource_integrity.cc
+++ b/third_party/blink/renderer/platform/loader/subresource_integrity.cc
@@ -5,6 +5,7 @@
 #include "third_party/blink/renderer/platform/loader/subresource_integrity.h"
 
 #include "base/stl_util.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
 #include "third_party/blink/public/platform/web_crypto.h"
 #include "third_party/blink/public/platform/web_crypto_algorithm.h"
 #include "third_party/blink/renderer/platform/crypto.h"
diff --git a/third_party/blink/renderer/platform/p2p/DEPS b/third_party/blink/renderer/platform/p2p/DEPS
index 4dca1d57..51f66cb 100644
--- a/third_party/blink/renderer/platform/p2p/DEPS
+++ b/third_party/blink/renderer/platform/p2p/DEPS
@@ -1,13 +1,7 @@
 include_rules = [
-    "+base/observer_list_threadsafe.h",
-    "+crypto/random.h",
-    "+jingle/glue/utils.h",
     "+media/base/media_permission.h",
+    "+jingle/glue/utils.h",
     "+net/base/ip_address.h",
-    "+net/base/ip_endpoint.h",
     "+net/base/network_change_notifier.h",
     "+net/base/network_interfaces.h",
-    "+net/traffic_annotation/network_traffic_annotation.h",
-    "+services/network/public/cpp/p2p_param_traits.h",
-    "+services/network/public/cpp/p2p_socket_type.h",
 ]
diff --git a/third_party/blink/renderer/platform/p2p/empty_network_manager.cc b/third_party/blink/renderer/platform/p2p/empty_network_manager.cc
index 4895e42..9422a0d64 100644
--- a/third_party/blink/renderer/platform/p2p/empty_network_manager.cc
+++ b/third_party/blink/renderer/platform/p2p/empty_network_manager.cc
@@ -2,13 +2,13 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/empty_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/empty_network_manager.h"
 
 #include "base/bind.h"
 #include "base/location.h"
 #include "base/logging.h"
 #include "base/threading/thread_task_runner_handle.h"
-#include "third_party/blink/renderer/platform/p2p/network_manager_uma.h"
+#include "third_party/blink/public/platform/modules/p2p/network_manager_uma.h"
 
 namespace blink {
 
diff --git a/third_party/blink/renderer/platform/p2p/filtering_network_manager.cc b/third_party/blink/renderer/platform/p2p/filtering_network_manager.cc
index 0f7994e..71efbae 100644
--- a/third_party/blink/renderer/platform/p2p/filtering_network_manager.cc
+++ b/third_party/blink/renderer/platform/p2p/filtering_network_manager.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/filtering_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/filtering_network_manager.h"
 
 #include <utility>
 
diff --git a/third_party/blink/renderer/platform/p2p/filtering_network_manager_test.cc b/third_party/blink/renderer/platform/p2p/filtering_network_manager_test.cc
index a928561..0732a2b 100644
--- a/third_party/blink/renderer/platform/p2p/filtering_network_manager_test.cc
+++ b/third_party/blink/renderer/platform/p2p/filtering_network_manager_test.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/filtering_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/filtering_network_manager.h"
 
 #include <stddef.h>
 
@@ -18,7 +18,7 @@
 #include "media/base/media_permission.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/platform/p2p/empty_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/empty_network_manager.h"
 #include "third_party/webrtc/rtc_base/ip_address.h"
 
 using NetworkList = rtc::NetworkManager::NetworkList;
diff --git a/third_party/blink/renderer/platform/p2p/ipc_network_manager.cc b/third_party/blink/renderer/platform/p2p/ipc_network_manager.cc
index 1ac806d..52d7d120 100644
--- a/third_party/blink/renderer/platform/p2p/ipc_network_manager.cc
+++ b/third_party/blink/renderer/platform/p2p/ipc_network_manager.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/ipc_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/ipc_network_manager.h"
 
 #include <string>
 #include <utility>
diff --git a/third_party/blink/renderer/platform/p2p/ipc_network_manager_test.cc b/third_party/blink/renderer/platform/p2p/ipc_network_manager_test.cc
index b00dc6f..152dd782 100644
--- a/third_party/blink/renderer/platform/p2p/ipc_network_manager_test.cc
+++ b/third_party/blink/renderer/platform/p2p/ipc_network_manager_test.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/ipc_network_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/ipc_network_manager.h"
 
 #include <algorithm>
 #include <memory>
@@ -11,7 +11,7 @@
 #include "net/base/network_change_notifier.h"
 #include "net/base/network_interfaces.h"
 #include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/platform/p2p/network_list_manager.h"
+#include "third_party/blink/public/platform/modules/p2p/network_list_manager.h"
 #include "third_party/webrtc/rtc_base/mdns_responder_interface.h"
 
 namespace blink {
diff --git a/third_party/blink/renderer/platform/p2p/network_manager_uma.cc b/third_party/blink/renderer/platform/p2p/network_manager_uma.cc
index b21e0a4..f98a9442 100644
--- a/third_party/blink/renderer/platform/p2p/network_manager_uma.cc
+++ b/third_party/blink/renderer/platform/p2p/network_manager_uma.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/p2p/network_manager_uma.h"
+#include "third_party/blink/public/platform/modules/p2p/network_manager_uma.h"
 
 #include "base/metrics/histogram_macros.h"
 #include "base/time/time.h"
diff --git a/third_party/blink/renderer/platform/peerconnection/DEPS b/third_party/blink/renderer/platform/peerconnection/DEPS
index 5bff309..c422df2 100644
--- a/third_party/blink/renderer/platform/peerconnection/DEPS
+++ b/third_party/blink/renderer/platform/peerconnection/DEPS
@@ -3,7 +3,6 @@
     "-third_party/blink/renderer/platform",
 
     # Module.
-    "+third_party/blink/renderer/platform/p2p",
     "+third_party/blink/renderer/platform/peerconnection",
     "+third_party/blink/renderer/platform/media_capabilities",
     "+third_party/blink/renderer/platform/webrtc",
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc
index 2ab30075..ba2a0ab10 100644
--- a/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc
+++ b/third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.cc
@@ -10,6 +10,7 @@
 #include "base/memory/ptr_util.h"
 #include "build/build_config.h"
 #include "media/video/gpu_video_accelerator_factories.h"
+#include "third_party/blink/public/platform/modules/peerconnection/rtc_video_decoder_factory_util.h"
 #include "third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_adapter.h"
 
 namespace blink {
@@ -58,6 +59,11 @@
 
 }  // namespace
 
+std::unique_ptr<webrtc::VideoDecoderFactory> CreateRTCVideoDecoderFactory(
+    media::GpuVideoAcceleratorFactories* gpu_factories) {
+  return std::make_unique<RTCVideoDecoderFactory>(gpu_factories);
+}
+
 RTCVideoDecoderFactory::RTCVideoDecoderFactory(
     media::GpuVideoAcceleratorFactories* gpu_factories)
     : gpu_factories_(gpu_factories) {
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.cc b/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.cc
index fc5bcb11..a0943b8 100644
--- a/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.cc
+++ b/third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.cc
@@ -11,6 +11,7 @@
 #include "media/media_buildflags.h"
 #include "media/video/gpu_video_accelerator_factories.h"
 #include "third_party/blink/public/common/features.h"
+#include "third_party/blink/public/platform/modules/peerconnection/rtc_video_encoder_factory_util.h"
 #include "third_party/blink/renderer/platform/peerconnection/rtc_video_encoder.h"
 #include "third_party/webrtc/api/video_codecs/sdp_video_format.h"
 #include "third_party/webrtc/api/video_codecs/video_encoder.h"
@@ -103,6 +104,11 @@
 
 }  // anonymous namespace
 
+std::unique_ptr<webrtc::VideoEncoderFactory> CreateRTCVideoEncoderFactory(
+    media::GpuVideoAcceleratorFactories* gpu_factories) {
+  return std::make_unique<RTCVideoEncoderFactory>(gpu_factories);
+}
+
 RTCVideoEncoderFactory::RTCVideoEncoderFactory(
     media::GpuVideoAcceleratorFactories* gpu_factories)
     : gpu_factories_(gpu_factories) {
diff --git a/third_party/blink/renderer/platform/peerconnection/stun_field_trial.cc b/third_party/blink/renderer/platform/peerconnection/stun_field_trial.cc
index bd64f2e0..2182823 100644
--- a/third_party/blink/renderer/platform/peerconnection/stun_field_trial.cc
+++ b/third_party/blink/renderer/platform/peerconnection/stun_field_trial.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/peerconnection/stun_field_trial.h"
+#include "third_party/blink/public/platform/modules/peerconnection/stun_field_trial.h"
 
 #include <math.h>
 
diff --git a/third_party/blink/renderer/platform/peerconnection/stun_field_trial_test.cc b/third_party/blink/renderer/platform/peerconnection/stun_field_trial_test.cc
index e48d6c04..719c30e7 100644
--- a/third_party/blink/renderer/platform/peerconnection/stun_field_trial_test.cc
+++ b/third_party/blink/renderer/platform/peerconnection/stun_field_trial_test.cc
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/peerconnection/stun_field_trial.h"
+#include "third_party/blink/public/platform/modules/peerconnection/stun_field_trial.h"
 
 #include "testing/gtest/include/gtest/gtest.h"
 #include "third_party/webrtc/rtc_base/socket_address.h"
diff --git a/third_party/blink/renderer/platform/peerconnection/transmission_encoding_info_handler.cc b/third_party/blink/renderer/platform/peerconnection/transmission_encoding_info_handler.cc
index 9ce0d60..753f0e8 100644
--- a/third_party/blink/renderer/platform/peerconnection/transmission_encoding_info_handler.cc
+++ b/third_party/blink/renderer/platform/peerconnection/transmission_encoding_info_handler.cc
@@ -11,10 +11,10 @@
 #include "base/logging.h"
 #include "base/system/sys_info.h"
 #include "third_party/blink/public/platform/modules/peerconnection/audio_codec_factory.h"
+#include "third_party/blink/public/platform/modules/peerconnection/video_codec_factory.h"
 #include "third_party/blink/public/platform/platform.h"
 #include "third_party/blink/renderer/platform/media_capabilities/web_media_configuration.h"
 #include "third_party/blink/renderer/platform/media_capabilities/web_video_configuration.h"
-#include "third_party/blink/renderer/platform/peerconnection/video_codec_factory.h"
 #include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
 #include "third_party/webrtc/api/audio_codecs/audio_encoder_factory.h"
 #include "third_party/webrtc/api/audio_codecs/audio_format.h"
diff --git a/third_party/blink/renderer/platform/peerconnection/video_codec_factory.cc b/third_party/blink/renderer/platform/peerconnection/video_codec_factory.cc
index 85ae4df..5adc8b1 100644
--- a/third_party/blink/renderer/platform/peerconnection/video_codec_factory.cc
+++ b/third_party/blink/renderer/platform/peerconnection/video_codec_factory.cc
@@ -2,14 +2,14 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#include "third_party/blink/renderer/platform/peerconnection/video_codec_factory.h"
+#include "third_party/blink/public/platform/modules/peerconnection/video_codec_factory.h"
 
 #include "base/memory/ptr_util.h"
 #include "build/build_config.h"
 #include "media/video/gpu_video_accelerator_factories.h"
+#include "third_party/blink/public/platform/modules/peerconnection/rtc_video_decoder_factory_util.h"
+#include "third_party/blink/public/platform/modules/peerconnection/rtc_video_encoder_factory_util.h"
 #include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/renderer/platform/peerconnection/rtc_video_decoder_factory.h"
-#include "third_party/blink/renderer/platform/peerconnection/rtc_video_encoder_factory.h"
 #include "third_party/webrtc/api/video_codecs/video_decoder_software_fallback_wrapper.h"
 #include "third_party/webrtc/api/video_codecs/video_encoder_software_fallback_wrapper.h"
 #include "third_party/webrtc/media/base/codec.h"
@@ -178,7 +178,7 @@
 
   if (gpu_factories && gpu_factories->IsGpuVideoAcceleratorEnabled() &&
       Platform::Current()->IsWebRtcHWEncodingEnabled()) {
-    encoder_factory = std::make_unique<RTCVideoEncoderFactory>(gpu_factories);
+    encoder_factory = blink::CreateRTCVideoEncoderFactory(gpu_factories);
   }
 
 #if defined(OS_ANDROID)
@@ -195,7 +195,7 @@
 
   if (gpu_factories && gpu_factories->IsGpuVideoAcceleratorEnabled() &&
       Platform::Current()->IsWebRtcHWDecodingEnabled()) {
-    decoder_factory = std::make_unique<RTCVideoDecoderFactory>(gpu_factories);
+    decoder_factory = blink::CreateRTCVideoDecoderFactory(gpu_factories);
   }
 
   return std::make_unique<DecoderAdapter>(std::move(decoder_factory));
diff --git a/third_party/blink/renderer/platform/peerconnection/video_codec_factory.h b/third_party/blink/renderer/platform/peerconnection/video_codec_factory.h
deleted file mode 100644
index 522d9ae..0000000
--- a/third_party/blink/renderer/platform/peerconnection/video_codec_factory.h
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_PEERCONNECTION_VIDEO_CODEC_FACTORY_H_
-#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_PEERCONNECTION_VIDEO_CODEC_FACTORY_H_
-
-#include "third_party/blink/renderer/platform/platform_export.h"
-#include "third_party/webrtc/api/video_codecs/video_decoder_factory.h"
-#include "third_party/webrtc/api/video_codecs/video_encoder_factory.h"
-
-namespace media {
-class GpuVideoAcceleratorFactories;
-}
-
-namespace blink {
-
-PLATFORM_EXPORT std::unique_ptr<webrtc::VideoEncoderFactory>
-CreateWebrtcVideoEncoderFactory(
-    media::GpuVideoAcceleratorFactories* gpu_factories);
-PLATFORM_EXPORT std::unique_ptr<webrtc::VideoDecoderFactory>
-CreateWebrtcVideoDecoderFactory(
-    media::GpuVideoAcceleratorFactories* gpu_factories);
-
-}  // namespace blink
-
-#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_PEERCONNECTION_VIDEO_CODEC_FACTORY_H_
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5
index 3894793..28abbbf8 100644
--- a/third_party/blink/renderer/platform/runtime_enabled_features.json5
+++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -120,6 +120,11 @@
       status: "stable",
     },
     {
+      name: "AllowSyncXHRInPageDismissal",
+      origin_trial_feature_name: "AllowSyncXHRInPageDismissal",
+      status: "experimental",
+    },
+    {
       name: "AnimationWorklet",
       origin_trial_feature_name: "AnimationWorklet",
       status: "experimental",
@@ -699,10 +704,6 @@
     },
     // For simulating Android's overlay fullscreen video in web tests on Linux.
     {
-      name: "ForbidSyncXHRInPageDismissal",
-      status: "experimental",
-    },
-    {
       name: "ForcedColors",
     },
     {
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
index e0aaf3d..3da70d2 100755
--- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
+++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -839,18 +839,8 @@
             'third_party/blink/renderer/bindings/modules/v8/serialization',
         ],
         'allowed': [
-            # TODO(crbug.com/787254): Remove base::BindOnce, base::Unretained,
-            # base::MessageLoopCurrent.
-            'base::BindOnce',
-            "base::MessageLoopCurrent",
-            'base::Unretained',
             'cricket::.*',
-            'jingle_glue::JingleThreadWrapper',
-            # TODO(crbug.com/787254): Remove GURL usage.
-            'GURL',
             'media::.+',
-            'net::NetworkTrafficAnnotationTag',
-            'net::DefineNetworkTrafficAnnotation',
             'rtc::.+',
             'webrtc::.+',
             'quic::.+',
diff --git a/third_party/blink/tools/lldb/lldb_blink.py b/third_party/blink/tools/lldb/lldb_blink.py
index 1c263f0..121b182 100644
--- a/third_party/blink/tools/lldb/lldb_blink.py
+++ b/third_party/blink/tools/lldb/lldb_blink.py
@@ -142,22 +142,30 @@
     def get_length(self):
         return self.valobj.GetChildMemberWithName('length_').GetValueAsUnsigned(0)
 
-    def get_data8(self):
-        # FIXME: This should be the equivalent of reinterpret_cast<LChar*>(self.valobj + 1)
-        return self.valobj.GetChildAtIndex(2).GetChildMemberWithName('m_data8')
-
-    def get_data16(self):
-        # FIXME: This should be the equivalent of reinterpret_cast<UChar*>(self.valobj + 1)
-        return self.valobj.GetChildAtIndex(2).GetChildMemberWithName('m_data16')
-
     def to_string(self):
+        val_type = self.valobj.GetType()
+        process = self.valobj.GetProcess()
+        endianness = process.GetByteOrder()
+        pointer_size = process.GetAddressByteSize()
+        offset = val_type.GetPointeeType().GetByteSize()
+
+        char_start = self.valobj.GetValueAsUnsigned(0) + offset
+        pointer = lldb.SBData.CreateDataFromUInt64Array(endianness, pointer_size, [char_start])
         error = lldb.SBError()
         if self.is_8bit():
-            return lstring_to_string(self.get_data8(), error, self.get_length())
-        return ustring_to_string(self.get_data16(), error, self.get_length())
+            return lstring_to_string(
+                self.valobj.CreateValueFromData(
+                    'str_impl', pointer,
+                    val_type.GetBasicType(lldb.eBasicTypeChar).GetPointerType()),
+                error, self.get_length())
+        return ustring_to_string(
+            self.valobj.CreateValueFromData(
+                'str_impl', pointer,
+                val_type.GetBasicType(lldb.eBasicTypeUnsignedChar).GetPointerType()),
+            error, self.get_length())
 
     def is_8bit(self):
-        return self.valobj.GetChildMemberWithName('is_8bit_')
+        return self.valobj.GetChildMemberWithName('is_8bit_').GetValueAsUnsigned(0)
 
 
 class WTFStringProvider:
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer b/third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer
index d560397..b655cbc 100644
--- a/third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer
+++ b/third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer
@@ -1,5 +1,2 @@
 # One portion of the image is offset.
 crbug.com/1002522 fast/canvas/canvas-toDataURL-webp.html [ Skip ]
-
-# Blurring is not pixelated.
-crbug.com/1002525 fast/canvas/pixelated.html [ Skip ]
diff --git a/third_party/blink/web_tests/MSANExpectations b/third_party/blink/web_tests/MSANExpectations
index 630a76ea..e1c202b 100644
--- a/third_party/blink/web_tests/MSANExpectations
+++ b/third_party/blink/web_tests/MSANExpectations
@@ -158,7 +158,6 @@
 crbug.com/856601 [ Linux ] virtual/feature-policy-permissions/external/wpt/mediacapture-streams/idlharness.https.window.html [ Pass Timeout ]
 crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Timeout Pass ]
 crbug.com/856601 [ Linux ] virtual/service-worker-servicification/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Timeout Pass ]
-crbug.com/856601 [ Linux ] virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Timeout Pass ]
 crbug.com/856601 [ Linux ] virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Pass Timeout ]
 crbug.com/856601 [ Linux ] virtual/omt-service-worker-startup/external/wpt/service-workers/service-worker/interfaces-sw.https.html [ Pass Failure Timeout ]
 crbug.com/856601 [ Linux ] external/wpt/fetch/api/idl.any.sharedworker.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests
index 9ceda36c..715d091 100644
--- a/third_party/blink/web_tests/NeverFixTests
+++ b/third_party/blink/web_tests/NeverFixTests
@@ -1838,9 +1838,6 @@
 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ]
 virtual/omt-worker-fetch/external/wpt/xhr/send-authentication-existing-session-manual.htm [ WontFix ]
 virtual/omt-worker-fetch/external/wpt/xhr/send-authentication-prompt-2-manual.htm [ WontFix ]
-virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-event-is-history-backward-navigation-manual.https.html [ WontFix ]
-virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-event-is-history-forward-navigation-manual.https.html [ WontFix ]
-virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ]
 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-event-is-history-backward-navigation-manual.https.html [ WontFix ]
 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-event-is-history-forward-navigation-manual.https.html [ WontFix ]
 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-event-is-reload-navigation-manual.https.html [ WontFix ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations
index 497f84d..14048d6 100644
--- a/third_party/blink/web_tests/TestExpectations
+++ b/third_party/blink/web_tests/TestExpectations
@@ -3062,7 +3062,6 @@
 # Failure messages are unstable so we cannot create baselines.
 crbug.com/832071 external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ]
 crbug.com/832071 virtual/navigation-mojo-response/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ]
-crbug.com/832071 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ]
 crbug.com/832071 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ]
 crbug.com/832071 virtual/omt-service-worker-startup/external/wpt/service-workers/service-worker/worker-client-id.https.html [ Failure ]
 
@@ -3222,97 +3221,43 @@
 
 crbug.com/1002514 external/wpt/web-share/share-sharePromise-internal-slot.https.html [ Failure Crash ]
 
+# Subgrid is not implemented yet
+crbug.com/618969 external/wpt/css/css-grid/subgrid/ [ Skip ]
+
 # ====== New tests from wpt-importer added here ======
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-normal-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-normal-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-normal-001.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-002.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-002.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-002.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-contain-003.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-contain-003.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-contain-003.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-007.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-007.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-007.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-005.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-005.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-005.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/line-names-004.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/line-names-004.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/line-names-004.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-001.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-001.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-001.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-003.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-003.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-003.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-005.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-005.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-005.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-contain-001.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-contain-001.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-contain-001.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-004.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-004.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-004.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-006.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-006.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-006.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/line-names-006.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/line-names-006.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/line-names-006.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-004.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-004.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-004.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-larger-002.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-larger-002.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-larger-002.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-002.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-002.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-002.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-004.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-004.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-004.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-003.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-003.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-003.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/abs-pos-002.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/abs-pos-002.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/abs-pos-002.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-contain-004.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-contain-004.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-contain-004.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/line-names-005.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/line-names-005.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/line-names-005.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-larger-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-larger-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-larger-001.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-003.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-003.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-003.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-smaller-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-smaller-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-smaller-001.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-006.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-006.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-006.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/subgrid-item-block-size-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/subgrid-item-block-size-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/subgrid-item-block-size-001.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-004.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-004.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-004.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/orthogonal-writing-mode-001.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-007.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-007.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-007.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-008.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-008.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-008.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-002.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-002.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-002.html [ Failure ]
@@ -3322,33 +3267,12 @@
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-009.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-009.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-009.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-009.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-009.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-009.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/line-names-008.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/line-names-008.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/line-names-008.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-002.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-002.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-002.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-003.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-003.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/css-grid/alignment/grid-self-alignment-baseline-with-grid-003.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/baseline-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/baseline-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/baseline-001.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/grid-gap-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/grid-gap-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/grid-gap-001.html [ Failure ]
 crbug.com/626703 [ Linux ] external/wpt/css/motion/offset-path-ray-contain-005.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/motion/offset-path-ray-contain-005.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/css/motion/offset-path-ray-contain-005.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/item-percentage-height-001.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/item-percentage-height-001.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/item-percentage-height-001.html [ Failure ]
-crbug.com/626703 [ Linux ] external/wpt/css/css-grid/subgrid/line-names-007.html [ Failure ]
-crbug.com/626703 [ Mac ] external/wpt/css/css-grid/subgrid/line-names-007.html [ Failure ]
-crbug.com/626703 [ Win ] external/wpt/css/css-grid/subgrid/line-names-007.html [ Failure ]
 crbug.com/626703 [ Win7 ] virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ]
 crbug.com/626703 [ Mac10.10 ] virtual/omt-worker-fetch/external/wpt/resource-timing/resource_timing_buffer_full_eventually.html [ Timeout ]
 crbug.com/626703 [ Retina ] virtual/omt-worker-fetch/external/wpt/resource-timing/resource_timing_buffer_full_eventually.html [ Timeout ]
@@ -3361,24 +3285,6 @@
 crbug.com/626703 [ Mac ] external/wpt/css/css-scroll-anchoring/infinite-scroll-event.tentative.html [ Timeout ]
 crbug.com/626703 [ Win ] external/wpt/css/css-scroll-anchoring/infinite-scroll-event.tentative.html [ Timeout ]
 crbug.com/626703 [ Win ] external/wpt/web-animations/timing-model/animation-effects/phases-and-states.html [ Crash ]
-crbug.com/626703 [ Mac10.11 ] external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.12 ] external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.13 ] external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https.html [ Failure Timeout ]
-crbug.com/626703 [ Retina ] external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.11 ] wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.12 ] wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.13 ] wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Retina ] wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.11 ] wpt_internal/webxr/render_state_vertical_fov_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.12 ] wpt_internal/webxr/render_state_vertical_fov_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.13 ] wpt_internal/webxr/render_state_vertical_fov_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Retina ] wpt_internal/webxr/render_state_vertical_fov_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.11 ] external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.12 ] external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.13 ] external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https.html [ Failure Timeout ]
-crbug.com/626703 [ Retina ] external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.10 ] wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https.html [ Failure Timeout ]
-crbug.com/626703 [ Mac10.10 ] wpt_internal/webxr/render_state_vertical_fov_inline.https.html [ Failure Timeout ]
 crbug.com/626703 [ Linux ] external/wpt/webvtt/rendering/cues-with-video/processing-model/snap-to-line.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/webvtt/rendering/cues-with-video/processing-model/snap-to-line.html [ Failure ]
 crbug.com/626703 [ Win ] external/wpt/webvtt/rendering/cues-with-video/processing-model/snap-to-line.html [ Failure ]
@@ -3460,7 +3366,6 @@
 crbug.com/626703 external/wpt/service-workers/service-worker/ready.https.html [ Timeout ]
 crbug.com/626703 virtual/omt-service-worker-startup/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ]
 crbug.com/626703 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ]
-crbug.com/626703 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ]
 crbug.com/626703 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/ready.https.html [ Timeout ]
 crbug.com/626703 [ Linux ] external/wpt/css/css-fonts/math-script-level-and-math-style/math-script-level-auto-and-math-style-002.tentative.html [ Failure ]
 crbug.com/626703 [ Mac ] external/wpt/css/css-fonts/math-script-level-and-math-style/math-script-level-auto-and-math-style-002.tentative.html [ Failure ]
@@ -4622,14 +4527,12 @@
 crbug.com/691944 external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ]
 crbug.com/691944 virtual/omt-service-worker-startup/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ]
 crbug.com/691944 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ]
-crbug.com/691944 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ]
 crbug.com/691944 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ]
 
 # These tests (erroneously) see a platform-specific User-Agent header
 crbug.com/595993 external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ]
 crbug.com/595993 virtual/omt-service-worker-startup/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ]
 crbug.com/595993 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ]
-crbug.com/595993 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ]
 crbug.com/595993 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ]
 
 crbug.com/619427 [ Mac ] fast/overflow/overflow-height-float-not-removed-crash3.html [ Pass Failure ]
@@ -4888,7 +4791,6 @@
 
 # Service worker updates need to handle redirect appropriately.
 crbug.com/889798 external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ]
-crbug.com/889798 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ]
 crbug.com/889798 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ]
 crbug.com/889798 virtual/omt-service-worker-startup/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ]
 crbug.com/889798 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/import-scripts-redirect.https.html [ Skip ]
@@ -5432,6 +5334,7 @@
 
 # S13N Sheriff 2018-7-11
 crbug.com/862643 http/tests/serviceworker/navigation_preload/use-counter.html [ Failure Pass ]
+crbug.com/862643 virtual/omt-service-worker-startup/http/tests/serviceworker/navigation_preload/use-counter.html [ Failure Pass ]
 
 # Sheriff 2018-7-13
 crbug.com/863599 [ Debug ] external/wpt/requestidlecallback/callback-iframe.html [ Pass Timeout ]
@@ -5455,8 +5358,6 @@
 
 crbug.com/873873 external/wpt/service-workers/service-worker/fetch-canvas-tainting-video.https.html [ Timeout Pass ]
 crbug.com/873873 external/wpt/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html [ Timeout Pass ]
-crbug.com/873873 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video.https.html [ Timeout Pass ]
-crbug.com/873873 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html [ Timeout Pass ]
 crbug.com/873873 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video.https.html [ Timeout Pass ]
 crbug.com/873873 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/fetch-canvas-tainting-video-cache.https.html [ Timeout Pass ]
 
@@ -5778,7 +5679,6 @@
 crbug.com/933880 external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ]
 crbug.com/933880 virtual/omt-service-worker-startup/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ]
 crbug.com/933880 virtual/omt-worker-fetch/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ]
-crbug.com/933880 virtual/cache-storage-parallel/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ]
 crbug.com/933880 virtual/cache-storage-sequence/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ]
 crbug.com/933880 http/tests/inspector-protocol/network/interception-take-stream.js [ Failure ]
 crbug.com/933880 http/tests/inspector-protocol/network/xhr-interception-auth-fail.js [ Failure ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites
index e8ddc32c..54603f8 100644
--- a/third_party/blink/web_tests/VirtualTestSuites
+++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -578,12 +578,17 @@
   {
     "prefix": "omt-service-worker-startup",
     "base": "external/wpt/service-workers",
-    "args": ["--enable-features=OffMainThreadServiceWorkerStartup"]
+    "args": ["--disable-features=OffMainThreadServiceWorkerStartup"]
   },
   {
     "prefix": "omt-service-worker-startup",
     "base": "external/wpt/shape-detection",
-    "args": ["--enable-features=OffMainThreadServiceWorkerStartup"]
+    "args": ["--disable-features=OffMainThreadServiceWorkerStartup"]
+  },
+  {
+    "prefix": "omt-service-worker-startup",
+    "base": "http/tests/serviceworker",
+    "args": ["--disable-features=OffMainThreadServiceWorkerStartup"]
   },
   {
     "prefix": "omt-worker-fetch",
@@ -1085,11 +1090,6 @@
     "args": ["--enable-blink-features=CSSVariables2AtProperty"]
   },
   {
-    "prefix": "cache-storage-parallel",
-    "base": "external/wpt/service-workers",
-    "args": ["--disable-features=CacheStorageParallelOps"]
-  },
-  {
     "prefix": "cache-storage-sequence",
     "base": "external/wpt/service-workers",
     "args": ["--disable-features=CacheStorageSequence"]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
index b79d7b63..aae3d191f 100644
--- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
+++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -452502,7 +452502,7 @@
    "support"
   ],
   "mathml/support/feature-detection.js": [
-   "6f1d033b5b9ce7d8c2a6f9bfff589189719b586f",
+   "1952d3b06c123955832d0f9d5e35031285703c73",
    "support"
   ],
   "mathml/support/layout-comparison.js": [
@@ -477086,7 +477086,7 @@
    "support"
   ],
   "resources/chromium/nfc-mock.js": [
-   "d7829640cf470a8d20d6fe9eab39b6a24215fae6",
+   "1cc6c32caa121281d8c47555bfd57d54e922b4f1",
    "support"
   ],
   "resources/chromium/sensor.mojom.js": [
@@ -493678,7 +493678,7 @@
    "testharness"
   ],
   "web-nfc/NFCWriter_push.https.html": [
-   "cc8c94188d5bbe109fc3c395dc8fa36739b0cc62",
+   "50a230344a14c372854df93e3c29815156e855dc",
    "testharness"
   ],
   "web-nfc/OWNERS": [
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-no-referrer.sub.html b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-no-referrer.sub.html
index e50c7b52..b8866f95 100644
--- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-no-referrer.sub.html
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-no-referrer.sub.html
@@ -21,6 +21,8 @@
 
 import { referrer as referrerRemoteRemote } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker.sub.js?name=remote_remote";
 
+import { referrer as referrerRemoteSame } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js?name=remote_same";
+
 test(t => {
   assert_equals(
       referrerSame, "",
@@ -54,6 +56,13 @@
 }, "Importing a remote-origin descendant script from a remote-origin " +
    "top-level script with the no-referrer policy.");
 
+test(t => {
+  assert_equals(
+      referrerRemoteSame, "",
+      "Referrer should not be sent for the same-origin descendant script.");
+}, "Importing a same-origin descendant script from a remote-origin " +
+   "top-level script with the no-referrer policy.");
+
 </script>
 </body>
 </html>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub-expected.txt
index cd990f90..618b27c2 100644
--- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub-expected.txt
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub-expected.txt
@@ -4,5 +4,6 @@
 PASS Importing a same-origin descendant script from a same-origin top-level script with the origin-when-cross-origin policy.
 PASS Importing a remote-origin descendant script from a same-origin top-level script with the origin-when-cross-origin policy.
 FAIL Importing a remote-origin descendant script from a remote-origin top-level script with the origin-when-cross-origin policy. assert_equals: Referrer should be sent for the remote-origin descendant script. expected "http://www1.web-platform.test:8001/" but got "http://www1.web-platform.test:8001/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker.sub.js?name=remote_remote"
+FAIL Importing a same-origin descendant script from a remote-origin top-level script with the origin-when-cross-origin policy. assert_equals: Referrer should be sent for the same-origin descendant script. expected "http://www1.web-platform.test:8001/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js?name=remote_same" but got "http://www1.web-platform.test:8001/"
 Harness: the test ran to completion.
 
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub.html b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub.html
index 3623ac2..8351289 100644
--- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub.html
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin-when-cross-origin.sub.html
@@ -21,6 +21,8 @@
 
 import { referrer as referrerRemoteRemote } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker.sub.js?name=remote_remote";
 
+import { referrer as referrerRemoteSame } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js?name=remote_same";
+
 const origin = (new URL(location.href)).origin + "/";
 const remoteOrigin = "http://{{domains[www1]}}:{{ports[http][0]}}/";
 
@@ -61,6 +63,16 @@
 }, "Importing a remote-origin descendant script from a remote-origin " +
    "top-level script with the origin-when-cross-origin policy.");
 
+test(t => {
+  const scriptURL = new URL(
+    "html/semantics/scripting-1/the-script-element/module/resources/" +
+    "import-same-origin-referrer-checker-from-remote-origin.sub.js",
+    remoteOrigin);
+  assert_equals(referrerRemoteSame, scriptURL + "?name=remote_same",
+      "Referrer should be sent for the same-origin descendant script.");
+}, "Importing a same-origin descendant script from a remote-origin " +
+   "top-level script with the origin-when-cross-origin policy.");
+
 </script>
 </body>
 </html>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin.sub.html b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin.sub.html
index f512982a..a554fb4 100644
--- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin.sub.html
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-origin.sub.html
@@ -21,6 +21,8 @@
 
 import { referrer as referrerRemoteRemote } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker.sub.js?name=remote_remote";
 
+import { referrer as referrerRemoteSame } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js?name=remote_same";
+
 const origin = (new URL(location.href)).origin + "/";
 const remoteOrigin = "http://{{domains[www1]}}:{{ports[http][0]}}/";
 
@@ -57,6 +59,13 @@
 }, "Importing a remote-origin descendant script from a remote-origin " +
    "top-level script with the origin policy.");
 
+test(t => {
+  assert_equals(
+      referrerRemoteSame, remoteOrigin,
+      "Referrer should be sent for the same-origin descendant script.");
+}, "Importing a same-origin descendant script from a remote-origin " +
+   "top-level script with the origin policy.");
+
 </script>
 </body>
 </html>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub-expected.txt
index 6720439b..814be90 100644
--- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub-expected.txt
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub-expected.txt
@@ -4,5 +4,6 @@
 PASS Importing a same-origin descendant script from a same-origin top-level script with the same-origin policy.
 PASS Importing a remote-origin descendant script from a same-origin top-level script with the same-origin policy.
 FAIL Importing a remote-origin descendant script from a remote-origin top-level script with the same-origin policy. assert_equals: Referrer should not be sent for the remote-origin descendant script even if it is imported from the script in the same remote-origin. expected "" but got "http://www1.web-platform.test:8001/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker.sub.js?name=remote_remote"
+FAIL Importing a same-origin descendant script from a remote-origin top-level script with the same-origin policy. assert_equals: Referrer should be sent for the same-origin descendant script even if it is imported from the script in the remote-origin. expected "http://www1.web-platform.test:8001/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js?name=remote_same" but got ""
 Harness: the test ran to completion.
 
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub.html b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub.html
index 67b055c..1d470e6 100644
--- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub.html
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-same-origin.sub.html
@@ -21,6 +21,10 @@
 
 import { referrer as referrerRemoteRemote } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker.sub.js?name=remote_remote";
 
+import { referrer as referrerRemoteSame } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js?name=remote_same";
+
+const remoteOrigin = "http://{{domains[www1]}}:{{ports[http][0]}}/";
+
 test(t => {
   assert_equals(
       referrerSame, location.href,
@@ -57,6 +61,18 @@
 }, "Importing a remote-origin descendant script from a remote-origin " +
    "top-level script with the same-origin policy.");
 
+test(t => {
+  const scriptURL = new URL(
+    "html/semantics/scripting-1/the-script-element/module/resources/" +
+    "import-same-origin-referrer-checker-from-remote-origin.sub.js",
+    remoteOrigin);
+  assert_equals(
+      referrerRemoteSame, scriptURL + "?name=remote_same",
+      "Referrer should be sent for the same-origin descendant script " +
+      "even if it is imported from the script in the remote-origin.");
+}, "Importing a same-origin descendant script from a remote-origin " +
+   "top-level script with the same-origin policy.");
+
 </script>
 </body>
 </html>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-unsafe-url.sub.html b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-unsafe-url.sub.html
index 11f60c0..443731c 100644
--- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-unsafe-url.sub.html
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/referrer-unsafe-url.sub.html
@@ -21,6 +21,8 @@
 
 import { referrer as referrerRemoteRemote } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-referrer-checker.sub.js?name=remote_remote";
 
+import { referrer as referrerRemoteSame } from "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js?name=remote_same";
+
 test(t => {
   assert_equals(
       referrerSame, location.href,
@@ -63,6 +65,17 @@
 }, "Importing a remote-origin descendant script from a remote-origin " +
    "top-level script with the unsafe-url policy.");
 
+test(t => {
+  const scriptURL =
+      "http://{{domains[www1]}}:{{ports[http][0]}}/html/semantics/" +
+      "scripting-1/the-script-element/module/resources/" +
+      "import-same-origin-referrer-checker-from-remote-origin.sub.js";
+  assert_equals(
+      referrerRemoteSame, scriptURL + "?name=remote_same",
+      "Referrer should be sent for the same-origin descendant script.");
+}, "Importing a same-origin descendant script from a remote-origin " +
+   "top-level script with the unsafe-url policy.");
+
 </script>
 </body>
 </html>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js
new file mode 100644
index 0000000..5a53bcd
--- /dev/null
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js
@@ -0,0 +1,2 @@
+import { referrer as referrerImport } from 'http://{{host}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/module/resources/referrer-checker.py?name={{GET[name]}}';
+export const referrer = referrerImport;
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js.headers b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js.headers
new file mode 100644
index 0000000..cb762eff
--- /dev/null
+++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/module/resources/import-same-origin-referrer-checker-from-remote-origin.sub.js.headers
@@ -0,0 +1 @@
+Access-Control-Allow-Origin: *
diff --git a/third_party/blink/web_tests/external/wpt/mathml/support/feature-detection.js b/third_party/blink/web_tests/external/wpt/mathml/support/feature-detection.js
index 6f1d033b..1952d3b0 100644
--- a/third_party/blink/web_tests/external/wpt/mathml/support/feature-detection.js
+++ b/third_party/blink/web_tests/external/wpt/mathml/support/feature-detection.js
@@ -320,15 +320,15 @@
   <mn>1</mn><mo lspace='0px' rspace='0px'>+</mo><mn>2</mn>\
 </mrow>\
 <mrow>\
-  <mn>1</mn><mo lspace='8px' rspace='8px'>+</mo><mn>2</mn>\
+  <mn>1</mn><mo lspace='20px' rspace='20px'>+</mo><mn>2</mn>\
 </mrow>\
 </math>");
             var math = document.body.lastElementChild;
             var mrow = math.getElementsByTagName("mrow");
-            // lspace/rspace will add 16px per MathML and none if not supported.
+            // lspace/rspace will add 40px per MathML and none if not supported.
             this._has_operator_spacing =
                 mrow[1].getBoundingClientRect().width -
-                mrow[0].getBoundingClientRect().width > 10;
+                mrow[0].getBoundingClientRect().width > 30;
             document.body.removeChild(math);
         }
         return this._has_operator_spacing;
diff --git a/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js b/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js
index d782964..1cc6c32c 100644
--- a/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js
+++ b/third_party/blink/web_tests/external/wpt/resources/chromium/nfc-mock.js
@@ -182,6 +182,10 @@
       let error = this.getHWError();
       if (error)
         return error;
+      // Cancel previous pending push operation
+      if (this.pending_promise_func_) {
+        this.cancelPendingPushOperation();
+      }
 
       this.pushed_message_ = message;
       this.push_options_ = options;
@@ -301,18 +305,18 @@
       this.push_options_ = null;
       this.pending_promise_func_ = null;
       this.push_should_timeout_ = false;
+      this.push_completed_ = true;
     }
 
     // Sets message that is used to deliver NFC reading updates.
     setReadingMessage(message) {
       this.reading_messages_.push(message);
       // Ignore reading if NFCPushOptions.ignoreRead is true
-      let ignoreRead = false;
       if(this.push_options_ && this.push_options_.ignoreRead)
-        ignoreRead = this.push_options_.ignoreRead;
+        return;
       // Triggers onWatch if the new message matches existing watchers
       for (let watcher of this.watchers_) {
-        if (!ignoreRead && matchesWatchOptions(message, watcher.options)) {
+        if (matchesWatchOptions(message, watcher.options)) {
           this.client_.onWatch(
               [watcher.id], fake_tag_serial_number,
               toMojoNDEFMessage(message));
diff --git a/third_party/blink/web_tests/external/wpt/web-nfc/NFCWriter_push.https.html b/third_party/blink/web_tests/external/wpt/web-nfc/NFCWriter_push.https.html
index cc8c941..50a23034 100644
--- a/third_party/blink/web_tests/external/wpt/web-nfc/NFCWriter_push.https.html
+++ b/third_party/blink/web_tests/external/wpt/web-nfc/NFCWriter_push.https.html
@@ -1,6 +1,6 @@
 <!DOCTYPE html>
 <meta charset=utf-8>
-<title>Web NFC: Test exceptions in NFCWriter.push</title>
+<title>Web NFC: NFCWriter.push Tests</title>
 <link rel="author" title="Intel" href="http://www.intel.com"/>
 <link rel="help" href="https://w3c.github.io/web-nfc/"/>
 <script src="/resources/testharness.js"></script>
@@ -336,4 +336,30 @@
   assertNDEFMessagesEqual(test_text_data, mockNFC.pushedMessage());
 }, "NFCWriter.push should ignore reading data when ignoreRead is true.");
 
+nfc_test(async (t, mockNFC) => {
+  const writer1 = new NFCWriter();
+  const writer2 = new NFCWriter();
+
+  const nfcPushOptions1 = createNFCPushOptions('tag', 1000, false);
+  const nfcPushOptions2 = createNFCPushOptions('tag', Infinity, true);
+  const p1 = writer1.push(test_text_data, nfcPushOptions1);
+  const p2 = writer2.push(test_url_data, nfcPushOptions2);
+
+  await new Promise((resolve, reject) => {
+    // Make first push pending
+    mockNFC.setPendingPushCompleted(false);
+    let err = "";
+    p1.then(() => {
+      reject("pending push should not be fulfilled");
+    }).catch(e => {
+      err = e.name;
+    });
+    p2.then(() => {
+      assertNDEFMessagesEqual(test_url_data, mockNFC.pushedMessage());
+      assertNFCPushOptionsEqual(nfcPushOptions2, mockNFC.pushOptions());
+      assert_equals(err, "AbortError", "the pending push should be aborted");
+      resolve();
+    });
+  });
+}, "NFCWriter.push should replace all previously configured push operations.");
 </script>
\ No newline at end of file
diff --git a/third_party/blink/web_tests/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
deleted file mode 100644
index 2372343..0000000
--- a/third_party/blink/web_tests/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ /dev/null
Binary files differ
diff --git a/third_party/blink/web_tests/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit.html b/third_party/blink/web_tests/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit.html
index 33741da..0b2fabc 100644
--- a/third_party/blink/web_tests/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit.html
+++ b/third_party/blink/web_tests/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit.html
@@ -2,7 +2,7 @@
 <input type=text value=abc disabled><br><br>
 <input type=number value=123>
 <input type=number value=123 disabled><br><br>
-<input type=password value=abc>
+<input type=password id=passwd>
 <input type=password value=abc disabled><br><br>
 <input type=button value=click>
 <input type=button value=click disabled><br><br>
@@ -11,6 +11,8 @@
 <input type=submit>
 <input type=submit disabled>
 <script>
-    if (window.testRunner)
-        testRunner.setUseMockTheme(false);
+  if (window.testRunner)
+    testRunner.setUseMockTheme(false);
+  document.getElementById("passwd").focus();
+  eventSender.keyDown('a');
 </script>
\ No newline at end of file
diff --git a/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/fast/canvas/pixelated-expected.png b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/fast/canvas/pixelated-expected.png
new file mode 100644
index 0000000..336aff93
--- /dev/null
+++ b/third_party/blink/web_tests/flag-specific/enable-gpu-rasterization/fast/canvas/pixelated-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/elements/dom-breakpoints-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/elements/dom-breakpoints-a11y-test.js
index b58867d3..736032c 100644
--- a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/elements/dom-breakpoints-a11y-test.js
+++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/elements/dom-breakpoints-a11y-test.js
@@ -4,33 +4,26 @@
 (async function() {
   TestRunner.addResult(
       'Tests accessibility in DOM breakpoints using the axe-core linter.');
+
   await TestRunner.loadModule('axe_core_test_runner');
   await TestRunner.loadModule('elements_test_runner');
   await TestRunner.showPanel('elements');
-  await UI.viewManager.showView('elements.domBreakpoints');
+  UI.panels.elements.sidebarPaneView.tabbedPane().selectTab('elements.domBreakpoints', true);
 
   await TestRunner.navigatePromise(
       '../../sources/debugger-breakpoints/resources/dom-breakpoints.html');
-  await ElementsTestRunner.nodeWithId('rootElement', domBpTest);
 
-  async function domBpTest(node) {
-    if (!node) {
-      TestRunner.addResult('Could not locate node with id rootElement.');
-      TestRunner.completeTest();
-      return;
-    }
+  const rootElement = await ElementsTestRunner.nodeWithIdPromise('rootElement');
 
-    // Add Dom breakpoints and then test
-    TestRunner.domDebuggerModel.setDOMBreakpoint(
-        node, SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified);
-    TestRunner.domDebuggerModel.setDOMBreakpoint(
-        node, SDK.DOMDebuggerModel.DOMBreakpoint.Type.AttributeModified);
-    TestRunner.addResult(
-        'Test DOM breakpoint container with multiple breakpoints.');
-    const view = 'elements.domBreakpoints';
-    const widget = await UI.viewManager.view(view).widget();
-    await AxeCoreTestRunner.runValidation(widget.element);
+  // Add Dom breakpoints and then test
+  TestRunner.domDebuggerModel.setDOMBreakpoint(
+    rootElement, SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified);
+  TestRunner.domDebuggerModel.setDOMBreakpoint(
+    rootElement, SDK.DOMDebuggerModel.DOMBreakpoint.Type.AttributeModified);
+  TestRunner.addResult(
+      'Test DOM breakpoint container with multiple breakpoints.');
 
-    TestRunner.completeTest();
-  }
+  const widget = UI.panels.elements.sidebarPaneView.tabbedPane().visibleView;
+  await AxeCoreTestRunner.runValidation(widget.element);
+  TestRunner.completeTest();
 })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test-expected.txt b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test-expected.txt
index 8134345..ac3e8bce 100644
--- a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test-expected.txt
+++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test-expected.txt
@@ -1,7 +1,39 @@
 Testing accessibility in the DOM breakpoints pane.
 Setting DOM breakpoints.
+DOM breakpoints container text content: DOM BreakpointsSubtree modifiedNode removedNo breakpoints
 DOM breakpoints pane text content: Subtree modifiedNode removedNo breakpoints
 Running the axe-core linter on the DOM breakpoints pane.
-aXe violations: []
+aXe violations: [
+  {
+    "ruleDescription": "Ensures every form element has a label",
+    "helpUrl": "https://dequeuniversity.com/rules/axe/3.0/label?application=axeAPI",
+    "ruleId": "label",
+    "impact": "critical",
+    "failedNodes": [
+      {
+        "target": [
+          [
+            "div:nth-child(7) > div.vbox.flex-auto",
+            ".widget.vbox > .breakpoint-list > div:nth-child(1) > span",
+            "#ui-checkbox-label9"
+          ]
+        ],
+        "html": "<input type=\"checkbox\" id=\"ui-checkbox-label9\" aria-label=\"Subtree modified: div#rootElement\">",
+        "failureSummary": "Fix any of the following:\n  aria-label attribute does not exist or is empty\n  aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty or not visible\n  Form element does not have an implicit (wrapped) <label>\n  Form element does not have an explicit <label>\n  Element has no title attribute or the title attribute is empty"
+      },
+      {
+        "target": [
+          [
+            "div:nth-child(7) > div.vbox.flex-auto",
+            ".widget.vbox > .breakpoint-list > div:nth-child(2) > span",
+            "#ui-checkbox-label10"
+          ]
+        ],
+        "html": "<input type=\"checkbox\" id=\"ui-checkbox-label10\" aria-label=\"Node removed: div#hostElement\">",
+        "failureSummary": "Fix any of the following:\n  aria-label attribute does not exist or is empty\n  aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty or not visible\n  Form element does not have an implicit (wrapped) <label>\n  Form element does not have an explicit <label>\n  Element has no title attribute or the title attribute is empty"
+      }
+    ]
+  }
+]
 
 
diff --git a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test.js b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test.js
index babf0c1b..886b6db 100644
--- a/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test.js
+++ b/third_party/blink/web_tests/http/tests/devtools/a11y-axe-core/sources/dom-breakpoints-pane-a11y-test.js
@@ -5,14 +5,17 @@
 (async function() {
   await TestRunner.loadModule('axe_core_test_runner');
   await TestRunner.loadModule('elements_test_runner');
+  await TestRunner.loadModule('sources_test_runner');
+  await TestRunner.showPanel('elements');
   await TestRunner.showPanel('sources');
   await TestRunner.navigatePromise(
-      '../../sources/debugger-breakpoints/resources/dom-breakpoints.html');
+    '../../sources/debugger-breakpoints/resources/dom-breakpoints.html');
 
   TestRunner.addResult('Testing accessibility in the DOM breakpoints pane.');
-  await UI.viewManager.showView('sources.domBreakpoints');
-  const domBreakpointsPane =
-      self.runtime.sharedInstance(BrowserDebugger.DOMBreakpointsSidebarPane);
+
+  // Expand the DOM Breakpoints container
+  const domBreakpointContainer = UI.panels.sources._sidebarPaneStack._expandableContainers.get('sources.domBreakpoints');
+  await domBreakpointContainer._expand();
 
   TestRunner.addResult('Setting DOM breakpoints.');
   const rootElement = await ElementsTestRunner.nodeWithIdPromise('rootElement');
@@ -24,10 +27,15 @@
       hostElement, SDK.DOMDebuggerModel.DOMBreakpoint.Type.NodeRemoved);
   TestRunner.domDebuggerModel.toggleDOMBreakpoint(breakpoint, false);
 
+  const domBreakpointsPane =
+    self.runtime.sharedInstance(BrowserDebugger.DOMBreakpointsSidebarPane);
+
+  TestRunner.addResult(`DOM breakpoints container text content: ${domBreakpointContainer.contentElement.deepTextContent()}`);
   TestRunner.addResult(`DOM breakpoints pane text content: ${domBreakpointsPane.contentElement.deepTextContent()}`);
+
   TestRunner.addResult(
       'Running the axe-core linter on the DOM breakpoints pane.');
-  await AxeCoreTestRunner.runValidation(domBreakpointsPane.contentElement);
 
+  await AxeCoreTestRunner.runValidation(domBreakpointContainer.element);
   TestRunner.completeTest();
 })();
diff --git a/third_party/blink/web_tests/http/tests/devtools/coverage/gutter-html-expected.txt b/third_party/blink/web_tests/http/tests/devtools/coverage/gutter-html-expected.txt
index 81c1266..09cba54 100644
--- a/third_party/blink/web_tests/http/tests/devtools/coverage/gutter-html-expected.txt
+++ b/third_party/blink/web_tests/http/tests/devtools/coverage/gutter-html-expected.txt
@@ -3,22 +3,22 @@
 0:   <html>
 1:   <head>
 2:   <style>
-3:   .used {
-4:     color: black;
-5:   }
+3: + .used {
+4: +   color: black;
+5: + }
 6:   
-7:   .notUsed {
-8:     color: red;
-9:   }
+7: - .notUsed {
+8: -   color: red;
+9: - }
 10:   </style>
 11:   <style>
-12:   #not-used {
-13:     color: red;
-14:   }
+12: - #not-used {
+13: -   color: red;
+14: - }
 15:   
-16:   #also-used {
-17:     color: black;
-18:   }
+16: + #also-used {
+17: +   color: black;
+18: + }
 19:   </style>
 20:   </head>
 21:   <body>
@@ -44,6 +44,8 @@
 41: +   used2();
 42: + }
 43:   </script>
-44:   </body>
-45:   
+44:   <div class="used">This is text.</div>
+45:   <div id="also-used">This is more text.</div>
+46:   </body>
+47:   
 
diff --git a/third_party/blink/web_tests/http/tests/devtools/coverage/resources/document.html b/third_party/blink/web_tests/http/tests/devtools/coverage/resources/document.html
index 56ad1c4..527d45a5 100644
--- a/third_party/blink/web_tests/http/tests/devtools/coverage/resources/document.html
+++ b/third_party/blink/web_tests/http/tests/devtools/coverage/resources/document.html
@@ -42,4 +42,6 @@
   used2();
 }
 </script>
+<div class="used">This is text.</div>
+<div id="also-used">This is more text.</div>
 </body>
diff --git a/third_party/blink/web_tests/http/tests/xmlhttprequest/resources/xmlhttprequest-in-unload-sync.html b/third_party/blink/web_tests/http/tests/xmlhttprequest/resources/xmlhttprequest-in-unload-sync.html
index d6eccee..6efa496ae 100644
--- a/third_party/blink/web_tests/http/tests/xmlhttprequest/resources/xmlhttprequest-in-unload-sync.html
+++ b/third_party/blink/web_tests/http/tests/xmlhttprequest/resources/xmlhttprequest-in-unload-sync.html
@@ -7,9 +7,9 @@
         var xhr = new XMLHttpRequest();
         xhr.open('GET', url, false);
         xhr.send(null);
-        window.parent.completed("FAIL: sync XHR completed successfully");
+        window.parent.completed("PASS: sync XHR completed successfully");
     } catch (e) {
-        window.parent.completed("PASS: sync XHR during unload failed: " + e.message);
+        window.parent.completed("FAIL: sync XHR during unload failed: " + e.message);
     }
 };
 window.onload = function () {
diff --git a/third_party/blink/web_tests/http/tests/xmlhttprequest/xmlhttprequest-unload-sync-expected.txt b/third_party/blink/web_tests/http/tests/xmlhttprequest/xmlhttprequest-unload-sync-expected.txt
index c692e2c..4b0cf22 100644
--- a/third_party/blink/web_tests/http/tests/xmlhttprequest/xmlhttprequest-unload-sync-expected.txt
+++ b/third_party/blink/web_tests/http/tests/xmlhttprequest/xmlhttprequest-unload-sync-expected.txt
@@ -1,4 +1,4 @@
 CONSOLE WARNING: line 8: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
 Test behavior of sync XHR during unload
 
-PASS: sync XHR during unload failed: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://127.0.0.1:8000/xmlhttprequest/resources/1251.html': Synchronous XHR in page dismissal.
+PASS: sync XHR completed successfully
diff --git a/third_party/blink/web_tests/platform/linux/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/linux/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 988fc085..f6a90c4 100644
--- a/third_party/blink/web_tests/platform/linux/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/linux/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index c4c6cf3..670157cf 100644
--- a/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/linux/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https-expected.txt
deleted file mode 100644
index 13364641..0000000
--- a/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https-expected.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-This is a testharness.js-based test.
-PASS XRFrame getViewerPose updates on the next frame for non-immersive sessions
-PASS XRFrame getViewerPose updates on the next frame for immersive sessions
-Harness: the test ran to completion.
-
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https-expected.txt b/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https-expected.txt
deleted file mode 100644
index 851edb4..0000000
--- a/third_party/blink/web_tests/platform/mac-mac10.10/external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https-expected.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-This is a testharness.js-based test.
-PASS 'floor-level' XRStationaryReferenceSpace updates properly when the transform changes for immersive sessions
-PASS 'floor-level' XRStationaryReferenceSpace updates properly when the transform changes for non-immersive sessions
-Harness: the test ran to completion.
-
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 8a4ed9e..98e34f51 100644
--- a/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac-mac10.10/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.10/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac-mac10.10/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 8124419..32c81b0 100644
--- a/third_party/blink/web_tests/platform/mac-mac10.10/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac-mac10.10/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 911fedd..782c2b09 100644
--- a/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac-mac10.11/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.11/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac-mac10.11/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 8124419..32c81b0 100644
--- a/third_party/blink/web_tests/platform/mac-mac10.11/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac-mac10.11/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 17ae057..d92542e 100644
--- a/third_party/blink/web_tests/platform/mac-mac10.12/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac-mac10.12/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 8124419..32c81b0 100644
--- a/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac-mac10.12/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-retina/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac-retina/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 8124419..32c81b0 100644
--- a/third_party/blink/web_tests/platform/mac-retina/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac-retina/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https-expected.txt
deleted file mode 100644
index f00aa5e8..0000000
--- a/third_party/blink/web_tests/platform/mac/external/wpt/webxr/xrSession_requestAnimationFrame_getViewerPose.https-expected.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-This is a testharness.js-based test.
-FAIL XRFrame getViewerPose updates on the next frame for non-immersive sessions promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'makeXRCompatible' of null"
-FAIL XRFrame getViewerPose updates on the next frame for immersive sessions promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'makeXRCompatible' of null"
-Harness: the test ran to completion.
-
diff --git a/third_party/blink/web_tests/platform/mac/external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https-expected.txt b/third_party/blink/web_tests/platform/mac/external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https-expected.txt
deleted file mode 100644
index c152f94..0000000
--- a/third_party/blink/web_tests/platform/mac/external/wpt/webxr/xrStationaryReferenceSpace_floorlevel_updates.https-expected.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-This is a testharness.js-based test.
-FAIL 'floor-level' XRStationaryReferenceSpace updates properly when the transform changes for immersive sessions promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'makeXRCompatible' of null"
-FAIL 'floor-level' XRStationaryReferenceSpace updates properly when the transform changes for non-immersive sessions promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'makeXRCompatible' of null"
-Harness: the test ran to completion.
-
diff --git a/third_party/blink/web_tests/platform/mac/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index e4eaaa19..9c90f804 100644
--- a/third_party/blink/web_tests/platform/mac/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 8124419..32c81b0 100644
--- a/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/platform/mac/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/wpt_internal/webxr/render_state_vertical_fov_inline.https-expected.txt b/third_party/blink/web_tests/platform/mac/wpt_internal/webxr/render_state_vertical_fov_inline.https-expected.txt
deleted file mode 100644
index 2184017..0000000
--- a/third_party/blink/web_tests/platform/mac/wpt_internal/webxr/render_state_vertical_fov_inline.https-expected.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-This is a testharness.js-based test.
-FAIL inlineVerticalFieldOfView is set appropriately on inline sessions promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'makeXRCompatible' of null"
-Harness: the test ran to completion.
-
diff --git a/third_party/blink/web_tests/platform/mac/wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https-expected.txt b/third_party/blink/web_tests/platform/mac/wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https-expected.txt
deleted file mode 100644
index bbdcbbe3..0000000
--- a/third_party/blink/web_tests/platform/mac/wpt_internal/webxr/xrSession_dataProviderDisconnect_inline.https-expected.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-This is a testharness.js-based test.
-FAIL Inline session ends if magic window data provider disconnects. promise_test: Unhandled rejection with value: object "TypeError: Cannot read property 'makeXRCompatible' of null"
-Harness: the test ran to completion.
-
diff --git a/third_party/blink/web_tests/platform/win/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/win/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
new file mode 100644
index 0000000..517541d
--- /dev/null
+++ b/third_party/blink/web_tests/platform/win/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/win/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
new file mode 100644
index 0000000..d5a1751
--- /dev/null
+++ b/third_party/blink/web_tests/platform/win/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/platform/win7/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/platform/win7/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
new file mode 100644
index 0000000..d5a1751
--- /dev/null
+++ b/third_party/blink/web_tests/platform/win7/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/virtual/cache-storage-parallel/external/wpt/service-workers/README.txt b/third_party/blink/web_tests/virtual/cache-storage-parallel/external/wpt/service-workers/README.txt
deleted file mode 100644
index 61a3a1c8..0000000
--- a/third_party/blink/web_tests/virtual/cache-storage-parallel/external/wpt/service-workers/README.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-This suite runs the ServiceWorker and CacheStorage tests with the
-CacheStorageParallelOps feature disabled.  This makes cache_storage
-execute read operations in sequence.
diff --git a/third_party/blink/web_tests/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png b/third_party/blink/web_tests/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
index 779e4cca..9e70e77 100644
--- a/third_party/blink/web_tests/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
+++ b/third_party/blink/web_tests/virtual/controls-refresh-high-contrast/fast/forms/controls-new-ui-high-contrast/text_number_password_button_submit-expected.png
Binary files differ
diff --git a/third_party/blink/web_tests/virtual/threaded/fast/idleToBlob/OffscreenCanvas-convertToBlob-oversized.html b/third_party/blink/web_tests/virtual/threaded/fast/idleToBlob/OffscreenCanvas-convertToBlob-oversized.html
index b79f64ca..804752e 100644
--- a/third_party/blink/web_tests/virtual/threaded/fast/idleToBlob/OffscreenCanvas-convertToBlob-oversized.html
+++ b/third_party/blink/web_tests/virtual/threaded/fast/idleToBlob/OffscreenCanvas-convertToBlob-oversized.html
@@ -1,18 +1,8 @@
 <!DOCTYPE html>
 <script src="../../../../resources/testharness.js"></script>
 <script src="../../../../resources/testharnessreport.js"></script>
-<script id="myWorker" type="text/worker">
-self.onmessage = function(e) {
-};
-</script>
 <script>
 
-function makeWorker(script)
-{
-  var blob = new Blob([script]);
-  return new Worker(URL.createObjectURL(blob));
-}
-
 async_test(function(t) {
   var png_max_dimension = 65535;
   var offscreenCanvas = new OffscreenCanvas(10, png_max_dimension + 1);
@@ -47,7 +37,5 @@
     assert_false("convertToBlob failed, but shouldn't be.");
   }));
 }, "Verify that convertToBlob does not crash with oversized source encoded to Webp");
-
-
 </script>
 
diff --git a/third_party/expat/0001-Do-not-claim-getrandom.patch b/third_party/expat/0001-Do-not-claim-getrandom.patch
new file mode 100644
index 0000000..cbf77db
--- /dev/null
+++ b/third_party/expat/0001-Do-not-claim-getrandom.patch
@@ -0,0 +1,22 @@
+diff --git a/third_party/expat/files/lib/expat_config.h b/third_party/expat/files/lib/expat_config.h
+index 278d7a8..c693a14a 100644
+--- a/third_party/expat/files/lib/expat_config.h
++++ b/third_party/expat/files/lib/expat_config.h
+@@ -23,7 +23,7 @@
+ #define HAVE_GETPAGESIZE 1
+ 
+ /* Define to 1 if you have the `getrandom' function. */
+-#define HAVE_GETRANDOM 1
++/* #define HAVE_GETRANDOM 1 */
+ 
+ /* Define to 1 if you have the <inttypes.h> header file. */
+ #define HAVE_INTTYPES_H 1
+@@ -50,7 +50,7 @@
+ #define HAVE_STRING_H 1
+ 
+ /* Define to 1 if you have `syscall' and `SYS_getrandom'. */
+-#define HAVE_SYSCALL_GETRANDOM 1
++/* #define HAVE_SYSCALL_GETRANDOM 1 */
+ 
+ /* Define to 1 if you have the <sys/param.h> header file. */
+ #define HAVE_SYS_PARAM_H 1
diff --git a/third_party/expat/0001-Do-not-redefine-lean-and-mean.patch b/third_party/expat/0001-Do-not-redefine-lean-and-mean.patch
deleted file mode 100644
index 595e071f..0000000
--- a/third_party/expat/0001-Do-not-redefine-lean-and-mean.patch
+++ /dev/null
@@ -1,26 +0,0 @@
-From 98180a6d1333d62175ce553cdecce110009b86bc Mon Sep 17 00:00:00 2001
-From: Dominic Cooney <dominicc@chromium.org>
-Date: Thu, 10 Aug 2017 17:39:39 +0900
-Subject: [PATCH] Do not redefine lean and mean.
-
----
- third_party/expat/files/lib/winconfig.h | 2 ++
- 1 file changed, 2 insertions(+)
-
-diff --git a/third_party/expat/files/lib/winconfig.h b/third_party/expat/files/lib/winconfig.h
-index 9bf014d7fbab..125b6b332406 100644
---- a/third_party/expat/files/lib/winconfig.h
-+++ b/third_party/expat/files/lib/winconfig.h
-@@ -10,7 +10,9 @@
- #ifndef WINCONFIG_H
- #define WINCONFIG_H
- 
-+#ifndef WIN32_LEAN_AND_MEAN
- #define WIN32_LEAN_AND_MEAN
-+#endif
- #include <windows.h>
- #undef WIN32_LEAN_AND_MEAN
- 
--- 
-2.14.0.434.g98096fd7a8-goog
-
diff --git a/third_party/expat/0002-Add-missing-include-for-malloc-free.patch b/third_party/expat/0002-Add-missing-include-for-malloc-free.patch
deleted file mode 100644
index 55201b5..0000000
--- a/third_party/expat/0002-Add-missing-include-for-malloc-free.patch
+++ /dev/null
@@ -1,24 +0,0 @@
-From 5e60caed029825a7e5d2d1d30af446612ad34d6c Mon Sep 17 00:00:00 2001
-From: Dominic Cooney <dominicc@chromium.org>
-Date: Mon, 14 Aug 2017 10:44:50 +0900
-Subject: [PATCH] Add missing include for malloc/free.
-
----
- third_party/expat/files/lib/loadlibrary.c | 1 +
- 1 file changed, 1 insertion(+)
-
-diff --git a/third_party/expat/files/lib/loadlibrary.c b/third_party/expat/files/lib/loadlibrary.c
-index ffce868399b3..d05bf59c4537 100644
---- a/third_party/expat/files/lib/loadlibrary.c
-+++ b/third_party/expat/files/lib/loadlibrary.c
-@@ -31,6 +31,7 @@
- #if defined(_WIN32)
- 
- #include <windows.h>
-+#include <stdlib.h>
- #include <tchar.h>
- 
- 
--- 
-2.14.0.434.g98096fd7a8-goog
-
diff --git a/third_party/expat/BUILD.gn b/third_party/expat/BUILD.gn
index 9289bdd1..842d0f9d 100644
--- a/third_party/expat/BUILD.gn
+++ b/third_party/expat/BUILD.gn
@@ -26,7 +26,6 @@
   static_library("expat") {
     sources = [
       "files/lib/expat.h",
-      "files/lib/loadlibrary.c",
       "files/lib/xmlparse.c",
       "files/lib/xmlrole.c",
       "files/lib/xmltok.c",
@@ -41,6 +40,8 @@
 
     defines = [ "_LIB" ]
     if (is_win) {
+      # expat expects to define WIN32_LEAN_AND_MEAN itself
+      configs -= [ "//build/config/win:lean_and_mean" ]
       defines += [ "COMPILED_FROM_DSP" ]
     } else {
       defines += [ "HAVE_EXPAT_CONFIG_H" ]
diff --git a/third_party/expat/README.chromium b/third_party/expat/README.chromium
index 894024b..435a7b9 100644
--- a/third_party/expat/README.chromium
+++ b/third_party/expat/README.chromium
@@ -1,7 +1,7 @@
 Name: Expat XML Parser
 Short Name: expat
 URL: https://github.com/libexpat/libexpat
-Version: 2.2.6
+Version: R_2_2_8-5-g4f23e05
 License: MIT
 License File: files/COPYING
 Security Critical: yes
@@ -21,15 +21,11 @@
   cd lib
   cp *.c *.def *.h $CHROMIUM_SRC/third_party/expat/files/lib
   cd $CHROMIUM_SRC/third_party/expat
-  patch -p3 < 0001-Do-not-redefine-lean-and-mean.patch
-  patch -p3 < 0002-Add-missing-include-for-malloc-free.patch
+  patch -p3 < 0001-Do-not-claim-getrandom.patch
 
 Patches:
-    0001-Do-not-redefine-lean-and-mean.patch:
-      * Do not redefine WIN32_LEAN_AND_MEAN which breaks the Windows
-        build because it uses -Werror,-Wmacro-redefined .
-    0002-Add-missing-include-for-malloc-free.patch:
-      * Include stdlib.h for declaration of malloc, free.
+    0001-Do-not-claim-getrandom.patch:
+      * Not all platforms have getrandom.
 
 Added files:
   lib/expat_config.h (a generated config file)
diff --git a/third_party/expat/files/Changes b/third_party/expat/files/Changes
index 147f48288..7fb561e 100644
--- a/third_party/expat/files/Changes
+++ b/third_party/expat/files/Changes
@@ -2,6 +2,272 @@
       https://github.com/libexpat/libexpat/labels/help%20wanted
       If you can help, please get in touch.  Thanks!
 
+Release x.x.x xxx xxxxxxxxx xx xxxx
+        Other changes:
+                  examples: Drop executable bits from elements.c
+
+Release 2.2.8 Fri Septemper 13 2019
+        Security fixes:
+       #317 #318  CVE-2019-15903 -- Fix heap overflow triggered by
+                    XML_GetCurrentLineNumber (or XML_GetCurrentColumnNumber),
+                    and deny internal entities closing the doctype;
+                    fixed in commit c20b758c332d9a13afbbb276d30db1d183a85d43
+
+        Bug fixes:
+            #240  Fix cases where XML_StopParser did not have any effect
+                    when called from inside of an end element handler
+            #341  xmlwf: Fix exit code for operation without "-d DIRECTORY";
+                    previously, only "-d DIRECTORY" would give you a proper
+                    exit code:
+                      # xmlwf -d . <<<'<not well-formed>' 2>/dev/null ; echo $?
+                      2
+                      # xmlwf <<<'<not well-formed>' 2>/dev/null ; echo $?
+                      0
+                    Now both cases return exit code 2.
+
+        Other changes:
+       #299 #302  Windows: Replace LoadLibrary hack to access
+                    unofficial API function SystemFunction036 (RtlGenRandom)
+                    by using official API function rand_s (needs WinXP+)
+            #325  Windows: Drop support for Visual Studio <=7.1/2003
+                    and document supported compilers in README.md
+            #286  Windows: Remove COM code from xmlwf; in case it turns
+                    out needed later, there will be a dedicated repository
+                    below https://github.com/libexpat/ for that code
+            #322  Windows: Remove explicit MSVC solution and project files.
+                    You can generate Visual Studio solution files through
+                    CMake, e.g.: cmake -G"Visual Studio 15 2017" .
+            #338  xmlwf: Make "xmlwf -h" help output more friendly
+            #339  examples: Improve elements.c
+       #244 #264  Autotools: Add argument --enable-xml-attr-info
+       #239 #301  Autotools: Add arguments
+                    --with-getrandom
+                    --without-getrandom
+                    --with-sys-getrandom
+                    --without-sys-getrandom
+       #312 #343  Autotools: Fix linking issues with "./configure LD=clang"
+                  Autotools: Fix "make run-xmltest" for out-of-source builds
+       #329 #336  CMake: Pull all options from Expat <=2.2.7 into namespace
+                    prefix EXPAT_ with the exception of DOCBOOK_TO_MAN:
+                    - BUILD_doc            -> EXPAT_BUILD_DOCS (plural)
+                    - BUILD_examples       -> EXPAT_BUILD_EXAMPLES
+                    - BUILD_shared         -> EXPAT_SHARED_LIBS
+                    - BUILD_tests          -> EXPAT_BUILD_TESTS
+                    - BUILD_tools          -> EXPAT_BUILD_TOOLS
+                    - DOCBOOK_TO_MAN       -> DOCBOOK_TO_MAN (unchanged)
+                    - INSTALL              -> EXPAT_ENABLE_INSTALL
+                    - MSVC_USE_STATIC_CRT  -> EXPAT_MSVC_STATIC_CRT
+                    - USE_libbsd           -> EXPAT_WITH_LIBBSD
+                    - WARNINGS_AS_ERRORS   -> EXPAT_WARNINGS_AS_ERRORS
+                    - XML_CONTEXT_BYTES    -> EXPAT_CONTEXT_BYTES
+                    - XML_DEV_URANDOM      -> EXPAT_DEV_URANDOM
+                    - XML_DTD              -> EXPAT_DTD
+                    - XML_NS               -> EXPAT_NS
+                    - XML_UNICODE          -> EXPAT_CHAR_TYPE=ushort (!)
+                    - XML_UNICODE_WCHAR_T  -> EXPAT_CHAR_TYPE=wchar_t (!)
+       #244 #264  CMake: Add argument -DEXPAT_ATTR_INFO=(ON|OFF),
+                    default OFF
+            #326  CMake: Add argument -DEXPAT_LARGE_SIZE=(ON|OFF),
+                    default OFF
+            #328  CMake: Add argument -DEXPAT_MIN_SIZE=(ON|OFF),
+                    default OFF
+       #239 #277  CMake: Add arguments
+                    -DEXPAT_WITH_GETRANDOM=(ON|OFF|AUTO), default AUTO
+                    -DEXPAT_WITH_SYS_GETRANDOM=(ON|OFF|AUTO), default AUTO
+            #326  CMake: Install expat_config.h to include directory
+            #326  CMake: Generate and install configuration files for
+                    future find_package(expat [..] CONFIG [..])
+                  CMake: Now produces a summary of applied configuration
+                  CMake: Require C++ compiler only when tests are enabled
+            #330  CMake: Fix compilation for 16bit character types,
+                    i.e. ex -DXML_UNICODE=ON (and ex -DXML_UNICODE_WCHAR_T=ON)
+            #265  CMake: Fix linking with MinGW
+            #330  CMake: Add full support for MinGW; to enable, use
+                    -DCMAKE_TOOLCHAIN_FILE=[expat]/cmake/mingw-toolchain.cmake
+            #330  CMake: Port "make run-xmltest" from GNU Autotools to CMake
+            #316  CMake: Windows: Make binary postfix match MSVC
+                    Old: expat[d].lib
+                    New: expat[w][d][MD|MT].lib
+                  CMake: Migrate files from Windows to Unix line endings
+            #308  CMake: Integrate OSS-Fuzz fuzzers, option
+                    -DEXPAT_BUILD_FUZZERS=(ON|OFF), default OFF
+             #14  Drop an OpenVMS support leftover
+    #235 #268 ..
+    #270 #310 ..
+  #313 #331 #333  Address compiler warnings
+    #282 #283 ..
+       #284 #285  Address cppcheck warnings
+       #294 #295  Address Clang Static Analyzer warnings
+        #24 #293  Mass-apply clang-format 9 (and ensure conformance during CI)
+                  Version info bumped from 7:9:6 to 7:10:6
+
+        Special thanks to:
+            David Loffredo
+            Joonun Jang
+            Khajapasha Mohammed
+            Kishore Kunche
+            Marco Maggi
+            Mitch Phillips
+            Rolf Ade
+            xantares
+            Zhongyuan Zhou
+
+Release 2.2.7 Wed June 19 2019
+        Security fixes:
+       #186 #262  CVE-2018-20843 -- Fix extraction of namespace prefixes from
+                    XML names; XML names with multiple colons could end up in
+                    the wrong namespace, and take a high amount of RAM and CPU
+                    resources while processing, opening the door to
+                    use for denial-of-service attacks
+
+        Other changes:
+       #195 #197  Autotools/CMake: Utilize -fvisibility=hidden to stop
+                    exporting non-API symbols
+            #227  Autotools: Add --without-examples and --without-tests
+            #228  Autotools: Modernize configure.ac
+       #245 #246  Autotools: Fix check for -fvisibility=hidden for Clang
+       #247 #248  Autotools: Fix compilation for lack of docbook2x-man
+       #236 #258  Autotools: Produce .tar.{gz,lz,xz} release archives
+            #212  CMake: Make libdir of pkgconfig expat.pc support multilib
+       #158 #263  CMake: Build man page in PROJECT_BINARY_DIR not _SOURCE_DIR
+            #219  Remove fallback to bcopy, assume that memmove(3) exists
+            #257  Use portable "/usr/bin/env bash" shebang (e.g. for OpenBSD)
+            #243  Windows: Fix syntax of .def module definition files
+                  Version info bumped from 7:8:6 to 7:9:6
+
+        Special thanks to:
+            Benjamin Peterson
+            Caolán McNamara
+            Hanno Böck
+            KangLin
+            Kishore Kunche
+            Marco Maggi
+            Rhodri James
+            Sebastian Dröge
+            userwithuid
+            Yury Gribov
+
+Release 2.2.6 Sun August 12 2018
+        Bug fixes:
+       #170 #206  Avoid doing arithmetic with NULL pointers in XML_GetBuffer
+       #204 #205  Fix 2.2.5 regression with suspend-resume while parsing
+                    a document like '<root/>'
+
+        Other changes:
+       #165 #168  Autotools: Fix docbook-related configure syntax error
+            #166  Autotools: Avoid grep option `-q` for Solaris
+            #167  Autotools: Support
+                    ./configure DOCBOOK_TO_MAN="xmlto man --skip-validation"
+       #159 #167  Autotools: Support DOCBOOK_TO_MAN command which produces
+                    xmlwf.1 rather than XMLWF.1; also covers case insensitive
+                    file systems
+            #181  Autotools: Drop -rpath option passed to libtool
+            #188  Autotools: Detect and deny SGML docbook2man as ours is XML
+            #188  Autotools/CMake: Support command db2x_docbook2man as well
+            #174  CMake: Introduce option WARNINGS_AS_ERRORS, defaults to OFF
+       #184 #185  CMake: Introduce option MSVC_USE_STATIC_CRT, defaults to OFF
+       #207 #208  CMake: Introduce option XML_UNICODE and XML_UNICODE_WCHAR_T,
+                    both defaulting to OFF
+            #175  CMake: Prefer check_symbol_exists over check_function_exists
+            #176  CMake: Create the same pkg-config file as with GNU Autotools
+       #178 #179  CMake: Use GNUInstallDirs module to set proper defaults for
+                    install directories
+            #208  CMake: Utilize expat_config.h.cmake for XML_DEV_URANDOM
+            #180  Windows: Fix compilation of test suite for Visual Studio 2008
+  #131 #173 #202  Address compiler warnings
+  #187 #190 #200  Fix miscellaneous typos
+                  Version info bumped from 7:7:6 to 7:8:6
+
+        Special thanks to:
+            Anton Maklakov
+            Benjamin Peterson
+            Brad King
+            Franek Korta
+            Frank Rast
+            Joe Orton
+            luzpaz
+            Pedro Vicente
+            Rainer Jung
+            Rhodri James
+            Rolf Ade
+            Rolf Eike Beer
+            Thomas Beutlich
+            Tomasz Kłoczko
+
+Release 2.2.5 Tue October 31 2017
+        Bug fixes:
+              #8  If the parser runs out of memory, make sure its internal
+                    state reflects the memory it actually has, not the memory
+                    it wanted to have.
+             #11  The default handler wasn't being called when it should for
+                    a SYSTEM or PUBLIC doctype if an entity declaration handler
+                    was registered.
+       #137 #138  Fix a case of mistakenly reported parsing success where
+                    XML_StopParser was called from an element handler
+            #162  Function XML_ErrorString was returning NULL rather than
+                    a message for code XML_ERROR_INVALID_ARGUMENT
+                    introduced with release 2.2.1
+
+        Other changes:
+            #106  xmlwf: Add argument -N adding notation declarations
+        #75 #106  Test suite: Resolve expected failure cases where xmlwf
+                    output was incomplete
+            #127  Windows: Fix test suite compilation
+       #126 #127  Windows: Fix compilation for Visual Studio 2012
+                  Windows: Upgrade shipped project files to Visual Studio 2017
+        #33 #132  tests: Mass-fix compilation for XML_UNICODE_WCHAR_T
+            #129  examples: Fix compilation for XML_UNICODE_WCHAR_T
+            #130  benchmark: Fix compilation for XML_UNICODE_WCHAR_T
+            #144  xmlwf: Fix compilation for XML_UNICODE_WCHAR_T; still needs
+                    Windows or MinGW for 2-byte wchar_t
+              #9  Address two Clang Static Analyzer false positives
+             #59  Resolve troublesome macros hiding parser struct membership
+                    and dereferencing that pointer
+              #6  Resolve superfluous internal malloc/realloc switch
+       #153 #155  Improve docbook2x-man detection
+            #160  Undefine NDEBUG in the test suite (rather than rejecting it)
+            #161  Address compiler warnings
+                  Version info bumped from 7:6:6 to 7:7:6
+
+        Special thanks to:
+            Benbuck Nason
+            Hans Wennborg
+            José Gutiérrez de la Concha
+            Pedro Monreal Gonzalez
+            Rhodri James
+            Rolf Ade
+            Stephen Groat
+                 and
+            Core Infrastructure Initiative
+
+Release 2.2.4 Sat August 19 2017
+        Bug fixes:
+            #115  Fix copying of partial characters for UTF-8 input
+
+        Other changes:
+            #109  Fix "make check" for non-x86 architectures that default
+                    to unsigned type char (-128..127 rather than 0..255)
+            #109  coverage.sh: Cover -funsigned-char
+                  Autotools: Introduce --without-xmlwf argument
+             #65  Autotools: Replace handwritten Makefile with GNU Automake
+             #43  CMake: Auto-detect high quality entropy extractors, add new
+                    option USE_libbsd=ON to use arc4random_buf of libbsd
+             #74  CMake: Add -fno-strict-aliasing only where supported
+            #114  CMake: Always honor manually set BUILD_* options
+            #114  CMake: Compile man page if docbook2x-man is available, only
+            #117  Include file tests/xmltest.log.expected in source tarball
+                    (required for "make run-xmltest")
+            #117  Include (existing) Visual Studio 2013 files in source tarball
+                  Improve test suite error output
+            #111  Fix some typos in documentation
+                  Version info bumped from 7:5:6 to 7:6:6
+
+        Special thanks to:
+            Jakub Wilk
+            Joe Orton
+            Lin Tian
+            Rolf Eike Beer
+
 Release 2.2.3 Wed August 2 2017
         Security fixes:
              #82  CVE-2017-11742 -- Windows: Fix DLL hijacking vulnerability
@@ -73,7 +339,7 @@
              #68  Fix "./buildconf.sh && ./configure" for some versions
                     of Dash for /bin/sh
              #72  CMake: Ease use of Expat in context of a parent project
-                    with multipe CMakeLists.txt files
+                    with multiple CMakeLists.txt files
              #72  CMake: Resolve mistaken executable permissions
              #76  Address compile warning with -DNDEBUG (not recommended!)
              #77  Address compile warning about macro redefinition
@@ -289,7 +555,7 @@
           #2855609: Dangling positionPtr after error.
           #2990652: CMake support.
           #3010819: UNEXPECTED_STATE with a trailing "%" in entity value.
-          #3206497: Unitialized memory returned from XML_Parse.
+          #3206497: Uninitialized memory returned from XML_Parse.
           #3287849: make check fails on mingw-w64.
         - Patches:
           #1749198: pkg-config support.
diff --git a/third_party/expat/files/README.md b/third_party/expat/files/README.md
index 0a1777e..e5db597 100644
--- a/third_party/expat/files/README.md
+++ b/third_party/expat/files/README.md
@@ -1,4 +1,9 @@
-# Expat, Release 2.2.3
+[![Travis CI Build Status](https://travis-ci.org/libexpat/libexpat.svg?branch=master)](https://travis-ci.org/libexpat/libexpat)
+[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/libexpat/libexpat?svg=true)](https://ci.appveyor.com/project/libexpat/libexpat)
+[![Packaging status](https://repology.org/badge/tiny-repos/expat.svg)](https://repology.org/metapackage/expat/versions)
+
+
+# Expat, Release 2.2.8
 
 This is Expat, a C library for parsing XML, started by
 [James Clark](https://en.wikipedia.org/wiki/James_Clark_(programmer)) in 1997.
@@ -8,6 +13,11 @@
 document being parsed.  A start tag is an example of the kind of
 structures for which you may register handlers.
 
+Expat supports the following compilers:
+- GNU GCC >=4.5
+- LLVM Clang >=3.5
+- Microsoft Visual Studio >=8.0/2005
+
 Windows users should use the
 [`expat_win32` package](https://sourceforge.net/projects/expat/files/expat_win32/),
 which includes both precompiled libraries and executables, and source code for
@@ -72,47 +82,43 @@
 
 If you are interested in building Expat to provide document
 information in UTF-16 encoding rather than the default UTF-8, follow
-these instructions (after having run `make distclean`):
+these instructions (after having run `make distclean`).
+Please note that we configure with `--without-xmlwf` as xmlwf does not
+support this mode of compilation (yet):
+
+1. Mass-patch `Makefile.am` files to use `libexpatw.la` for a library name:
+   <br/>
+   `find -name Makefile.am -exec sed
+       -e 's,libexpat\.la,libexpatw.la,'
+       -e 's,libexpat_la,libexpatw_la,'
+       -i {} +`
+
+1. Run `automake` to re-write `Makefile.in` files:<br/>
+   `automake`
 
 1. For UTF-16 output as unsigned short (and version/error strings as char),
    run:<br/>
-   `./configure CPPFLAGS=-DXML_UNICODE`<br/>
+   `./configure CPPFLAGS=-DXML_UNICODE --without-xmlwf`<br/>
    For UTF-16 output as `wchar_t` (incl. version/error strings), run:<br/>
-   `./configure CFLAGS="-g -O2 -fshort-wchar" CPPFLAGS=-DXML_UNICODE_WCHAR_T`
+   `./configure CFLAGS="-g -O2 -fshort-wchar" CPPFLAGS=-DXML_UNICODE_WCHAR_T
+       --without-xmlwf`
    <br/>Note: The latter requires libc compiled with `-fshort-wchar`, as well.
 
-1. Edit `Makefile`, changing:<br/>
-   `LIBRARY = libexpat.la`<br/>
-   to:<br/>
-   `LIBRARY = libexpatw.la`<br/>
-   (Note the additional "w" in the library name.)
+1. Run `make` (which excludes xmlwf).
 
-1. Run `make buildlib` (which builds the library only).
-   Or, to save step 2, run `make buildlib LIBRARY=libexpatw.la`.
+1. Run `make install` (again, excludes xmlwf).
 
-1. Run `make installlib` (which installs the library only).
-   Or, if step 2 was omitted, run `make installlib LIBRARY=libexpatw.la`.
-
-Using `DESTDIR` or `INSTALL_ROOT` is enabled, with `INSTALL_ROOT` being the
-default value for `DESTDIR`, and the rest of the make file using only
-`DESTDIR`.  It works as follows:
+Using `DESTDIR` is supported.  It works as follows:
 
 ```console
 make install DESTDIR=/path/to/image
 ```
 
-overrides the in-makefile set `DESTDIR`, while both
+overrides the in-makefile set `DESTDIR`, because variable-setting priority is
 
-```console
-INSTALL_ROOT=/path/to/image make install
-make install INSTALL_ROOT=/path/to/image
-```
-
-use `DESTDIR=$(INSTALL_ROOT)`, even if `DESTDIR` eventually is defined in the
-environment, because variable-setting priority is
 1. commandline
-2. in-makefile
-3. environment
+1. in-makefile
+1. environment
 
 Note: This only applies to the Expat library itself, building UTF-16 versions
 of xmlwf and the tests is currently not supported.
@@ -124,3 +130,59 @@
 
 A reference manual is available in the file `doc/reference.html` in this
 distribution.
+
+
+The CMake build system is still *experimental* and will replace the primary
+build system based on GNU Autotools at some point when it is ready.
+For an idea of the available (non-advanced) options for building with CMake:
+
+```console
+# rm -f CMakeCache.txt ; cmake -D_EXPAT_HELP=ON -LH . | grep -B1 ':.*=' | sed 's,^--$,,'
+// Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel ...
+CMAKE_BUILD_TYPE:STRING=
+
+// Install path prefix, prepended onto install directories.
+CMAKE_INSTALL_PREFIX:PATH=/usr/local
+
+// Path to a program.
+DOCBOOK_TO_MAN:FILEPATH=/usr/bin/docbook2x-man
+
+// build man page for xmlwf
+EXPAT_BUILD_DOCS:BOOL=ON
+
+// build the examples for expat library
+EXPAT_BUILD_EXAMPLES:BOOL=ON
+
+// build fuzzers for the expat library
+EXPAT_BUILD_FUZZERS:BOOL=OFF
+
+// build the tests for expat library
+EXPAT_BUILD_TESTS:BOOL=ON
+
+// build the xmlwf tool for expat library
+EXPAT_BUILD_TOOLS:BOOL=ON
+
+// Character type to use (char|ushort|wchar_t) [default=char]
+EXPAT_CHAR_TYPE:STRING=char
+
+// install expat files in cmake install target
+EXPAT_ENABLE_INSTALL:BOOL=ON
+
+// Use /MT flag (static CRT) when compiling in MSVC
+EXPAT_MSVC_STATIC_CRT:BOOL=OFF
+
+// build a shared expat library
+EXPAT_SHARED_LIBS:BOOL=ON
+
+// Treat all compiler warnings as errors
+EXPAT_WARNINGS_AS_ERRORS:BOOL=OFF
+
+// Make use of getrandom function (ON|OFF|AUTO) [default=AUTO]
+EXPAT_WITH_GETRANDOM:STRING=AUTO
+
+// utilize libbsd (for arc4random_buf)
+EXPAT_WITH_LIBBSD:BOOL=OFF
+
+// Make use of syscall SYS_getrandom (ON|OFF|AUTO) [default=AUTO]
+EXPAT_WITH_SYS_GETRANDOM:STRING=AUTO
+```
diff --git a/third_party/expat/files/lib/asciitab.h b/third_party/expat/files/lib/asciitab.h
index 2f59fd9..63b1d1b4 100644
--- a/third_party/expat/files/lib/asciitab.h
+++ b/third_party/expat/files/lib/asciitab.h
@@ -31,34 +31,34 @@
 */
 
 /* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
-/* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML,
-/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
-/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
-/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
-/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
-/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
-/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
-/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
-/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
-/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
-/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
-/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
-/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
-/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
-/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
-/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
-/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
+    /* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML,
+    /* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
+    /* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
+    /* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
+    /* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
+    /* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
+    /* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
+    /* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
+    /* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
+    /* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
+    /* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
+    /* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
+    /* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
+    /* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
+    /* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
+    /* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
+    /* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,
diff --git a/third_party/expat/files/lib/expat.h b/third_party/expat/files/lib/expat.h
index 174c3faf..6c8eb1f 100644
--- a/third_party/expat/files/lib/expat.h
+++ b/third_party/expat/files/lib/expat.h
@@ -33,15 +33,6 @@
 #ifndef Expat_INCLUDED
 #define Expat_INCLUDED 1
 
-#ifdef __VMS
-/*      0        1         2         3      0        1         2         3
-        1234567890123456789012345678901     1234567890123456789012345678901 */
-#define XML_SetProcessingInstructionHandler XML_SetProcessingInstrHandler
-#define XML_SetUnparsedEntityDeclHandler    XML_SetUnparsedEntDeclHandler
-#define XML_SetStartNamespaceDeclHandler    XML_SetStartNamespcDeclHandler
-#define XML_SetExternalEntityRefHandlerArg  XML_SetExternalEntRefHandlerArg
-#endif
-
 #include <stdlib.h>
 #include "expat_external.h"
 
@@ -53,8 +44,8 @@
 typedef struct XML_ParserStruct *XML_Parser;
 
 typedef unsigned char XML_Bool;
-#define XML_TRUE   ((XML_Bool) 1)
-#define XML_FALSE  ((XML_Bool) 0)
+#define XML_TRUE ((XML_Bool)1)
+#define XML_FALSE ((XML_Bool)0)
 
 /* The XML_Status enum gives the possible return values for several
    API functions.  The preprocessor #defines are included so this
@@ -164,25 +155,23 @@
 typedef struct XML_cp XML_Content;
 
 struct XML_cp {
-  enum XML_Content_Type         type;
-  enum XML_Content_Quant        quant;
-  XML_Char *                    name;
-  unsigned int                  numchildren;
-  XML_Content *                 children;
+  enum XML_Content_Type type;
+  enum XML_Content_Quant quant;
+  XML_Char *name;
+  unsigned int numchildren;
+  XML_Content *children;
 };
 
-
 /* This is called for an element declaration. See above for
    description of the model argument. It's the caller's responsibility
    to free model when finished with it.
 */
-typedef void (XMLCALL *XML_ElementDeclHandler) (void *userData,
-                                                const XML_Char *name,
-                                                XML_Content *model);
+typedef void(XMLCALL *XML_ElementDeclHandler)(void *userData,
+                                              const XML_Char *name,
+                                              XML_Content *model);
 
 XMLPARSEAPI(void)
-XML_SetElementDeclHandler(XML_Parser parser,
-                          XML_ElementDeclHandler eldecl);
+XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl);
 
 /* The Attlist declaration handler is called for *each* attribute. So
    a single Attlist declaration with multiple attributes declared will
@@ -192,17 +181,12 @@
    value will be NULL in the case of "#REQUIRED". If "isrequired" is
    true and default is non-NULL, then this is a "#FIXED" default.
 */
-typedef void (XMLCALL *XML_AttlistDeclHandler) (
-                                    void            *userData,
-                                    const XML_Char  *elname,
-                                    const XML_Char  *attname,
-                                    const XML_Char  *att_type,
-                                    const XML_Char  *dflt,
-                                    int              isrequired);
+typedef void(XMLCALL *XML_AttlistDeclHandler)(
+    void *userData, const XML_Char *elname, const XML_Char *attname,
+    const XML_Char *att_type, const XML_Char *dflt, int isrequired);
 
 XMLPARSEAPI(void)
-XML_SetAttlistDeclHandler(XML_Parser parser,
-                          XML_AttlistDeclHandler attdecl);
+XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl);
 
 /* The XML declaration handler is called for *both* XML declarations
    and text declarations. The way to distinguish is that the version
@@ -212,15 +196,13 @@
    was no standalone parameter in the declaration, that it was given
    as no, or that it was given as yes.
 */
-typedef void (XMLCALL *XML_XmlDeclHandler) (void           *userData,
-                                            const XML_Char *version,
-                                            const XML_Char *encoding,
-                                            int             standalone);
+typedef void(XMLCALL *XML_XmlDeclHandler)(void *userData,
+                                          const XML_Char *version,
+                                          const XML_Char *encoding,
+                                          int standalone);
 
 XMLPARSEAPI(void)
-XML_SetXmlDeclHandler(XML_Parser parser,
-                      XML_XmlDeclHandler xmldecl);
-
+XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler xmldecl);
 
 typedef struct {
   void *(*malloc_fcn)(size_t size);
@@ -248,7 +230,6 @@
 XMLPARSEAPI(XML_Parser)
 XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator);
 
-
 /* Constructs a new parser using the memory management suite referred to
    by memsuite. If memsuite is NULL, then use the standard library memory
    suite. If namespaceSeparator is non-NULL it creates a parser with
@@ -278,31 +259,27 @@
 /* atts is array of name/value pairs, terminated by 0;
    names and values are 0 terminated.
 */
-typedef void (XMLCALL *XML_StartElementHandler) (void *userData,
-                                                 const XML_Char *name,
-                                                 const XML_Char **atts);
+typedef void(XMLCALL *XML_StartElementHandler)(void *userData,
+                                               const XML_Char *name,
+                                               const XML_Char **atts);
 
-typedef void (XMLCALL *XML_EndElementHandler) (void *userData,
-                                               const XML_Char *name);
-
+typedef void(XMLCALL *XML_EndElementHandler)(void *userData,
+                                             const XML_Char *name);
 
 /* s is not 0 terminated. */
-typedef void (XMLCALL *XML_CharacterDataHandler) (void *userData,
-                                                  const XML_Char *s,
-                                                  int len);
+typedef void(XMLCALL *XML_CharacterDataHandler)(void *userData,
+                                                const XML_Char *s, int len);
 
 /* target and data are 0 terminated */
-typedef void (XMLCALL *XML_ProcessingInstructionHandler) (
-                                                void *userData,
-                                                const XML_Char *target,
-                                                const XML_Char *data);
+typedef void(XMLCALL *XML_ProcessingInstructionHandler)(void *userData,
+                                                        const XML_Char *target,
+                                                        const XML_Char *data);
 
 /* data is 0 terminated */
-typedef void (XMLCALL *XML_CommentHandler) (void *userData,
-                                            const XML_Char *data);
+typedef void(XMLCALL *XML_CommentHandler)(void *userData, const XML_Char *data);
 
-typedef void (XMLCALL *XML_StartCdataSectionHandler) (void *userData);
-typedef void (XMLCALL *XML_EndCdataSectionHandler) (void *userData);
+typedef void(XMLCALL *XML_StartCdataSectionHandler)(void *userData);
+typedef void(XMLCALL *XML_EndCdataSectionHandler)(void *userData);
 
 /* This is called for any characters in the XML document for which
    there is no applicable handler.  This includes both characters that
@@ -317,25 +294,23 @@
    default handler: for example, a comment might be split between
    multiple calls.
 */
-typedef void (XMLCALL *XML_DefaultHandler) (void *userData,
-                                            const XML_Char *s,
-                                            int len);
+typedef void(XMLCALL *XML_DefaultHandler)(void *userData, const XML_Char *s,
+                                          int len);
 
 /* This is called for the start of the DOCTYPE declaration, before
    any DTD or internal subset is parsed.
 */
-typedef void (XMLCALL *XML_StartDoctypeDeclHandler) (
-                                            void *userData,
-                                            const XML_Char *doctypeName,
-                                            const XML_Char *sysid,
-                                            const XML_Char *pubid,
-                                            int has_internal_subset);
+typedef void(XMLCALL *XML_StartDoctypeDeclHandler)(void *userData,
+                                                   const XML_Char *doctypeName,
+                                                   const XML_Char *sysid,
+                                                   const XML_Char *pubid,
+                                                   int has_internal_subset);
 
 /* This is called for the start of the DOCTYPE declaration when the
    closing > is encountered, but after processing any external
    subset.
 */
-typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
+typedef void(XMLCALL *XML_EndDoctypeDeclHandler)(void *userData);
 
 /* This is called for entity declarations. The is_parameter_entity
    argument will be non-zero if the entity is a parameter entity, zero
@@ -355,20 +330,14 @@
    Note that is_parameter_entity can't be changed to XML_Bool, since
    that would break binary compatibility.
 */
-typedef void (XMLCALL *XML_EntityDeclHandler) (
-                              void *userData,
-                              const XML_Char *entityName,
-                              int is_parameter_entity,
-                              const XML_Char *value,
-                              int value_length,
-                              const XML_Char *base,
-                              const XML_Char *systemId,
-                              const XML_Char *publicId,
-                              const XML_Char *notationName);
+typedef void(XMLCALL *XML_EntityDeclHandler)(
+    void *userData, const XML_Char *entityName, int is_parameter_entity,
+    const XML_Char *value, int value_length, const XML_Char *base,
+    const XML_Char *systemId, const XML_Char *publicId,
+    const XML_Char *notationName);
 
 XMLPARSEAPI(void)
-XML_SetEntityDeclHandler(XML_Parser parser,
-                         XML_EntityDeclHandler handler);
+XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler);
 
 /* OBSOLETE -- OBSOLETE -- OBSOLETE
    This handler has been superseded by the EntityDeclHandler above.
@@ -379,24 +348,20 @@
    entityName, systemId and notationName arguments will never be
    NULL. The other arguments may be.
 */
-typedef void (XMLCALL *XML_UnparsedEntityDeclHandler) (
-                                    void *userData,
-                                    const XML_Char *entityName,
-                                    const XML_Char *base,
-                                    const XML_Char *systemId,
-                                    const XML_Char *publicId,
-                                    const XML_Char *notationName);
+typedef void(XMLCALL *XML_UnparsedEntityDeclHandler)(
+    void *userData, const XML_Char *entityName, const XML_Char *base,
+    const XML_Char *systemId, const XML_Char *publicId,
+    const XML_Char *notationName);
 
 /* This is called for a declaration of notation.  The base argument is
    whatever was set by XML_SetBase. The notationName will never be
    NULL.  The other arguments can be.
 */
-typedef void (XMLCALL *XML_NotationDeclHandler) (
-                                    void *userData,
-                                    const XML_Char *notationName,
-                                    const XML_Char *base,
-                                    const XML_Char *systemId,
-                                    const XML_Char *publicId);
+typedef void(XMLCALL *XML_NotationDeclHandler)(void *userData,
+                                               const XML_Char *notationName,
+                                               const XML_Char *base,
+                                               const XML_Char *systemId,
+                                               const XML_Char *publicId);
 
 /* When namespace processing is enabled, these are called once for
    each namespace declaration. The call to the start and end element
@@ -404,14 +369,12 @@
    declaration handlers. For an xmlns attribute, prefix will be
    NULL.  For an xmlns="" attribute, uri will be NULL.
 */
-typedef void (XMLCALL *XML_StartNamespaceDeclHandler) (
-                                    void *userData,
-                                    const XML_Char *prefix,
-                                    const XML_Char *uri);
+typedef void(XMLCALL *XML_StartNamespaceDeclHandler)(void *userData,
+                                                     const XML_Char *prefix,
+                                                     const XML_Char *uri);
 
-typedef void (XMLCALL *XML_EndNamespaceDeclHandler) (
-                                    void *userData,
-                                    const XML_Char *prefix);
+typedef void(XMLCALL *XML_EndNamespaceDeclHandler)(void *userData,
+                                                   const XML_Char *prefix);
 
 /* This is called if the document is not standalone, that is, it has an
    external subset or a reference to a parameter entity, but does not
@@ -422,7 +385,7 @@
    conditions above this handler will only be called if the referenced
    entity was actually read.
 */
-typedef int (XMLCALL *XML_NotStandaloneHandler) (void *userData);
+typedef int(XMLCALL *XML_NotStandaloneHandler)(void *userData);
 
 /* This is called for a reference to an external parsed general
    entity.  The referenced entity is not automatically parsed.  The
@@ -458,12 +421,11 @@
    Note that unlike other handlers the first argument is the parser,
    not userData.
 */
-typedef int (XMLCALL *XML_ExternalEntityRefHandler) (
-                                    XML_Parser parser,
-                                    const XML_Char *context,
-                                    const XML_Char *base,
-                                    const XML_Char *systemId,
-                                    const XML_Char *publicId);
+typedef int(XMLCALL *XML_ExternalEntityRefHandler)(XML_Parser parser,
+                                                   const XML_Char *context,
+                                                   const XML_Char *base,
+                                                   const XML_Char *systemId,
+                                                   const XML_Char *publicId);
 
 /* This is called in two situations:
    1) An entity reference is encountered for which no declaration
@@ -475,10 +437,9 @@
          the event would be out of sync with the reporting of the
          declarations or attribute values
 */
-typedef void (XMLCALL *XML_SkippedEntityHandler) (
-                                    void *userData,
-                                    const XML_Char *entityName,
-                                    int is_parameter_entity);
+typedef void(XMLCALL *XML_SkippedEntityHandler)(void *userData,
+                                                const XML_Char *entityName,
+                                                int is_parameter_entity);
 
 /* This structure is filled in by the XML_UnknownEncodingHandler to
    provide information to the parser about encodings that are unknown
@@ -535,8 +496,8 @@
 typedef struct {
   int map[256];
   void *data;
-  int (XMLCALL *convert)(void *data, const char *s);
-  void (XMLCALL *release)(void *data);
+  int(XMLCALL *convert)(void *data, const char *s);
+  void(XMLCALL *release)(void *data);
 } XML_Encoding;
 
 /* This is called for an encoding that is unknown to the parser.
@@ -554,23 +515,19 @@
    If info does not describe a suitable encoding, then the parser will
    return an XML_UNKNOWN_ENCODING error.
 */
-typedef int (XMLCALL *XML_UnknownEncodingHandler) (
-                                    void *encodingHandlerData,
-                                    const XML_Char *name,
-                                    XML_Encoding *info);
+typedef int(XMLCALL *XML_UnknownEncodingHandler)(void *encodingHandlerData,
+                                                 const XML_Char *name,
+                                                 XML_Encoding *info);
 
 XMLPARSEAPI(void)
-XML_SetElementHandler(XML_Parser parser,
-                      XML_StartElementHandler start,
+XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
                       XML_EndElementHandler end);
 
 XMLPARSEAPI(void)
-XML_SetStartElementHandler(XML_Parser parser,
-                           XML_StartElementHandler handler);
+XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler handler);
 
 XMLPARSEAPI(void)
-XML_SetEndElementHandler(XML_Parser parser,
-                         XML_EndElementHandler handler);
+XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler handler);
 
 XMLPARSEAPI(void)
 XML_SetCharacterDataHandler(XML_Parser parser,
@@ -580,8 +537,7 @@
 XML_SetProcessingInstructionHandler(XML_Parser parser,
                                     XML_ProcessingInstructionHandler handler);
 XMLPARSEAPI(void)
-XML_SetCommentHandler(XML_Parser parser,
-                      XML_CommentHandler handler);
+XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler);
 
 XMLPARSEAPI(void)
 XML_SetCdataSectionHandler(XML_Parser parser,
@@ -601,20 +557,17 @@
    default handler, or to the skipped entity handler, if one is set.
 */
 XMLPARSEAPI(void)
-XML_SetDefaultHandler(XML_Parser parser,
-                      XML_DefaultHandler handler);
+XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler);
 
 /* This sets the default handler but does not inhibit expansion of
    internal entities.  The entity reference will not be passed to the
    default handler.
 */
 XMLPARSEAPI(void)
-XML_SetDefaultHandlerExpand(XML_Parser parser,
-                            XML_DefaultHandler handler);
+XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler);
 
 XMLPARSEAPI(void)
-XML_SetDoctypeDeclHandler(XML_Parser parser,
-                          XML_StartDoctypeDeclHandler start,
+XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
                           XML_EndDoctypeDeclHandler end);
 
 XMLPARSEAPI(void)
@@ -622,16 +575,14 @@
                                XML_StartDoctypeDeclHandler start);
 
 XMLPARSEAPI(void)
-XML_SetEndDoctypeDeclHandler(XML_Parser parser,
-                             XML_EndDoctypeDeclHandler end);
+XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end);
 
 XMLPARSEAPI(void)
 XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
                                  XML_UnparsedEntityDeclHandler handler);
 
 XMLPARSEAPI(void)
-XML_SetNotationDeclHandler(XML_Parser parser,
-                           XML_NotationDeclHandler handler);
+XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler);
 
 XMLPARSEAPI(void)
 XML_SetNamespaceDeclHandler(XML_Parser parser,
@@ -659,8 +610,7 @@
    instead of the parser object.
 */
 XMLPARSEAPI(void)
-XML_SetExternalEntityRefHandlerArg(XML_Parser parser,
-                                   void *arg);
+XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg);
 
 XMLPARSEAPI(void)
 XML_SetSkippedEntityHandler(XML_Parser parser,
@@ -740,7 +690,6 @@
 XMLPARSEAPI(enum XML_Error)
 XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD);
 
-
 /* Sets the base to be used for resolving relative URIs in system
    identifiers in declarations.  Resolving relative identifiers is
    left to the application: this value will be passed through as the
@@ -780,10 +729,10 @@
    info->valueEnd - info->valueStart = 4 bytes.
 */
 typedef struct {
-  XML_Index  nameStart;  /* Offset to beginning of the attribute name. */
-  XML_Index  nameEnd;    /* Offset after the attribute name's last byte. */
-  XML_Index  valueStart; /* Offset to beginning of the attribute value. */
-  XML_Index  valueEnd;   /* Offset after the attribute value's last byte. */
+  XML_Index nameStart;  /* Offset to beginning of the attribute name. */
+  XML_Index nameEnd;    /* Offset after the attribute name's last byte. */
+  XML_Index valueStart; /* Offset to beginning of the attribute value. */
+  XML_Index valueEnd;   /* Offset after the attribute value's last byte. */
 } XML_AttrInfo;
 
 /* Returns an array of XML_AttrInfo structures for the attribute/value pairs
@@ -819,20 +768,20 @@
    (resumable = 0) an already suspended parser. Some call-backs may
    still follow because they would otherwise get lost. Examples:
    - endElementHandler() for empty elements when stopped in
-     startElementHandler(), 
-   - endNameSpaceDeclHandler() when stopped in endElementHandler(), 
+     startElementHandler(),
+   - endNameSpaceDeclHandler() when stopped in endElementHandler(),
    and possibly others.
 
    Can be called from most handlers, including DTD related call-backs,
    except when parsing an external parameter entity and resumable != 0.
    Returns XML_STATUS_OK when successful, XML_STATUS_ERROR otherwise.
-   Possible error codes: 
+   Possible error codes:
    - XML_ERROR_SUSPENDED: when suspending an already suspended parser.
    - XML_ERROR_FINISHED: when the parser has already finished.
    - XML_ERROR_SUSPEND_PE: when suspending while parsing an external PE.
 
-   When resumable != 0 (true) then parsing is suspended, that is, 
-   XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED. 
+   When resumable != 0 (true) then parsing is suspended, that is,
+   XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED.
    Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer()
    return XML_STATUS_ERROR with error code XML_ERROR_ABORTED.
 
@@ -843,7 +792,7 @@
    the externalEntityRefHandler() to call XML_StopParser() on the parent
    parser (recursively), if one wants to stop parsing altogether.
 
-   When suspended, parsing can be resumed by calling XML_ResumeParser(). 
+   When suspended, parsing can be resumed by calling XML_ResumeParser().
 */
 XMLPARSEAPI(enum XML_Status)
 XML_StopParser(XML_Parser parser, XML_Bool resumable);
@@ -851,7 +800,7 @@
 /* Resumes parsing after it has been suspended with XML_StopParser().
    Must not be called from within a handler call-back. Returns same
    status codes as XML_Parse() or XML_ParseBuffer().
-   Additional error code XML_ERROR_NOT_SUSPENDED possible.   
+   Additional error code XML_ERROR_NOT_SUSPENDED possible.
 
    *Note*:
    This must be called on the most deeply nested child parser instance
@@ -863,12 +812,7 @@
 XMLPARSEAPI(enum XML_Status)
 XML_ResumeParser(XML_Parser parser);
 
-enum XML_Parsing {
-  XML_INITIALIZED,
-  XML_PARSING,
-  XML_FINISHED,
-  XML_SUSPENDED
-};
+enum XML_Parsing { XML_INITIALIZED, XML_PARSING, XML_FINISHED, XML_SUSPENDED };
 
 typedef struct {
   enum XML_Parsing parsing;
@@ -900,8 +844,7 @@
    Otherwise returns a new XML_Parser object.
 */
 XMLPARSEAPI(XML_Parser)
-XML_ExternalEntityParserCreate(XML_Parser parser,
-                               const XML_Char *context,
+XML_ExternalEntityParserCreate(XML_Parser parser, const XML_Char *context,
                                const XML_Char *encoding);
 
 enum XML_ParamEntityParsing {
@@ -945,8 +888,7 @@
    Note: If parser == NULL, the function will do nothing and return 0.
 */
 XMLPARSEAPI(int)
-XML_SetHashSalt(XML_Parser parser,
-                unsigned long hash_salt);
+XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt);
 
 /* If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then
    XML_GetErrorCode returns information about the error.
@@ -963,7 +905,7 @@
    be within the relevant markup.  When called outside of the callback
    functions, the position indicated will be just past the last parse
    event (regardless of whether there was an associated callback).
-   
+
    They may also be called after returning from a call to XML_Parse
    or XML_ParseBuffer.  If the return value is XML_STATUS_ERROR then
    the location is the location of the character at which the error
@@ -995,14 +937,12 @@
    the handler that makes the call.
 */
 XMLPARSEAPI(const char *)
-XML_GetInputContext(XML_Parser parser,
-                    int *offset,
-                    int *size);
+XML_GetInputContext(XML_Parser parser, int *offset, int *size);
 
 /* For backwards compatibility with previous versions. */
-#define XML_GetErrorLineNumber   XML_GetCurrentLineNumber
+#define XML_GetErrorLineNumber XML_GetCurrentLineNumber
 #define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber
-#define XML_GetErrorByteIndex    XML_GetCurrentByteIndex
+#define XML_GetErrorByteIndex XML_GetCurrentByteIndex
 
 /* Frees the content model passed to the element declaration handler */
 XMLPARSEAPI(void)
@@ -1062,21 +1002,20 @@
 };
 
 typedef struct {
-  enum XML_FeatureEnum  feature;
-  const XML_LChar       *name;
-  long int              value;
+  enum XML_FeatureEnum feature;
+  const XML_LChar *name;
+  long int value;
 } XML_Feature;
 
 XMLPARSEAPI(const XML_Feature *)
 XML_GetFeatureList(void);
 
-
 /* Expat follows the semantic versioning convention.
    See http://semver.org.
 */
 #define XML_MAJOR_VERSION 2
 #define XML_MINOR_VERSION 2
-#define XML_MICRO_VERSION 6
+#define XML_MICRO_VERSION 8
 
 #ifdef __cplusplus
 }
diff --git a/third_party/expat/files/lib/expat_config.h b/third_party/expat/files/lib/expat_config.h
index 62d1dd3a..c693a14a 100644
--- a/third_party/expat/files/lib/expat_config.h
+++ b/third_party/expat/files/lib/expat_config.h
@@ -1,7 +1,10 @@
 /* expat_config.h.  Generated from expat_config.h.in by configure.  */
 /* expat_config.h.in.  Generated from configure.ac by autoheader.  */
 
-/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */
+/* Define if building universal (internal helper macro) */
+/* #undef AC_APPLE_UNIVERSAL_BUILD */
+
+/* 1234 = LILENDIAN, 4321 = BIGENDIAN */
 #define BYTEORDER 1234
 
 /* Define to 1 if you have the `arc4random' function. */
@@ -20,7 +23,7 @@
 #define HAVE_GETPAGESIZE 1
 
 /* Define to 1 if you have the `getrandom' function. */
-/* #undef HAVE_GETRANDOM */
+/* #define HAVE_GETRANDOM 1 */
 
 /* Define to 1 if you have the <inttypes.h> header file. */
 #define HAVE_INTTYPES_H 1
@@ -47,7 +50,7 @@
 #define HAVE_STRING_H 1
 
 /* Define to 1 if you have `syscall' and `SYS_getrandom'. */
-/* #undef HAVE_SYSCALL_GETRANDOM */
+/* #define HAVE_SYSCALL_GETRANDOM 1 */
 
 /* Define to 1 if you have the <sys/param.h> header file. */
 #define HAVE_SYS_PARAM_H 1
@@ -74,7 +77,7 @@
 #define PACKAGE_NAME "expat"
 
 /* Define to the full name and version of this package. */
-#define PACKAGE_STRING "expat 2.2.6"
+#define PACKAGE_STRING "expat 2.2.8"
 
 /* Define to the one symbol short name of this package. */
 #define PACKAGE_TARNAME "expat"
@@ -83,16 +86,29 @@
 #define PACKAGE_URL ""
 
 /* Define to the version of this package. */
-#define PACKAGE_VERSION "2.2.6"
+#define PACKAGE_VERSION "2.2.8"
 
 /* Define to 1 if you have the ANSI C header files. */
 #define STDC_HEADERS 1
 
 /* Version number of package */
-#define VERSION "2.2.6"
+#define VERSION "2.2.8"
 
-/* whether byteorder is bigendian */
-/* #undef WORDS_BIGENDIAN */
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+   significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+#  define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+/* #  undef WORDS_BIGENDIAN */
+# endif
+#endif
+
+/* Define to allow retrieving the byte offsets for attribute names and values.
+   */
+/* #undef XML_ATTR_INFO */
 
 /* Define to specify how much context to retain around the current parse
    point. */
diff --git a/third_party/expat/files/lib/expat_external.h b/third_party/expat/files/lib/expat_external.h
index 875225d..b3b6e74 100644
--- a/third_party/expat/files/lib/expat_external.h
+++ b/third_party/expat/files/lib/expat_external.h
@@ -35,10 +35,6 @@
 
 /* External API definitions */
 
-#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)
-# define XML_USE_MSC_EXTENSIONS 1
-#endif
-
 /* Expat tries very hard to make the API boundary very specifically
    defined.  There are two macros defined to control this boundary;
    each of these can be defined before including this header to
@@ -62,11 +58,11 @@
    system headers may assume the cdecl convention.
 */
 #ifndef XMLCALL
-# if defined(_MSC_VER)
-#  define XMLCALL __cdecl
-# elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)
-#  define XMLCALL __attribute__((cdecl))
-# else
+#  if defined(_MSC_VER)
+#    define XMLCALL __cdecl
+#  elif defined(__GNUC__) && defined(__i386) && ! defined(__INTEL_COMPILER)
+#    define XMLCALL __attribute__((cdecl))
+#  else
 /* For any platform which uses this definition and supports more than
    one calling convention, we need to extend this definition to
    declare the convention used on that platform, if it's possible to
@@ -77,45 +73,46 @@
    pre-processor and how to specify the same calling convention as the
    platform's malloc() implementation.
 */
-#  define XMLCALL
-# endif
-#endif  /* not defined XMLCALL */
+#    define XMLCALL
+#  endif
+#endif /* not defined XMLCALL */
 
-
-#if !defined(XML_STATIC) && !defined(XMLIMPORT)
-# ifndef XML_BUILDING_EXPAT
+#if ! defined(XML_STATIC) && ! defined(XMLIMPORT)
+#  ifndef XML_BUILDING_EXPAT
 /* using Expat from an application */
 
-#  ifdef XML_USE_MSC_EXTENSIONS
-#   define XMLIMPORT __declspec(dllimport)
-#  endif
+#    if defined(_MSC_EXTENSIONS) && ! defined(__BEOS__) && ! defined(__CYGWIN__)
+#      define XMLIMPORT __declspec(dllimport)
+#    endif
 
-# endif
-#endif  /* not defined XML_STATIC */
+#  endif
+#endif /* not defined XML_STATIC */
 
 #ifndef XML_ENABLE_VISIBILITY
-# define XML_ENABLE_VISIBILITY 0
+#  define XML_ENABLE_VISIBILITY 0
 #endif
 
-#if !defined(XMLIMPORT) && XML_ENABLE_VISIBILITY
-# define XMLIMPORT __attribute__ ((visibility ("default")))
+#if ! defined(XMLIMPORT) && XML_ENABLE_VISIBILITY
+#  define XMLIMPORT __attribute__((visibility("default")))
 #endif
 
 /* If we didn't define it above, define it away: */
 #ifndef XMLIMPORT
-# define XMLIMPORT
+#  define XMLIMPORT
 #endif
 
-#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96))
-# define XML_ATTR_MALLOC __attribute__((__malloc__))
+#if defined(__GNUC__)                                                          \
+    && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96))
+#  define XML_ATTR_MALLOC __attribute__((__malloc__))
 #else
-# define XML_ATTR_MALLOC
+#  define XML_ATTR_MALLOC
 #endif
 
-#if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
-# define XML_ATTR_ALLOC_SIZE(x)  __attribute__((__alloc_size__(x)))
+#if defined(__GNUC__)                                                          \
+    && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
+#  define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x)))
 #else
-# define XML_ATTR_ALLOC_SIZE(x)
+#  define XML_ATTR_ALLOC_SIZE(x)
 #endif
 
 #define XMLPARSEAPI(type) XMLIMPORT type XMLCALL
@@ -125,35 +122,30 @@
 #endif
 
 #ifdef XML_UNICODE_WCHAR_T
-# ifndef XML_UNICODE
-#  define XML_UNICODE
-# endif
-# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2)
-#  error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc"
-# endif
+#  ifndef XML_UNICODE
+#    define XML_UNICODE
+#  endif
+#  if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2)
+#    error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc"
+#  endif
 #endif
 
-#ifdef XML_UNICODE     /* Information is UTF-16 encoded. */
-# ifdef XML_UNICODE_WCHAR_T
+#ifdef XML_UNICODE /* Information is UTF-16 encoded. */
+#  ifdef XML_UNICODE_WCHAR_T
 typedef wchar_t XML_Char;
 typedef wchar_t XML_LChar;
-# else
+#  else
 typedef unsigned short XML_Char;
 typedef char XML_LChar;
-# endif /* XML_UNICODE_WCHAR_T */
-#else                  /* Information is UTF-8 encoded. */
+#  endif /* XML_UNICODE_WCHAR_T */
+#else    /* Information is UTF-8 encoded. */
 typedef char XML_Char;
 typedef char XML_LChar;
-#endif /* XML_UNICODE */
+#endif   /* XML_UNICODE */
 
-#ifdef XML_LARGE_SIZE  /* Use large integers for file/stream positions. */
-# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
-typedef __int64 XML_Index; 
-typedef unsigned __int64 XML_Size;
-# else
+#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */
 typedef long long XML_Index;
 typedef unsigned long long XML_Size;
-# endif
 #else
 typedef long XML_Index;
 typedef unsigned long XML_Size;
diff --git a/third_party/expat/files/lib/iasciitab.h b/third_party/expat/files/lib/iasciitab.h
index ce4a4bf..ea97cfc 100644
--- a/third_party/expat/files/lib/iasciitab.h
+++ b/third_party/expat/files/lib/iasciitab.h
@@ -32,34 +32,34 @@
 
 /* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */
 /* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
-/* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML,
-/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
-/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
-/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
-/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
-/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
-/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
-/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
-/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
-/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
-/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
-/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
-/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
-/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
-/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
-/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
-/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML,
+    /* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML,
+    /* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM,
+    /* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS,
+    /* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS,
+    /* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL,
+    /* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
+    /* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT,
+    /* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI,
+    /* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST,
+    /* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
+    /* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
+    /* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB,
+    /* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT,
+    /* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX,
+    /* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT,
+    /* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
+    /* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER,
diff --git a/third_party/expat/files/lib/internal.h b/third_party/expat/files/lib/internal.h
index dc4ef0c..60913dab 100644
--- a/third_party/expat/files/lib/internal.h
+++ b/third_party/expat/files/lib/internal.h
@@ -49,7 +49,7 @@
    USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#if defined(__GNUC__) && defined(__i386__) && !defined(__MINGW32__)
+#if defined(__GNUC__) && defined(__i386__) && ! defined(__MINGW32__)
 /* We'll use this version by default only where we know it helps.
 
    regparm() generates warnings on Solaris boxes.   See SF bug #692878.
@@ -59,8 +59,8 @@
    #define FASTCALL __attribute__((stdcall, regparm(3)))
    and let's try this:
 */
-#define FASTCALL __attribute__((regparm(3)))
-#define PTRFASTCALL __attribute__((regparm(3)))
+#  define FASTCALL __attribute__((regparm(3)))
+#  define PTRFASTCALL __attribute__((regparm(3)))
 #endif
 
 /* Using __fastcall seems to have an unexpected negative effect under
@@ -74,55 +74,49 @@
 /* Make sure all of these are defined if they aren't already. */
 
 #ifndef FASTCALL
-#define FASTCALL
+#  define FASTCALL
 #endif
 
 #ifndef PTRCALL
-#define PTRCALL
+#  define PTRCALL
 #endif
 
 #ifndef PTRFASTCALL
-#define PTRFASTCALL
+#  define PTRFASTCALL
 #endif
 
 #ifndef XML_MIN_SIZE
-#if !defined(__cplusplus) && !defined(inline)
-#ifdef __GNUC__
-#define inline __inline
-#endif /* __GNUC__ */
-#endif
+#  if ! defined(__cplusplus) && ! defined(inline)
+#    ifdef __GNUC__
+#      define inline __inline
+#    endif /* __GNUC__ */
+#  endif
 #endif /* XML_MIN_SIZE */
 
 #ifdef __cplusplus
-#define inline inline
+#  define inline inline
 #else
-#ifndef inline
-#define inline
-#endif
+#  ifndef inline
+#    define inline
+#  endif
 #endif
 
 #ifndef UNUSED_P
-# ifdef __GNUC__
-#  define UNUSED_P(p) UNUSED_ ## p __attribute__((__unused__))
-# else
-#  define UNUSED_P(p) UNUSED_ ## p
-# endif
+#  define UNUSED_P(p) (void)p
 #endif
 
-
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-
 #ifdef XML_ENABLE_VISIBILITY
-#if XML_ENABLE_VISIBILITY
-__attribute__ ((visibility ("default")))
-#endif
+#  if XML_ENABLE_VISIBILITY
+__attribute__((visibility("default")))
+#  endif
 #endif
 void
-_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef);
-
+_INTERNAL_trim_to_complete_utf8_characters(const char *from,
+                                           const char **fromLimRef);
 
 #ifdef __cplusplus
 }
diff --git a/third_party/expat/files/lib/latin1tab.h b/third_party/expat/files/lib/latin1tab.h
index 95dfa52..6f91604 100644
--- a/third_party/expat/files/lib/latin1tab.h
+++ b/third_party/expat/files/lib/latin1tab.h
@@ -31,34 +31,34 @@
 */
 
 /* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
-/* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME,
-/* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
-/* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
-/* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
-/* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
-/* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
-/* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
+    /* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME,
+    /* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER,
+    /* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
+    /* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
+    /* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER,
+    /* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
+    /* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT,
diff --git a/third_party/expat/files/lib/libexpat.def b/third_party/expat/files/lib/libexpat.def
index d08f5b7c..16faf595 100644
--- a/third_party/expat/files/lib/libexpat.def
+++ b/third_party/expat/files/lib/libexpat.def
@@ -73,6 +73,6 @@
   XML_GetParsingStatus @65
 ; added with version 2.1.1
 ; XML_GetAttributeInfo @66
-  XML_SetHashSalt @67@
+  XML_SetHashSalt @67
 ; added with version 2.2.5
-  _INTERNAL_trim_to_complete_utf8_characters @68@
\ No newline at end of file
+  _INTERNAL_trim_to_complete_utf8_characters @68
diff --git a/third_party/expat/files/lib/libexpatw.def b/third_party/expat/files/lib/libexpatw.def
index 928e01b1..16faf595 100644
--- a/third_party/expat/files/lib/libexpatw.def
+++ b/third_party/expat/files/lib/libexpatw.def
@@ -73,6 +73,6 @@
   XML_GetParsingStatus @65
 ; added with version 2.1.1
 ; XML_GetAttributeInfo @66
-  XML_SetHashSalt @67@
+  XML_SetHashSalt @67
 ; added with version 2.2.5
-  _INTERNAL_trim_to_complete_utf8_characters @68@
+  _INTERNAL_trim_to_complete_utf8_characters @68
diff --git a/third_party/expat/files/lib/loadlibrary.c b/third_party/expat/files/lib/loadlibrary.c
deleted file mode 100644
index 19dc74d9..0000000
--- a/third_party/expat/files/lib/loadlibrary.c
+++ /dev/null
@@ -1,144 +0,0 @@
-/***************************************************************************
- *                                  _   _ ____  _
- *  Project                     ___| | | |  _ \| |
- *                             / __| | | | |_) | |
- *                            | (__| |_| |  _ <| |___
- *                             \___|\___/|_| \_\_____|
- *
- * Copyright (C) 2016 - 2017, Steve Holme, <steve_holme@hotmail.com>.
- * Copyright (C) 2017, Expat development team
- *
- * All rights reserved.
- * Licensed under the MIT license:
- *
- * Permission to  use, copy,  modify, and distribute  this software  for any
- * purpose with  or without fee is  hereby granted, provided that  the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE  SOFTWARE  IS  PROVIDED  "AS  IS",  WITHOUT  WARRANTY  OF  ANY  KIND,
- * EXPRESS  OR IMPLIED,  INCLUDING  BUT  NOT LIMITED  TO  THE WARRANTIES  OF
- * MERCHANTABILITY, FITNESS FOR A  PARTICULAR PURPOSE AND NONINFRINGEMENT OF
- * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR  OTHERWISE, ARISING FROM, OUT OF OR  IN CONNECTION WITH
- * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice,  the name of a copyright holder shall
- * not be used in advertising or otherwise to promote the sale, use or other
- * dealings  in this  Software without  prior written  authorization of  the
- * copyright holder.
- *
- ***************************************************************************/
-
-#if defined(_WIN32)
-
-#include <windows.h>
-#include <stdlib.h>
-#include <tchar.h>
-
-
-HMODULE _Expat_LoadLibrary(LPCTSTR filename);
-
-
-#if !defined(LOAD_WITH_ALTERED_SEARCH_PATH)
-#define LOAD_WITH_ALTERED_SEARCH_PATH  0x00000008
-#endif
-
-#if !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
-#define LOAD_LIBRARY_SEARCH_SYSTEM32   0x00000800
-#endif
-
-/* We use our own typedef here since some headers might lack these */
-typedef HMODULE (APIENTRY *LOADLIBRARYEX_FN)(LPCTSTR, HANDLE, DWORD);
-
-/* See function definitions in winbase.h */
-#ifdef UNICODE
-#  ifdef _WIN32_WCE
-#    define LOADLIBARYEX  L"LoadLibraryExW"
-#  else
-#    define LOADLIBARYEX  "LoadLibraryExW"
-#  endif
-#else
-#  define LOADLIBARYEX    "LoadLibraryExA"
-#endif
-
-
-/*
- * _Expat_LoadLibrary()
- *
- * This is used to dynamically load DLLs using the most secure method available
- * for the version of Windows that we are running on.
- *
- * Parameters:
- *
- * filename  [in] - The filename or full path of the DLL to load. If only the
- *                  filename is passed then the DLL will be loaded from the
- *                  Windows system directory.
- *
- * Returns the handle of the module on success; otherwise NULL.
- */
-HMODULE _Expat_LoadLibrary(LPCTSTR filename)
-{
-  HMODULE hModule = NULL;
-  LOADLIBRARYEX_FN pLoadLibraryEx = NULL;
-
-  /* Get a handle to kernel32 so we can access it's functions at runtime */
-  HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32"));
-  if(!hKernel32)
-    return NULL;  /* LCOV_EXCL_LINE */
-
-  /* Attempt to find LoadLibraryEx() which is only available on Windows 2000
-     and above */
-  pLoadLibraryEx = (LOADLIBRARYEX_FN) GetProcAddress(hKernel32, LOADLIBARYEX);
-
-  /* Detect if there's already a path in the filename and load the library if
-     there is. Note: Both back slashes and forward slashes have been supported
-     since the earlier days of DOS at an API level although they are not
-     supported by command prompt */
-  if(_tcspbrk(filename, TEXT("\\/"))) {
-    /** !checksrc! disable BANNEDFUNC 1 **/
-    hModule = pLoadLibraryEx ?
-      pLoadLibraryEx(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
-      LoadLibrary(filename);
-  }
-  /* Detect if KB2533623 is installed, as LOAD_LIBARY_SEARCH_SYSTEM32 is only
-     supported on Windows Vista, Windows Server 2008, Windows 7 and Windows
-     Server 2008 R2 with this patch or natively on Windows 8 and above */
-  else if(pLoadLibraryEx && GetProcAddress(hKernel32, "AddDllDirectory")) {
-    /* Load the DLL from the Windows system directory */
-    hModule = pLoadLibraryEx(filename, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
-  }
-  else {
-    /* Attempt to get the Windows system path */
-    UINT systemdirlen = GetSystemDirectory(NULL, 0);
-    if(systemdirlen) {
-      /* Allocate space for the full DLL path (Room for the null terminator
-         is included in systemdirlen) */
-      size_t filenamelen = _tcslen(filename);
-      TCHAR *path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen));
-      if(path && GetSystemDirectory(path, systemdirlen)) {
-        /* Calculate the full DLL path */
-        _tcscpy(path + _tcslen(path), TEXT("\\"));
-        _tcscpy(path + _tcslen(path), filename);
-
-        /* Load the DLL from the Windows system directory */
-        /** !checksrc! disable BANNEDFUNC 1 **/
-        hModule = pLoadLibraryEx ?
-          pLoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
-          LoadLibrary(path);
-
-      }
-      free(path);
-    }
-  }
-
-  return hModule;
-}
-
-#else /* defined(_WIN32) */
-
-/* ISO C requires a translation unit to contain at least one declaration
-   [-Wempty-translation-unit] */
-typedef int _TRANSLATION_UNIT_LOAD_LIBRARY_C_NOT_EMTPY;
-
-#endif /* defined(_WIN32) */
diff --git a/third_party/expat/files/lib/nametab.h b/third_party/expat/files/lib/nametab.h
index bfa2bd3..3681df3 100644
--- a/third_party/expat/files/lib/nametab.h
+++ b/third_party/expat/files/lib/nametab.h
@@ -31,152 +31,106 @@
 */
 
 static const unsigned namingBitmap[] = {
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
-0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
-0x00000000, 0x04000000, 0x87FFFFFE, 0x07FFFFFE,
-0x00000000, 0x00000000, 0xFF7FFFFF, 0xFF7FFFFF,
-0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF,
-0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFE00F, 0xFC31FFFF,
-0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF,
-0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD,
-0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF,
-0xFFFF0003, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF,
-0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE,
-0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF,
-0x00000000, 0x07FFFFFE, 0x000007FE, 0xFFFE0000,
-0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060,
-0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003,
-0xFFF99FE0, 0x03C5FDFF, 0xB0000000, 0x00030003,
-0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000,
-0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001,
-0xFFF99FE0, 0x23CDFDFF, 0xB0000000, 0x00000003,
-0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000,
-0xFFFDDFE0, 0x03EFFDFF, 0x00000000, 0x00000003,
-0xFFFDDFE0, 0x03EFFDFF, 0x40000000, 0x00000003,
-0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0xFFFFFFFE, 0x000D7FFF, 0x0000003F, 0x00000000,
-0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000,
-0x00000000, 0x00000000, 0xFFFFFEFF, 0x000003FF,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF,
-0x0007DAED, 0x50000000, 0x82315001, 0x002C62AB,
-0x40000000, 0xF580C900, 0x00000007, 0x02010800,
-0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
-0x0FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x03FFFFFF,
-0x3F3FFFFF, 0xFFFFFFFF, 0xAAFF3F3F, 0x3FFFFFFF,
-0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF,
-0x00000000, 0x00004C40, 0x00000000, 0x00000000,
-0x00000007, 0x00000000, 0x00000000, 0x00000000,
-0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF,
-0x001FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x07FFFFFF,
-0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
-0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000,
-0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
-0xFFFFFFFF, 0x0000000F, 0x00000000, 0x00000000,
-0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE,
-0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF,
-0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF,
-0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000,
-0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003,
-0xFFFFD7C0, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD,
-0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF,
-0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF,
-0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE,
-0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF,
-0x00000000, 0x07FFFFFE, 0x0007FFFF, 0xFFFF03FF,
-0xFFFFFFFF, 0x7CFFFFFF, 0xFFEF7FFF, 0x03FF3DFF,
-0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF,
-0xFFF99FEE, 0xD3C5FDFF, 0xB080399F, 0x0003FFCF,
-0xFFF987E4, 0xD36DFDFF, 0x5E003987, 0x001FFFC0,
-0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1,
-0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3,
-0xD63DC7EC, 0xC3BFC718, 0x00803DC7, 0x0000FF80,
-0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, 0x0000FFC3,
-0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3,
-0xFFFDDFEC, 0xC3FFFDFF, 0x00803DCF, 0x0000FFC3,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000,
-0xFEF02596, 0x3BFF6CAE, 0x03FF3F5F, 0x00000000,
-0x03000000, 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF,
-0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000,
-0x00000000, 0x00000000, 0x00000000, 0x00000000,
-0x00000000, 0x00000000, 0x1FFF0000, 0x00000002,
-0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF,
-0x661FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x77FFFFFF,
+    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x04000000,
+    0x87FFFFFE, 0x07FFFFFE, 0x00000000, 0x00000000, 0xFF7FFFFF, 0xFF7FFFFF,
+    0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
+    0xFFFFE00F, 0xFC31FFFF, 0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF,
+    0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0x00000000, 0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD,
+    0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, 0xFFFF0003, 0xFFFFFFFF,
+    0xFFFF199F, 0x033FCFFF, 0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE,
+    0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF, 0x00000000, 0x07FFFFFE,
+    0x000007FE, 0xFFFE0000, 0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060,
+    0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003, 0xFFF99FE0, 0x03C5FDFF,
+    0xB0000000, 0x00030003, 0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000,
+    0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001, 0xFFF99FE0, 0x23CDFDFF,
+    0xB0000000, 0x00000003, 0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000,
+    0xFFFDDFE0, 0x03EFFDFF, 0x00000000, 0x00000003, 0xFFFDDFE0, 0x03EFFDFF,
+    0x40000000, 0x00000003, 0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003,
+    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFE, 0x000D7FFF,
+    0x0000003F, 0x00000000, 0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000,
+    0x00000000, 0x00000000, 0xFFFFFEFF, 0x000003FF, 0x00000000, 0x00000000,
+    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF, 0x0007DAED, 0x50000000,
+    0x82315001, 0x002C62AB, 0x40000000, 0xF580C900, 0x00000007, 0x02010800,
+    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0FFFFFFF, 0xFFFFFFFF,
+    0xFFFFFFFF, 0x03FFFFFF, 0x3F3FFFFF, 0xFFFFFFFF, 0xAAFF3F3F, 0x3FFFFFFF,
+    0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF, 0x00000000, 0x00004C40,
+    0x00000000, 0x00000000, 0x00000007, 0x00000000, 0x00000000, 0x00000000,
+    0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF, 0x001FFFFF, 0xFFFFFFFE,
+    0xFFFFFFFF, 0x07FFFFFF, 0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000,
+    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF,
+    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000,
+    0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0000000F,
+    0x00000000, 0x00000000, 0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE,
+    0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF, 0x00FFFFFF, 0x00000000,
+    0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000,
+    0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003, 0xFFFFD7C0, 0xFFFFFFFB,
+    0x547F7FFF, 0x000FFFFD, 0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF,
+    0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF, 0x00000000, 0xFFFE0000,
+    0x027FFFFF, 0xFFFFFFFE, 0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF,
+    0x00000000, 0x07FFFFFE, 0x0007FFFF, 0xFFFF03FF, 0xFFFFFFFF, 0x7CFFFFFF,
+    0xFFEF7FFF, 0x03FF3DFF, 0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF,
+    0xFFF99FEE, 0xD3C5FDFF, 0xB080399F, 0x0003FFCF, 0xFFF987E4, 0xD36DFDFF,
+    0x5E003987, 0x001FFFC0, 0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1,
+    0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3, 0xD63DC7EC, 0xC3BFC718,
+    0x00803DC7, 0x0000FF80, 0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, 0x0000FFC3,
+    0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3, 0xFFFDDFEC, 0xC3FFFDFF,
+    0x00803DCF, 0x0000FFC3, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000, 0xFEF02596, 0x3BFF6CAE,
+    0x03FF3F5F, 0x00000000, 0x03000000, 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF,
+    0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x1FFF0000, 0x00000002,
+    0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF, 0x661FFFFF, 0xFFFFFFFE,
+    0xFFFFFFFF, 0x77FFFFFF,
 };
 static const unsigned char nmstrtPages[] = {
-0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00,
-0x00, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
-0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13,
-0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00, 0x09, 0x0A, 0x0B,
+    0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x00, 0x14, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00,
 };
 static const unsigned char namePages[] = {
-0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00,
-0x00, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25,
-0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13,
-0x26, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00, 0x00, 0x1F, 0x20, 0x21,
+    0x22, 0x23, 0x24, 0x25, 0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, 0x26, 0x14, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
+    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x00, 0x00, 0x00,
 };
diff --git a/third_party/expat/files/lib/siphash.h b/third_party/expat/files/lib/siphash.h
index 4d6786d7..bfee65a 100644
--- a/third_party/expat/files/lib/siphash.h
+++ b/third_party/expat/files/lib/siphash.h
@@ -11,6 +11,10 @@
  * --------------------------------------------------------------------------
  * HISTORY:
  *
+ * 2019-08-03  (Sebastian Pipping)
+ *   - Mark part of sip24_valid as to be excluded from clang-format
+ *   - Re-format code using clang-format 9
+ *
  * 2018-07-08  (Anton Maklakov)
  *   - Add "fall through" markers for GCC's -Wimplicit-fallthrough
  *
@@ -94,186 +98,186 @@
 #include <stddef.h> /* size_t */
 
 #if defined(_WIN32) && defined(_MSC_VER) && (_MSC_VER < 1600)
-  /* For vs2003/7.1 up to vs2008/9.0; _MSC_VER 1600 is vs2010/10.0 */
-  typedef unsigned __int8   uint8_t;
-  typedef unsigned __int32 uint32_t;
-  typedef unsigned __int64 uint64_t;
+/* For vs2003/7.1 up to vs2008/9.0; _MSC_VER 1600 is vs2010/10.0 */
+typedef unsigned __int8 uint8_t;
+typedef unsigned __int32 uint32_t;
+typedef unsigned __int64 uint64_t;
 #else
- #include <stdint.h> /* uint64_t uint32_t uint8_t */
+#  include <stdint.h> /* uint64_t uint32_t uint8_t */
 #endif
 
-
 /*
  * Workaround to not require a C++11 compiler for using ULL suffix
  * if this code is included and compiled as C++; related GCC warning is:
  * warning: use of C++11 long long integer constant [-Wlong-long]
  */
-#define _SIP_ULL(high, low)  (((uint64_t)high << 32) | low)
+#define _SIP_ULL(high, low) (((uint64_t)high << 32) | low)
 
+#define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))
 
-#define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ( (x) >> (64 - (b))))
+#define SIP_U32TO8_LE(p, v)                                                    \
+  (p)[0] = (uint8_t)((v) >> 0);                                                \
+  (p)[1] = (uint8_t)((v) >> 8);                                                \
+  (p)[2] = (uint8_t)((v) >> 16);                                               \
+  (p)[3] = (uint8_t)((v) >> 24);
 
-#define SIP_U32TO8_LE(p, v) \
-	(p)[0] = (uint8_t)((v) >>  0); (p)[1] = (uint8_t)((v) >>  8); \
-	(p)[2] = (uint8_t)((v) >> 16); (p)[3] = (uint8_t)((v) >> 24);
+#define SIP_U64TO8_LE(p, v)                                                    \
+  SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >> 0));                                \
+  SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));
 
-#define SIP_U64TO8_LE(p, v) \
-	SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >>  0)); \
-	SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32));
+#define SIP_U8TO64_LE(p)                                                       \
+  (((uint64_t)((p)[0]) << 0) | ((uint64_t)((p)[1]) << 8)                       \
+   | ((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24)                   \
+   | ((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40)                   \
+   | ((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56))
 
-#define SIP_U8TO64_LE(p) \
-	(((uint64_t)((p)[0]) <<  0) | \
-	 ((uint64_t)((p)[1]) <<  8) | \
-	 ((uint64_t)((p)[2]) << 16) | \
-	 ((uint64_t)((p)[3]) << 24) | \
-	 ((uint64_t)((p)[4]) << 32) | \
-	 ((uint64_t)((p)[5]) << 40) | \
-	 ((uint64_t)((p)[6]) << 48) | \
-	 ((uint64_t)((p)[7]) << 56))
-
-
-#define SIPHASH_INITIALIZER { 0, 0, 0, 0, { 0 }, 0, 0 }
+#define SIPHASH_INITIALIZER                                                    \
+  { 0, 0, 0, 0, {0}, 0, 0 }
 
 struct siphash {
-	uint64_t v0, v1, v2, v3;
+  uint64_t v0, v1, v2, v3;
 
-	unsigned char buf[8], *p;
-	uint64_t c;
+  unsigned char buf[8], *p;
+  uint64_t c;
 }; /* struct siphash */
 
-
 #define SIP_KEYLEN 16
 
 struct sipkey {
-	uint64_t k[2];
+  uint64_t k[2];
 }; /* struct sipkey */
 
-#define sip_keyof(k) sip_tokey(&(struct sipkey){ { 0 } }, (k))
+#define sip_keyof(k) sip_tokey(&(struct sipkey){{0}}, (k))
 
-static struct sipkey *sip_tokey(struct sipkey *key, const void *src) {
-	key->k[0] = SIP_U8TO64_LE((const unsigned char *)src);
-	key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8);
-	return key;
+static struct sipkey *
+sip_tokey(struct sipkey *key, const void *src) {
+  key->k[0] = SIP_U8TO64_LE((const unsigned char *)src);
+  key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8);
+  return key;
 } /* sip_tokey() */
 
-
 #ifdef SIPHASH_TOBIN
 
-#define sip_binof(v) sip_tobin((unsigned char[8]){ 0 }, (v))
+#  define sip_binof(v) sip_tobin((unsigned char[8]){0}, (v))
 
-static void *sip_tobin(void *dst, uint64_t u64) {
-	SIP_U64TO8_LE((unsigned char *)dst, u64);
-	return dst;
+static void *
+sip_tobin(void *dst, uint64_t u64) {
+  SIP_U64TO8_LE((unsigned char *)dst, u64);
+  return dst;
 } /* sip_tobin() */
 
-#endif  /* SIPHASH_TOBIN */
+#endif /* SIPHASH_TOBIN */
 
+static void
+sip_round(struct siphash *H, const int rounds) {
+  int i;
 
-static void sip_round(struct siphash *H, const int rounds) {
-	int i;
+  for (i = 0; i < rounds; i++) {
+    H->v0 += H->v1;
+    H->v1 = SIP_ROTL(H->v1, 13);
+    H->v1 ^= H->v0;
+    H->v0 = SIP_ROTL(H->v0, 32);
 
-	for (i = 0; i < rounds; i++) {
-		H->v0 += H->v1;
-		H->v1 = SIP_ROTL(H->v1, 13);
-		H->v1 ^= H->v0;
-		H->v0 = SIP_ROTL(H->v0, 32);
+    H->v2 += H->v3;
+    H->v3 = SIP_ROTL(H->v3, 16);
+    H->v3 ^= H->v2;
 
-		H->v2 += H->v3;
-		H->v3 = SIP_ROTL(H->v3, 16);
-		H->v3 ^= H->v2;
+    H->v0 += H->v3;
+    H->v3 = SIP_ROTL(H->v3, 21);
+    H->v3 ^= H->v0;
 
-		H->v0 += H->v3;
-		H->v3 = SIP_ROTL(H->v3, 21);
-		H->v3 ^= H->v0;
-
-		H->v2 += H->v1;
-		H->v1 = SIP_ROTL(H->v1, 17);
-		H->v1 ^= H->v2;
-		H->v2 = SIP_ROTL(H->v2, 32);
-	}
+    H->v2 += H->v1;
+    H->v1 = SIP_ROTL(H->v1, 17);
+    H->v1 ^= H->v2;
+    H->v2 = SIP_ROTL(H->v2, 32);
+  }
 } /* sip_round() */
 
+static struct siphash *
+sip24_init(struct siphash *H, const struct sipkey *key) {
+  H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0];
+  H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1];
+  H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0];
+  H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1];
 
-static struct siphash *sip24_init(struct siphash *H,
-		const struct sipkey *key) {
-	H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0];
-	H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1];
-	H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0];
-	H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1];
+  H->p = H->buf;
+  H->c = 0;
 
-	H->p = H->buf;
-	H->c = 0;
-
-	return H;
+  return H;
 } /* sip24_init() */
 
+#define sip_endof(a) (&(a)[sizeof(a) / sizeof *(a)])
 
-#define sip_endof(a) (&(a)[sizeof (a) / sizeof *(a)])
+static struct siphash *
+sip24_update(struct siphash *H, const void *src, size_t len) {
+  const unsigned char *p = (const unsigned char *)src, *pe = p + len;
+  uint64_t m;
 
-static struct siphash *sip24_update(struct siphash *H, const void *src,
-		size_t len) {
-	const unsigned char *p = (const unsigned char *)src, *pe = p + len;
-	uint64_t m;
+  do {
+    while (p < pe && H->p < sip_endof(H->buf))
+      *H->p++ = *p++;
 
-	do {
-		while (p < pe && H->p < sip_endof(H->buf))
-			*H->p++ = *p++;
+    if (H->p < sip_endof(H->buf))
+      break;
 
-		if (H->p < sip_endof(H->buf))
-			break;
+    m = SIP_U8TO64_LE(H->buf);
+    H->v3 ^= m;
+    sip_round(H, 2);
+    H->v0 ^= m;
 
-		m = SIP_U8TO64_LE(H->buf);
-		H->v3 ^= m;
-		sip_round(H, 2);
-		H->v0 ^= m;
+    H->p = H->buf;
+    H->c += 8;
+  } while (p < pe);
 
-		H->p = H->buf;
-		H->c += 8;
-	} while (p < pe);
-
-	return H;
+  return H;
 } /* sip24_update() */
 
+static uint64_t
+sip24_final(struct siphash *H) {
+  const char left = (char)(H->p - H->buf);
+  uint64_t b = (H->c + left) << 56;
 
-static uint64_t sip24_final(struct siphash *H) {
-	const char left = (char)(H->p - H->buf);
-	uint64_t b = (H->c + left) << 56;
+  switch (left) {
+  case 7:
+    b |= (uint64_t)H->buf[6] << 48;
+    /* fall through */
+  case 6:
+    b |= (uint64_t)H->buf[5] << 40;
+    /* fall through */
+  case 5:
+    b |= (uint64_t)H->buf[4] << 32;
+    /* fall through */
+  case 4:
+    b |= (uint64_t)H->buf[3] << 24;
+    /* fall through */
+  case 3:
+    b |= (uint64_t)H->buf[2] << 16;
+    /* fall through */
+  case 2:
+    b |= (uint64_t)H->buf[1] << 8;
+    /* fall through */
+  case 1:
+    b |= (uint64_t)H->buf[0] << 0;
+    /* fall through */
+  case 0:
+    break;
+  }
 
-	switch (left) {
-	case 7: b |= (uint64_t)H->buf[6] << 48;
-		/* fall through */
-	case 6: b |= (uint64_t)H->buf[5] << 40;
-		/* fall through */
-	case 5: b |= (uint64_t)H->buf[4] << 32;
-		/* fall through */
-	case 4: b |= (uint64_t)H->buf[3] << 24;
-		/* fall through */
-	case 3: b |= (uint64_t)H->buf[2] << 16;
-		/* fall through */
-	case 2: b |= (uint64_t)H->buf[1] << 8;
-		/* fall through */
-	case 1: b |= (uint64_t)H->buf[0] << 0;
-		/* fall through */
-	case 0: break;
-	}
+  H->v3 ^= b;
+  sip_round(H, 2);
+  H->v0 ^= b;
+  H->v2 ^= 0xff;
+  sip_round(H, 4);
 
-	H->v3 ^= b;
-	sip_round(H, 2);
-	H->v0 ^= b;
-	H->v2 ^= 0xff;
-	sip_round(H, 4);
-
-	return H->v0 ^ H->v1 ^ H->v2  ^ H->v3;
+  return H->v0 ^ H->v1 ^ H->v2 ^ H->v3;
 } /* sip24_final() */
 
-
-static uint64_t siphash24(const void *src, size_t len,
-		const struct sipkey *key) {
-	struct siphash state = SIPHASH_INITIALIZER;
-	return sip24_final(sip24_update(sip24_init(&state, key), src, len));
+static uint64_t
+siphash24(const void *src, size_t len, const struct sipkey *key) {
+  struct siphash state = SIPHASH_INITIALIZER;
+  return sip24_final(sip24_update(sip24_init(&state, key), src, len));
 } /* siphash24() */
 
-
 /*
  * SipHash-2-4 output with
  * k = 00 01 02 ...
@@ -285,107 +289,110 @@
  * ...
  * in = 00 01 02 ... 3e (63 bytes)
  */
-static int sip24_valid(void) {
-	static const unsigned char vectors[64][8] = {
-		{ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, },
-		{ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, },
-		{ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, },
-		{ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, },
-		{ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, },
-		{ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, },
-		{ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, },
-		{ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, },
-		{ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, },
-		{ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, },
-		{ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, },
-		{ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, },
-		{ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, },
-		{ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, },
-		{ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, },
-		{ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, },
-		{ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, },
-		{ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, },
-		{ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, },
-		{ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, },
-		{ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, },
-		{ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, },
-		{ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, },
-		{ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, },
-		{ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, },
-		{ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, },
-		{ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, },
-		{ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, },
-		{ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, },
-		{ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, },
-		{ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, },
-		{ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, },
-		{ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, },
-		{ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, },
-		{ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, },
-		{ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, },
-		{ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, },
-		{ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, },
-		{ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, },
-		{ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, },
-		{ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, },
-		{ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, },
-		{ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, },
-		{ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, },
-		{ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, },
-		{ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, },
-		{ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, },
-		{ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, },
-		{ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, },
-		{ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, },
-		{ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, },
-		{ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, },
-		{ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, },
-		{ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, },
-		{ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, },
-		{ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, },
-		{ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, },
-		{ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, },
-		{ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, },
-		{ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, },
-		{ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, },
-		{ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, },
-		{ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, },
-		{ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, }
-	};
-	unsigned char in[64];
-	struct sipkey k;
-	size_t i;
+static int
+sip24_valid(void) {
+  /* clang-format off */
+  static const unsigned char vectors[64][8] = {
+    { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, },
+    { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, },
+    { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, },
+    { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, },
+    { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, },
+    { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, },
+    { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, },
+    { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, },
+    { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, },
+    { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, },
+    { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, },
+    { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, },
+    { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, },
+    { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, },
+    { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, },
+    { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, },
+    { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, },
+    { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, },
+    { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, },
+    { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, },
+    { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, },
+    { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, },
+    { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, },
+    { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, },
+    { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, },
+    { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, },
+    { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, },
+    { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, },
+    { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, },
+    { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, },
+    { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, },
+    { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, },
+    { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, },
+    { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, },
+    { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, },
+    { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, },
+    { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, },
+    { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, },
+    { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, },
+    { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, },
+    { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, },
+    { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, },
+    { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, },
+    { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, },
+    { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, },
+    { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, },
+    { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, },
+    { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, },
+    { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, },
+    { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, },
+    { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, },
+    { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, },
+    { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, },
+    { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, },
+    { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, },
+    { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, },
+    { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, },
+    { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, },
+    { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, },
+    { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, },
+    { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, },
+    { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, },
+    { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, },
+    { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, }
+  };
+  /* clang-format on */
 
-	sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011"
-			"\012\013\014\015\016\017");
+  unsigned char in[64];
+  struct sipkey k;
+  size_t i;
 
-	for (i = 0; i < sizeof in; ++i) {
-		in[i] = (unsigned char)i;
+  sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011"
+                "\012\013\014\015\016\017");
 
-		if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i]))
-			return 0;
-	}
+  for (i = 0; i < sizeof in; ++i) {
+    in[i] = (unsigned char)i;
 
-	return 1;
+    if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i]))
+      return 0;
+  }
+
+  return 1;
 } /* sip24_valid() */
 
-
 #ifdef SIPHASH_MAIN
 
-#include <stdio.h>
+#  include <stdio.h>
 
-int main(void) {
-	const int ok = sip24_valid();
+int
+main(void) {
+  const int ok = sip24_valid();
 
-	if (ok)
-		puts("OK");
-	else
-		puts("FAIL");
+  if (ok)
+    puts("OK");
+  else
+    puts("FAIL");
 
-	return !ok;
+  return ! ok;
 } /* main() */
 
 #endif /* SIPHASH_MAIN */
 
-
 #endif /* SIPHASH_H */
diff --git a/third_party/expat/files/lib/utf8tab.h b/third_party/expat/files/lib/utf8tab.h
index fa0bed6f5..a22986a 100644
--- a/third_party/expat/files/lib/utf8tab.h
+++ b/third_party/expat/files/lib/utf8tab.h
@@ -31,34 +31,34 @@
 */
 
 /* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
-/* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
-/* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
-/* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
-/* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
-/* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
-/* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4,
-/* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
-/* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM,
+    /* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
+    /* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2,
+    /* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
+    /* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
+    /* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
+    /* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3,
+    /* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4,
+    /* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
+    /* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM,
diff --git a/third_party/expat/files/lib/winconfig.h b/third_party/expat/files/lib/winconfig.h
index 40a232dd..ce1a4b9 100644
--- a/third_party/expat/files/lib/winconfig.h
+++ b/third_party/expat/files/lib/winconfig.h
@@ -42,20 +42,17 @@
 #include <memory.h>
 #include <string.h>
 
+#if defined(HAVE_EXPAT_CONFIG_H) /* e.g. MinGW */
+#  include <expat_config.h>
+#else /* !defined(HAVE_EXPAT_CONFIG_H) */
 
-#if defined(HAVE_EXPAT_CONFIG_H)  /* e.g. MinGW */
-# include <expat_config.h>
-#else  /* !defined(HAVE_EXPAT_CONFIG_H) */
-
-
-#define XML_NS 1
-#define XML_DTD 1
-#define XML_CONTEXT_BYTES 1024
+#  define XML_NS 1
+#  define XML_DTD 1
+#  define XML_CONTEXT_BYTES 1024
 
 /* we will assume all Windows platforms are little endian */
-#define BYTEORDER 1234
+#  define BYTEORDER 1234
 
 #endif /* !defined(HAVE_EXPAT_CONFIG_H) */
 
-
 #endif /* ndef WINCONFIG_H */
diff --git a/third_party/expat/files/lib/xmlparse.c b/third_party/expat/files/lib/xmlparse.c
index eaefb6f4..08a04c6 100644
--- a/third_party/expat/files/lib/xmlparse.c
+++ b/third_party/expat/files/lib/xmlparse.c
@@ -1,4 +1,4 @@
-/* 19ac4776051591216f1874e34ee99b6a43a3784c8bd7d70efeb9258dd22b906a (2.2.6+)
+/* f2d0ab6d1d4422a08cf1cf3bbdfba96b49dea42fb5ff4615e03a2a25c306e769 (2.2.8+)
                             __  __            _
                          ___\ \/ /_ __   __ _| |_
                         / _ \\  /| '_ \ / _` | __|
@@ -30,33 +30,40 @@
    USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
 
-#if !defined(_GNU_SOURCE)
-# define _GNU_SOURCE 1                  /* syscall prototype */
+#if ! defined(_GNU_SOURCE)
+#  define _GNU_SOURCE 1 /* syscall prototype */
+#endif
+
+#ifdef _WIN32
+/* force stdlib to define rand_s() */
+#  if ! defined(_CRT_RAND_S)
+#    define _CRT_RAND_S
+#  endif
 #endif
 
 #include <stddef.h>
-#include <string.h>                     /* memset(), memcpy() */
+#include <string.h> /* memset(), memcpy() */
 #include <assert.h>
-#include <limits.h>                     /* UINT_MAX */
-#include <stdio.h>                      /* fprintf */
-#include <stdlib.h>                     /* getenv */
+#include <limits.h> /* UINT_MAX */
+#include <stdio.h>  /* fprintf */
+#include <stdlib.h> /* getenv, rand_s */
 
 #ifdef _WIN32
-#define getpid GetCurrentProcessId
+#  define getpid GetCurrentProcessId
 #else
-#include <sys/time.h>                   /* gettimeofday() */
-#include <sys/types.h>                  /* getpid() */
-#include <unistd.h>                     /* getpid() */
-#include <fcntl.h>                      /* O_RDONLY */
-#include <errno.h>
+#  include <sys/time.h>  /* gettimeofday() */
+#  include <sys/types.h> /* getpid() */
+#  include <unistd.h>    /* getpid() */
+#  include <fcntl.h>     /* O_RDONLY */
+#  include <errno.h>
 #endif
 
 #define XML_BUILDING_EXPAT 1
 
 #ifdef _WIN32
-#include "winconfig.h"
+#  include "winconfig.h"
 #elif defined(HAVE_EXPAT_CONFIG_H)
-#include <expat_config.h>
+#  include <expat_config.h>
 #endif /* ndef _WIN32 */
 
 #include "ascii.h"
@@ -64,33 +71,31 @@
 #include "siphash.h"
 
 #if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
-# if defined(HAVE_GETRANDOM)
-#  include <sys/random.h>    /* getrandom */
-# else
-#  include <unistd.h>        /* syscall */
-#  include <sys/syscall.h>   /* SYS_getrandom */
-# endif
-# if ! defined(GRND_NONBLOCK)
-#  define GRND_NONBLOCK  0x0001
-# endif  /* defined(GRND_NONBLOCK) */
-#endif  /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
+#  if defined(HAVE_GETRANDOM)
+#    include <sys/random.h> /* getrandom */
+#  else
+#    include <unistd.h>      /* syscall */
+#    include <sys/syscall.h> /* SYS_getrandom */
+#  endif
+#  if ! defined(GRND_NONBLOCK)
+#    define GRND_NONBLOCK 0x0001
+#  endif /* defined(GRND_NONBLOCK) */
+#endif   /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
 
-#if defined(HAVE_LIBBSD) \
+#if defined(HAVE_LIBBSD)                                                       \
     && (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
-# include <bsd/stdlib.h>
+#  include <bsd/stdlib.h>
 #endif
 
-#if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
-# define LOAD_LIBRARY_SEARCH_SYSTEM32  0x00000800
+#if defined(_WIN32) && ! defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
+#  define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
 #endif
 
-#if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \
-    && !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \
-    && !defined(XML_DEV_URANDOM) \
-    && !defined(_WIN32) \
-    && !defined(XML_POOR_ENTROPY)
-# error  \
-    You do not have support for any sources of high quality entropy \
+#if ! defined(HAVE_GETRANDOM) && ! defined(HAVE_SYSCALL_GETRANDOM)             \
+    && ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)            \
+    && ! defined(XML_DEV_URANDOM) && ! defined(_WIN32)                         \
+    && ! defined(XML_POOR_ENTROPY)
+#  error You do not have support for any sources of high quality entropy \
     enabled.  For end user security, that is probably not what you want. \
     \
     Your options include: \
@@ -101,7 +106,7 @@
       * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
       * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
       * Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \
-      * Windows (RtlGenRandom): _WIN32. \
+      * Windows (rand_s): _WIN32. \
     \
     If insist on not using any of these, bypass this error by defining \
     XML_POOR_ENTROPY; you have been warned. \
@@ -110,56 +115,55 @@
     to the build system, please open a bug.  Thank you!
 #endif
 
-
 #ifdef XML_UNICODE
-#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
-#define XmlConvert XmlUtf16Convert
-#define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
-#define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
-#define XmlEncode XmlUtf16Encode
+#  define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
+#  define XmlConvert XmlUtf16Convert
+#  define XmlGetInternalEncoding XmlGetUtf16InternalEncoding
+#  define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS
+#  define XmlEncode XmlUtf16Encode
 /* Using pointer subtraction to convert to integer type. */
-#define MUST_CONVERT(enc, s) (!(enc)->isUtf16 || (((char *)(s) - (char *)NULL) & 1))
+#  define MUST_CONVERT(enc, s)                                                 \
+    (! (enc)->isUtf16 || (((char *)(s) - (char *)NULL) & 1))
 typedef unsigned short ICHAR;
 #else
-#define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
-#define XmlConvert XmlUtf8Convert
-#define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
-#define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
-#define XmlEncode XmlUtf8Encode
-#define MUST_CONVERT(enc, s) (!(enc)->isUtf8)
+#  define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX
+#  define XmlConvert XmlUtf8Convert
+#  define XmlGetInternalEncoding XmlGetUtf8InternalEncoding
+#  define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS
+#  define XmlEncode XmlUtf8Encode
+#  define MUST_CONVERT(enc, s) (! (enc)->isUtf8)
 typedef char ICHAR;
 #endif
 
-
 #ifndef XML_NS
 
-#define XmlInitEncodingNS XmlInitEncoding
-#define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
-#undef XmlGetInternalEncodingNS
-#define XmlGetInternalEncodingNS XmlGetInternalEncoding
-#define XmlParseXmlDeclNS XmlParseXmlDecl
+#  define XmlInitEncodingNS XmlInitEncoding
+#  define XmlInitUnknownEncodingNS XmlInitUnknownEncoding
+#  undef XmlGetInternalEncodingNS
+#  define XmlGetInternalEncodingNS XmlGetInternalEncoding
+#  define XmlParseXmlDeclNS XmlParseXmlDecl
 
 #endif
 
 #ifdef XML_UNICODE
 
-#ifdef XML_UNICODE_WCHAR_T
-#define XML_T(x) (const wchar_t)x
-#define XML_L(x) L ## x
-#else
-#define XML_T(x) (const unsigned short)x
-#define XML_L(x) x
-#endif
+#  ifdef XML_UNICODE_WCHAR_T
+#    define XML_T(x) (const wchar_t) x
+#    define XML_L(x) L##x
+#  else
+#    define XML_T(x) (const unsigned short)x
+#    define XML_L(x) x
+#  endif
 
 #else
 
-#define XML_T(x) x
-#define XML_L(x) x
+#  define XML_T(x) x
+#  define XML_L(x) x
 
 #endif
 
 /* Round up n to be a multiple of sz, where sz is a power of 2. */
-#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
+#define ROUND_UP(n, sz) (((n) + ((sz)-1)) & ~((sz)-1))
 
 /* Do safe (NULL-aware) pointer arithmetic */
 #define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
@@ -182,11 +186,9 @@
   const XML_Memory_Handling_Suite *mem;
 } HASH_TABLE;
 
-static size_t
-keylen(KEY s);
+static size_t keylen(KEY s);
 
-static void
-copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key);
+static void copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key);
 
 /* For probing (after a collision) we need a step size relative prime
    to the hash table size, which is a power of 2. We use double-hashing,
@@ -196,9 +198,9 @@
    We limit the maximum step size to table->size / 4 (mask >> 2) and make
    it odd, since odd numbers are always relative prime to a power of 2.
 */
-#define SECOND_HASH(hash, mask, power) \
-  ((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2))
-#define PROBE_STEP(hash, mask, power) \
+#define SECOND_HASH(hash, mask, power)                                         \
+  ((((hash) & ~(mask)) >> ((power)-1)) & ((mask) >> 2))
+#define PROBE_STEP(hash, mask, power)                                          \
   ((unsigned char)((SECOND_HASH(hash, mask, power)) | 1))
 
 typedef struct {
@@ -206,7 +208,7 @@
   NAMED **end;
 } HASH_TABLE_ITER;
 
-#define INIT_TAG_BUF_SIZE 32  /* must be a multiple of sizeof(XML_Char) */
+#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */
 #define INIT_DATA_BUF_SIZE 1024
 #define INIT_ATTS_SIZE 16
 #define INIT_ATTS_VERSION 0xFFFFFFFF
@@ -253,20 +255,20 @@
    TAG objects in a free list.
 */
 typedef struct tag {
-  struct tag *parent;           /* parent of this element */
-  const char *rawName;          /* tagName in the original encoding */
+  struct tag *parent;  /* parent of this element */
+  const char *rawName; /* tagName in the original encoding */
   int rawNameLength;
-  TAG_NAME name;                /* tagName in the API encoding */
-  char *buf;                    /* buffer for name components */
-  char *bufEnd;                 /* end of the buffer */
+  TAG_NAME name; /* tagName in the API encoding */
+  char *buf;     /* buffer for name components */
+  char *bufEnd;  /* end of the buffer */
   BINDING *bindings;
 } TAG;
 
 typedef struct {
   const XML_Char *name;
   const XML_Char *textPtr;
-  int textLen;                  /* length in XML_Chars */
-  int processed;                /* # of processed bytes - when suspended */
+  int textLen;   /* length in XML_Chars */
+  int processed; /* # of processed bytes - when suspended */
   const XML_Char *systemId;
   const XML_Char *base;
   const XML_Char *publicId;
@@ -277,13 +279,13 @@
 } ENTITY;
 
 typedef struct {
-  enum XML_Content_Type         type;
-  enum XML_Content_Quant        quant;
-  const XML_Char *              name;
-  int                           firstchild;
-  int                           lastchild;
-  int                           childcnt;
-  int                           nextsib;
+  enum XML_Content_Type type;
+  enum XML_Content_Quant quant;
+  const XML_Char *name;
+  int firstchild;
+  int lastchild;
+  int childcnt;
+  int nextsib;
 } CONTENT_SCAFFOLD;
 
 #define INIT_SCAFFOLD_ELEMENTS 32
@@ -371,10 +373,8 @@
   XML_Bool betweenDecl; /* WFC: PE Between Declarations */
 } OPEN_INTERNAL_ENTITY;
 
-typedef enum XML_Error PTRCALL Processor(XML_Parser parser,
-                                         const char *start,
-                                         const char *end,
-                                         const char **endPtr);
+typedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,
+                                         const char *end, const char **endPtr);
 
 static Processor prologProcessor;
 static Processor prologInitProcessor;
@@ -395,118 +395,101 @@
 static Processor externalEntityContentProcessor;
 static Processor internalEntityProcessor;
 
-static enum XML_Error
-handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName);
-static enum XML_Error
-processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
-               const char *s, const char *next);
-static enum XML_Error
-initializeEncoding(XML_Parser parser);
-static enum XML_Error
-doProlog(XML_Parser parser, const ENCODING *enc, const char *s,
-         const char *end, int tok, const char *next, const char **nextPtr,
-         XML_Bool haveMore);
-static enum XML_Error
-processInternalEntity(XML_Parser parser, ENTITY *entity,
-                      XML_Bool betweenDecl);
-static enum XML_Error
-doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
-          const char *start, const char *end, const char **endPtr,
-          XML_Bool haveMore);
-static enum XML_Error
-doCdataSection(XML_Parser parser, const ENCODING *, const char **startPtr,
-               const char *end, const char **nextPtr, XML_Bool haveMore);
+static enum XML_Error handleUnknownEncoding(XML_Parser parser,
+                                            const XML_Char *encodingName);
+static enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
+                                     const char *s, const char *next);
+static enum XML_Error initializeEncoding(XML_Parser parser);
+static enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,
+                               const char *s, const char *end, int tok,
+                               const char *next, const char **nextPtr,
+                               XML_Bool haveMore, XML_Bool allowClosingDoctype);
+static enum XML_Error processInternalEntity(XML_Parser parser, ENTITY *entity,
+                                            XML_Bool betweenDecl);
+static enum XML_Error doContent(XML_Parser parser, int startTagLevel,
+                                const ENCODING *enc, const char *start,
+                                const char *end, const char **endPtr,
+                                XML_Bool haveMore);
+static enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *,
+                                     const char **startPtr, const char *end,
+                                     const char **nextPtr, XML_Bool haveMore);
 #ifdef XML_DTD
-static enum XML_Error
-doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr,
-                const char *end, const char **nextPtr, XML_Bool haveMore);
+static enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *,
+                                      const char **startPtr, const char *end,
+                                      const char **nextPtr, XML_Bool haveMore);
 #endif /* XML_DTD */
 
-static void
-freeBindings(XML_Parser parser, BINDING *bindings);
-static enum XML_Error
-storeAtts(XML_Parser parser, const ENCODING *, const char *s,
-          TAG_NAME *tagNamePtr, BINDING **bindingsPtr);
-static enum XML_Error
-addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
-           const XML_Char *uri, BINDING **bindingsPtr);
-static int
-defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata,
-                XML_Bool isId, const XML_Char *dfltValue, XML_Parser parser);
-static enum XML_Error
-storeAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
-                    const char *, const char *, STRING_POOL *);
-static enum XML_Error
-appendAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata,
-                     const char *, const char *, STRING_POOL *);
-static ATTRIBUTE_ID *
-getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
-               const char *end);
-static int
-setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *);
-static enum XML_Error
-storeEntityValue(XML_Parser parser, const ENCODING *enc, const char *start,
-                 const char *end);
-static int
-reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
-                            const char *start, const char *end);
-static int
-reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
-              const char *end);
-static void
-reportDefault(XML_Parser parser, const ENCODING *enc, const char *start,
-              const char *end);
+static void freeBindings(XML_Parser parser, BINDING *bindings);
+static enum XML_Error storeAtts(XML_Parser parser, const ENCODING *,
+                                const char *s, TAG_NAME *tagNamePtr,
+                                BINDING **bindingsPtr);
+static enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,
+                                 const ATTRIBUTE_ID *attId, const XML_Char *uri,
+                                 BINDING **bindingsPtr);
+static int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata,
+                           XML_Bool isId, const XML_Char *dfltValue,
+                           XML_Parser parser);
+static enum XML_Error storeAttributeValue(XML_Parser parser, const ENCODING *,
+                                          XML_Bool isCdata, const char *,
+                                          const char *, STRING_POOL *);
+static enum XML_Error appendAttributeValue(XML_Parser parser, const ENCODING *,
+                                           XML_Bool isCdata, const char *,
+                                           const char *, STRING_POOL *);
+static ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,
+                                    const char *start, const char *end);
+static int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *);
+static enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,
+                                       const char *start, const char *end);
+static int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
+                                       const char *start, const char *end);
+static int reportComment(XML_Parser parser, const ENCODING *enc,
+                         const char *start, const char *end);
+static void reportDefault(XML_Parser parser, const ENCODING *enc,
+                          const char *start, const char *end);
 
-static const XML_Char * getContext(XML_Parser parser);
-static XML_Bool
-setContext(XML_Parser parser, const XML_Char *context);
+static const XML_Char *getContext(XML_Parser parser);
+static XML_Bool setContext(XML_Parser parser, const XML_Char *context);
 
 static void FASTCALL normalizePublicId(XML_Char *s);
 
-static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms);
+static DTD *dtdCreate(const XML_Memory_Handling_Suite *ms);
 /* do not call if m_parentParser != NULL */
 static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
-static void
-dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms);
-static int
-dtdCopy(XML_Parser oldParser,
-        DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms);
-static int
-copyEntityTable(XML_Parser oldParser,
-                HASH_TABLE *, STRING_POOL *, const HASH_TABLE *);
-static NAMED *
-lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize);
-static void FASTCALL
-hashTableInit(HASH_TABLE *, const XML_Memory_Handling_Suite *ms);
+static void dtdDestroy(DTD *p, XML_Bool isDocEntity,
+                       const XML_Memory_Handling_Suite *ms);
+static int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
+                   const XML_Memory_Handling_Suite *ms);
+static int copyEntityTable(XML_Parser oldParser, HASH_TABLE *, STRING_POOL *,
+                           const HASH_TABLE *);
+static NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,
+                     size_t createSize);
+static void FASTCALL hashTableInit(HASH_TABLE *,
+                                   const XML_Memory_Handling_Suite *ms);
 static void FASTCALL hashTableClear(HASH_TABLE *);
 static void FASTCALL hashTableDestroy(HASH_TABLE *);
-static void FASTCALL
-hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *);
-static NAMED * FASTCALL hashTableIterNext(HASH_TABLE_ITER *);
+static void FASTCALL hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *);
+static NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *);
 
-static void FASTCALL
-poolInit(STRING_POOL *, const XML_Memory_Handling_Suite *ms);
+static void FASTCALL poolInit(STRING_POOL *,
+                              const XML_Memory_Handling_Suite *ms);
 static void FASTCALL poolClear(STRING_POOL *);
 static void FASTCALL poolDestroy(STRING_POOL *);
-static XML_Char *
-poolAppend(STRING_POOL *pool, const ENCODING *enc,
-           const char *ptr, const char *end);
-static XML_Char *
-poolStoreString(STRING_POOL *pool, const ENCODING *enc,
-                const char *ptr, const char *end);
+static XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,
+                            const char *ptr, const char *end);
+static XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,
+                                 const char *ptr, const char *end);
 static XML_Bool FASTCALL poolGrow(STRING_POOL *pool);
-static const XML_Char * FASTCALL
-poolCopyString(STRING_POOL *pool, const XML_Char *s);
-static const XML_Char *
-poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n);
-static const XML_Char * FASTCALL
-poolAppendString(STRING_POOL *pool, const XML_Char *s);
+static const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,
+                                               const XML_Char *s);
+static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,
+                                       int n);
+static const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,
+                                                 const XML_Char *s);
 
 static int FASTCALL nextScaffoldPart(XML_Parser parser);
-static XML_Content * build_model(XML_Parser parser);
-static ELEMENT_TYPE *
-getElementType(XML_Parser parser, const ENCODING *enc,
-               const char *ptr, const char *end);
+static XML_Content *build_model(XML_Parser parser);
+static ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,
+                                    const char *ptr, const char *end);
 
 static XML_Char *copyString(const XML_Char *s,
                             const XML_Memory_Handling_Suite *memsuite);
@@ -514,14 +497,11 @@
 static unsigned long generate_hash_secret_salt(XML_Parser parser);
 static XML_Bool startParsing(XML_Parser parser);
 
-static XML_Parser
-parserCreate(const XML_Char *encodingName,
-             const XML_Memory_Handling_Suite *memsuite,
-             const XML_Char *nameSep,
-             DTD *dtd);
+static XML_Parser parserCreate(const XML_Char *encodingName,
+                               const XML_Memory_Handling_Suite *memsuite,
+                               const XML_Char *nameSep, DTD *dtd);
 
-static void
-parserInit(XML_Parser parser, const XML_Char *encodingName);
+static void parserInit(XML_Parser parser, const XML_Char *encodingName);
 
 #define poolStart(pool) ((pool)->start)
 #define poolEnd(pool) ((pool)->ptr)
@@ -530,10 +510,10 @@
 #define poolLastChar(pool) (((pool)->ptr)[-1])
 #define poolDiscard(pool) ((pool)->ptr = (pool)->start)
 #define poolFinish(pool) ((pool)->start = (pool)->ptr)
-#define poolAppendChar(pool, c) \
-  (((pool)->ptr == (pool)->end && !poolGrow(pool)) \
-   ? 0 \
-   : ((*((pool)->ptr)++ = c), 1))
+#define poolAppendChar(pool, c)                                                \
+  (((pool)->ptr == (pool)->end && ! poolGrow(pool))                            \
+       ? 0                                                                     \
+       : ((*((pool)->ptr)++ = c), 1))
 
 struct XML_ParserStruct {
   /* The first member must be m_userData so that the XML_GetUserData
@@ -584,7 +564,7 @@
   void *m_unknownEncodingMem;
   void *m_unknownEncodingData;
   void *m_unknownEncodingHandlerData;
-  void (XMLCALL *m_unknownEncodingRelease)(void *);
+  void(XMLCALL *m_unknownEncodingRelease)(void *);
   PROLOG_STATE m_prologState;
   Processor *m_processor;
   enum XML_Error m_errorCode;
@@ -638,57 +618,55 @@
   unsigned long m_hash_secret_salt;
 };
 
-#define MALLOC(parser, s)      (parser->m_mem.malloc_fcn((s)))
-#define REALLOC(parser, p, s)  (parser->m_mem.realloc_fcn((p),(s)))
-#define FREE(parser, p)        (parser->m_mem.free_fcn((p)))
-
+#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
+#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))
+#define FREE(parser, p) (parser->m_mem.free_fcn((p)))
 
 XML_Parser XMLCALL
-XML_ParserCreate(const XML_Char *encodingName)
-{
+XML_ParserCreate(const XML_Char *encodingName) {
   return XML_ParserCreate_MM(encodingName, NULL, NULL);
 }
 
 XML_Parser XMLCALL
-XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep)
-{
+XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {
   XML_Char tmp[2];
   *tmp = nsSep;
   return XML_ParserCreate_MM(encodingName, NULL, tmp);
 }
 
-static const XML_Char implicitContext[] = {
-  ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h, ASCII_t, ASCII_t, ASCII_p,
-  ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,
-  ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g,
-  ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9,
-  ASCII_9, ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,
-  ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0'
-};
-
+static const XML_Char implicitContext[]
+    = {ASCII_x,     ASCII_m,     ASCII_l,      ASCII_EQUALS, ASCII_h,
+       ASCII_t,     ASCII_t,     ASCII_p,      ASCII_COLON,  ASCII_SLASH,
+       ASCII_SLASH, ASCII_w,     ASCII_w,      ASCII_w,      ASCII_PERIOD,
+       ASCII_w,     ASCII_3,     ASCII_PERIOD, ASCII_o,      ASCII_r,
+       ASCII_g,     ASCII_SLASH, ASCII_X,      ASCII_M,      ASCII_L,
+       ASCII_SLASH, ASCII_1,     ASCII_9,      ASCII_9,      ASCII_8,
+       ASCII_SLASH, ASCII_n,     ASCII_a,      ASCII_m,      ASCII_e,
+       ASCII_s,     ASCII_p,     ASCII_a,      ASCII_c,      ASCII_e,
+       '\0'};
 
 /* To avoid warnings about unused functions: */
 #if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
 
-#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
+#  if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
 
 /* Obtain entropy on Linux 3.17+ */
 static int
-writeRandomBytes_getrandom_nonblock(void * target, size_t count) {
-  int success = 0;  /* full count bytes written? */
+writeRandomBytes_getrandom_nonblock(void *target, size_t count) {
+  int success = 0; /* full count bytes written? */
   size_t bytesWrittenTotal = 0;
   const unsigned int getrandomFlags = GRND_NONBLOCK;
 
   do {
-    void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
+    void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
     const size_t bytesToWrite = count - bytesWrittenTotal;
 
     const int bytesWrittenMore =
-#if defined(HAVE_GETRANDOM)
+#    if defined(HAVE_GETRANDOM)
         getrandom(currentTarget, bytesToWrite, getrandomFlags);
-#else
+#    else
         syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags);
-#endif
+#    endif
 
     if (bytesWrittenMore > 0) {
       bytesWrittenTotal += bytesWrittenMore;
@@ -700,15 +678,14 @@
   return success;
 }
 
-#endif  /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
+#  endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
 
-
-#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
+#  if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
 
 /* Extract entropy from /dev/urandom */
 static int
-writeRandomBytes_dev_urandom(void * target, size_t count) {
-  int success = 0;  /* full count bytes written? */
+writeRandomBytes_dev_urandom(void *target, size_t count) {
+  int success = 0; /* full count bytes written? */
   size_t bytesWrittenTotal = 0;
 
   const int fd = open("/dev/urandom", O_RDONLY);
@@ -717,7 +694,7 @@
   }
 
   do {
-    void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
+    void *const currentTarget = (void *)((char *)target + bytesWrittenTotal);
     const size_t bytesToWrite = count - bytesWrittenTotal;
 
     const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
@@ -733,15 +710,14 @@
   return success;
 }
 
-#endif  /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
+#  endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
 
-#endif  /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
+#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
 
-
-#if defined(HAVE_ARC4RANDOM)
+#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
 
 static void
-writeRandomBytes_arc4random(void * target, size_t count) {
+writeRandomBytes_arc4random(void *target, size_t count) {
   size_t bytesWrittenTotal = 0;
 
   while (bytesWrittenTotal < count) {
@@ -749,93 +725,82 @@
     size_t i = 0;
 
     for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
-        i++, bytesWrittenTotal++) {
+         i++, bytesWrittenTotal++) {
       const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
       ((uint8_t *)target)[bytesWrittenTotal] = random8;
     }
   }
 }
 
-#endif  /* defined(HAVE_ARC4RANDOM) */
-
+#endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
 
 #ifdef _WIN32
 
-typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG);
-HMODULE _Expat_LoadLibrary(LPCTSTR filename);  /* see loadlibrary.c */
-
-/* Obtain entropy on Windows XP / Windows Server 2003 and later.
- * Hint on RtlGenRandom and the following article from libsodium.
- *
- * Michael Howard: Cryptographically Secure Random number on Windows without using CryptoAPI
- * https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/
+/* Obtain entropy on Windows using the rand_s() function which
+ * generates cryptographically secure random numbers.  Internally it
+ * uses RtlGenRandom API which is present in Windows XP and later.
  */
 static int
-writeRandomBytes_RtlGenRandom(void * target, size_t count) {
-  int success = 0;  /* full count bytes written? */
-  const HMODULE advapi32 = _Expat_LoadLibrary(TEXT("ADVAPI32.DLL"));
+writeRandomBytes_rand_s(void *target, size_t count) {
+  size_t bytesWrittenTotal = 0;
 
-  if (advapi32) {
-    const RTLGENRANDOM_FUNC RtlGenRandom
-        = (RTLGENRANDOM_FUNC)GetProcAddress(advapi32, "SystemFunction036");
-    if (RtlGenRandom) {
-      if (RtlGenRandom((PVOID)target, (ULONG)count) == TRUE) {
-        success = 1;
-      }
+  while (bytesWrittenTotal < count) {
+    unsigned int random32 = 0;
+    size_t i = 0;
+
+    if (rand_s(&random32))
+      return 0; /* failure */
+
+    for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
+         i++, bytesWrittenTotal++) {
+      const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
+      ((uint8_t *)target)[bytesWrittenTotal] = random8;
     }
-    FreeLibrary(advapi32);
   }
-
-  return success;
+  return 1; /* success */
 }
 
 #endif /* _WIN32 */
 
-
 #if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
 
 static unsigned long
-gather_time_entropy(void)
-{
-#ifdef _WIN32
+gather_time_entropy(void) {
+#  ifdef _WIN32
   FILETIME ft;
   GetSystemTimeAsFileTime(&ft); /* never fails */
   return ft.dwHighDateTime ^ ft.dwLowDateTime;
-#else
+#  else
   struct timeval tv;
   int gettimeofday_res;
 
   gettimeofday_res = gettimeofday(&tv, NULL);
 
-#if defined(NDEBUG)
+#    if defined(NDEBUG)
   (void)gettimeofday_res;
-#else
-  assert (gettimeofday_res == 0);
-#endif  /* defined(NDEBUG) */
+#    else
+  assert(gettimeofday_res == 0);
+#    endif /* defined(NDEBUG) */
 
   /* Microseconds time is <20 bits entropy */
   return tv.tv_usec;
-#endif
+#  endif
 }
 
-#endif  /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
-
+#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
 
 static unsigned long
-ENTROPY_DEBUG(const char * label, unsigned long entropy) {
-  const char * const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
+ENTROPY_DEBUG(const char *label, unsigned long entropy) {
+  const char *const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
   if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) {
-    fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n",
-        label,
-        (int)sizeof(entropy) * 2, entropy,
-        (unsigned long)sizeof(entropy));
+    fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n", label,
+            (int)sizeof(entropy) * 2, entropy, (unsigned long)sizeof(entropy));
   }
   return entropy;
 }
 
 static unsigned long
-generate_hash_secret_salt(XML_Parser parser)
-{
+generate_hash_secret_salt(XML_Parser parser) {
   unsigned long entropy;
   (void)parser;
 
@@ -848,20 +813,20 @@
   return ENTROPY_DEBUG("arc4random", entropy);
 #else
   /* Try high quality providers first .. */
-#ifdef _WIN32
-  if (writeRandomBytes_RtlGenRandom((void *)&entropy, sizeof(entropy))) {
-    return ENTROPY_DEBUG("RtlGenRandom", entropy);
+#  ifdef _WIN32
+  if (writeRandomBytes_rand_s((void *)&entropy, sizeof(entropy))) {
+    return ENTROPY_DEBUG("rand_s", entropy);
   }
-#elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
+#  elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
   if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
     return ENTROPY_DEBUG("getrandom", entropy);
   }
-#endif
-#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
+#  endif
+#  if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
   if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
     return ENTROPY_DEBUG("/dev/urandom", entropy);
   }
-#endif  /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
+#  endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
   /* .. and self-made low quality for backup: */
 
   /* Process ID is 0 bits entropy if attacker has local access */
@@ -872,7 +837,7 @@
     return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
   } else {
     return ENTROPY_DEBUG("fallback(8)",
-        entropy * (unsigned long)2305843009213693951ULL);
+                         entropy * (unsigned long)2305843009213693951ULL);
   }
 #endif
 }
@@ -884,49 +849,43 @@
   return parser->m_hash_secret_salt;
 }
 
-static XML_Bool  /* only valid for root parser */
-startParsing(XML_Parser parser)
-{
-    /* hash functions must be initialized before setContext() is called */
-    if (parser->m_hash_secret_salt == 0)
-      parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
-    if (parser->m_ns) {
-      /* implicit context only set for root parser, since child
-         parsers (i.e. external entity parsers) will inherit it
-      */
-      return setContext(parser, implicitContext);
-    }
-    return XML_TRUE;
+static XML_Bool /* only valid for root parser */
+startParsing(XML_Parser parser) {
+  /* hash functions must be initialized before setContext() is called */
+  if (parser->m_hash_secret_salt == 0)
+    parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
+  if (parser->m_ns) {
+    /* implicit context only set for root parser, since child
+       parsers (i.e. external entity parsers) will inherit it
+    */
+    return setContext(parser, implicitContext);
+  }
+  return XML_TRUE;
 }
 
 XML_Parser XMLCALL
 XML_ParserCreate_MM(const XML_Char *encodingName,
                     const XML_Memory_Handling_Suite *memsuite,
-                    const XML_Char *nameSep)
-{
+                    const XML_Char *nameSep) {
   return parserCreate(encodingName, memsuite, nameSep, NULL);
 }
 
 static XML_Parser
 parserCreate(const XML_Char *encodingName,
-             const XML_Memory_Handling_Suite *memsuite,
-             const XML_Char *nameSep,
-             DTD *dtd)
-{
+             const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,
+             DTD *dtd) {
   XML_Parser parser;
 
   if (memsuite) {
     XML_Memory_Handling_Suite *mtemp;
-    parser = (XML_Parser)
-      memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
+    parser = (XML_Parser)memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));
     if (parser != NULL) {
       mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);
       mtemp->malloc_fcn = memsuite->malloc_fcn;
       mtemp->realloc_fcn = memsuite->realloc_fcn;
       mtemp->free_fcn = memsuite->free_fcn;
     }
-  }
-  else {
+  } else {
     XML_Memory_Handling_Suite *mtemp;
     parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct));
     if (parser != NULL) {
@@ -937,27 +896,30 @@
     }
   }
 
-  if (!parser)
+  if (! parser)
     return parser;
 
   parser->m_buffer = NULL;
   parser->m_bufferLim = NULL;
 
   parser->m_attsSize = INIT_ATTS_SIZE;
-  parser->m_atts = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
+  parser->m_atts
+      = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
   if (parser->m_atts == NULL) {
     FREE(parser, parser);
     return NULL;
   }
 #ifdef XML_ATTR_INFO
-  parser->m_attInfo = (XML_AttrInfo*)MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));
+  parser->m_attInfo = (XML_AttrInfo *)MALLOC(
+      parser, parser->m_attsSize * sizeof(XML_AttrInfo));
   if (parser->m_attInfo == NULL) {
     FREE(parser, parser->m_atts);
     FREE(parser, parser);
     return NULL;
   }
 #endif
-  parser->m_dataBuf = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
+  parser->m_dataBuf
+      = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
   if (parser->m_dataBuf == NULL) {
     FREE(parser, parser->m_atts);
 #ifdef XML_ATTR_INFO
@@ -1007,7 +969,7 @@
   poolInit(&parser->m_temp2Pool, &(parser->m_mem));
   parserInit(parser, encodingName);
 
-  if (encodingName && !parser->m_protocolEncodingName) {
+  if (encodingName && ! parser->m_protocolEncodingName) {
     XML_ParserFree(parser);
     return NULL;
   }
@@ -1016,8 +978,7 @@
     parser->m_ns = XML_TRUE;
     parser->m_internalEncoding = XmlGetInternalEncodingNS();
     parser->m_namespaceSeparator = *nameSep;
-  }
-  else {
+  } else {
     parser->m_internalEncoding = XmlGetInternalEncoding();
   }
 
@@ -1025,8 +986,7 @@
 }
 
 static void
-parserInit(XML_Parser parser, const XML_Char *encodingName)
-{
+parserInit(XML_Parser parser, const XML_Char *encodingName) {
   parser->m_processor = prologInitProcessor;
   XmlPrologStateInit(&parser->m_prologState);
   if (encodingName != NULL) {
@@ -1099,8 +1059,7 @@
 
 /* moves list of bindings to m_freeBindingList */
 static void FASTCALL
-moveToFreeBindingList(XML_Parser parser, BINDING *bindings)
-{
+moveToFreeBindingList(XML_Parser parser, BINDING *bindings) {
   while (bindings) {
     BINDING *b = bindings;
     bindings = bindings->nextTagBinding;
@@ -1110,13 +1069,12 @@
 }
 
 XML_Bool XMLCALL
-XML_ParserReset(XML_Parser parser, const XML_Char *encodingName)
-{
+XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
   TAG *tStk;
   OPEN_INTERNAL_ENTITY *openEntityList;
 
   if (parser == NULL)
-      return XML_FALSE;
+    return XML_FALSE;
 
   if (parser->m_parentParser)
     return XML_FALSE;
@@ -1152,15 +1110,15 @@
 }
 
 enum XML_Status XMLCALL
-XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName)
-{
+XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {
   if (parser == NULL)
-      return XML_STATUS_ERROR;
+    return XML_STATUS_ERROR;
   /* Block after XML_Parse()/XML_ParseBuffer() has been called.
      XXX There's no way for the caller to determine which of the
      XXX possible error cases caused the XML_STATUS_ERROR return.
   */
-  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
+  if (parser->m_parsingStatus.parsing == XML_PARSING
+      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
     return XML_STATUS_ERROR;
 
   /* Get rid of any previous encoding name */
@@ -1172,17 +1130,15 @@
   else {
     /* Copy the new encoding name into allocated memory */
     parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
-    if (!parser->m_protocolEncodingName)
+    if (! parser->m_protocolEncodingName)
       return XML_STATUS_ERROR;
   }
   return XML_STATUS_OK;
 }
 
 XML_Parser XMLCALL
-XML_ExternalEntityParserCreate(XML_Parser oldParser,
-                               const XML_Char *context,
-                               const XML_Char *encodingName)
-{
+XML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,
+                               const XML_Char *encodingName) {
   XML_Parser parser = oldParser;
   DTD *newDtd = NULL;
   DTD *oldDtd;
@@ -1206,7 +1162,7 @@
   XML_AttlistDeclHandler oldAttlistDeclHandler;
   XML_EntityDeclHandler oldEntityDeclHandler;
   XML_XmlDeclHandler oldXmlDeclHandler;
-  ELEMENT_TYPE * oldDeclElementType;
+  ELEMENT_TYPE *oldDeclElementType;
 
   void *oldUserData;
   void *oldHandlerArg;
@@ -1269,7 +1225,7 @@
   oldhash_secret_salt = parser->m_hash_secret_salt;
 
 #ifdef XML_DTD
-  if (!context)
+  if (! context)
     newDtd = oldDtd;
 #endif /* XML_DTD */
 
@@ -1282,12 +1238,11 @@
     XML_Char tmp[2];
     *tmp = parser->m_namespaceSeparator;
     parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
-  }
-  else {
+  } else {
     parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd);
   }
 
-  if (!parser)
+  if (! parser)
     return NULL;
 
   parser->m_startElementHandler = oldStartElementHandler;
@@ -1327,21 +1282,20 @@
   parser->m_prologState.inEntityValue = oldInEntityValue;
   if (context) {
 #endif /* XML_DTD */
-    if (!dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
-      || !setContext(parser, context)) {
+    if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
+        || ! setContext(parser, context)) {
       XML_ParserFree(parser);
       return NULL;
     }
     parser->m_processor = externalEntityInitProcessor;
 #ifdef XML_DTD
-  }
-  else {
-    /* The DTD instance referenced by parser->m_dtd is shared between the document's
-       root parser and external PE parsers, therefore one does not need to
-       call setContext. In addition, one also *must* not call setContext,
-       because this would overwrite existing prefix->binding pointers in
-       parser->m_dtd with ones that get destroyed with the external PE parser.
-       This would leave those prefixes with dangling pointers.
+  } else {
+    /* The DTD instance referenced by parser->m_dtd is shared between the
+       document's root parser and external PE parsers, therefore one does not
+       need to call setContext. In addition, one also *must* not call
+       setContext, because this would overwrite existing prefix->binding
+       pointers in parser->m_dtd with ones that get destroyed with the external
+       PE parser. This would leave those prefixes with dangling pointers.
     */
     parser->m_isParamEntity = XML_TRUE;
     XmlPrologStateInitExternalEntity(&parser->m_prologState);
@@ -1352,11 +1306,10 @@
 }
 
 static void FASTCALL
-destroyBindings(BINDING *bindings, XML_Parser parser)
-{
+destroyBindings(BINDING *bindings, XML_Parser parser) {
   for (;;) {
     BINDING *b = bindings;
-    if (!b)
+    if (! b)
       break;
     bindings = b->nextTagBinding;
     FREE(parser, b->uri);
@@ -1365,8 +1318,7 @@
 }
 
 void XMLCALL
-XML_ParserFree(XML_Parser parser)
-{
+XML_ParserFree(XML_Parser parser) {
   TAG *tagList;
   OPEN_INTERNAL_ENTITY *entityList;
   if (parser == NULL)
@@ -1411,11 +1363,12 @@
   /* external parameter entity parsers share the DTD structure
      parser->m_dtd with the root parser, so we must not destroy it
   */
-  if (!parser->m_isParamEntity && parser->m_dtd)
+  if (! parser->m_isParamEntity && parser->m_dtd)
 #else
   if (parser->m_dtd)
 #endif /* XML_DTD */
-    dtdDestroy(parser->m_dtd, (XML_Bool)!parser->m_parentParser, &parser->m_mem);
+    dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser,
+               &parser->m_mem);
   FREE(parser, (void *)parser->m_atts);
 #ifdef XML_ATTR_INFO
   FREE(parser, (void *)parser->m_attInfo);
@@ -1431,20 +1384,19 @@
 }
 
 void XMLCALL
-XML_UseParserAsHandlerArg(XML_Parser parser)
-{
+XML_UseParserAsHandlerArg(XML_Parser parser) {
   if (parser != NULL)
     parser->m_handlerArg = parser;
 }
 
 enum XML_Error XMLCALL
-XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD)
-{
+XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {
   if (parser == NULL)
     return XML_ERROR_INVALID_ARGUMENT;
 #ifdef XML_DTD
   /* block after XML_Parse()/XML_ParseBuffer() has been called */
-  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
+  if (parser->m_parsingStatus.parsing == XML_PARSING
+      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
     return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
   parser->m_useForeignDTD = useDTD;
   return XML_ERROR_NONE;
@@ -1454,19 +1406,18 @@
 }
 
 void XMLCALL
-XML_SetReturnNSTriplet(XML_Parser parser, int do_nst)
-{
+XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {
   if (parser == NULL)
     return;
   /* block after XML_Parse()/XML_ParseBuffer() has been called */
-  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
+  if (parser->m_parsingStatus.parsing == XML_PARSING
+      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
     return;
   parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
 }
 
 void XMLCALL
-XML_SetUserData(XML_Parser parser, void *p)
-{
+XML_SetUserData(XML_Parser parser, void *p) {
   if (parser == NULL)
     return;
   if (parser->m_handlerArg == parser->m_userData)
@@ -1476,49 +1427,43 @@
 }
 
 enum XML_Status XMLCALL
-XML_SetBase(XML_Parser parser, const XML_Char *p)
-{
+XML_SetBase(XML_Parser parser, const XML_Char *p) {
   if (parser == NULL)
     return XML_STATUS_ERROR;
   if (p) {
     p = poolCopyString(&parser->m_dtd->pool, p);
-    if (!p)
+    if (! p)
       return XML_STATUS_ERROR;
     parser->m_curBase = p;
-  }
-  else
+  } else
     parser->m_curBase = NULL;
   return XML_STATUS_OK;
 }
 
-const XML_Char * XMLCALL
-XML_GetBase(XML_Parser parser)
-{
+const XML_Char *XMLCALL
+XML_GetBase(XML_Parser parser) {
   if (parser == NULL)
     return NULL;
   return parser->m_curBase;
 }
 
 int XMLCALL
-XML_GetSpecifiedAttributeCount(XML_Parser parser)
-{
+XML_GetSpecifiedAttributeCount(XML_Parser parser) {
   if (parser == NULL)
     return -1;
   return parser->m_nSpecifiedAtts;
 }
 
 int XMLCALL
-XML_GetIdAttributeIndex(XML_Parser parser)
-{
+XML_GetIdAttributeIndex(XML_Parser parser) {
   if (parser == NULL)
     return -1;
   return parser->m_idAttIndex;
 }
 
 #ifdef XML_ATTR_INFO
-const XML_AttrInfo * XMLCALL
-XML_GetAttributeInfo(XML_Parser parser)
-{
+const XML_AttrInfo *XMLCALL
+XML_GetAttributeInfo(XML_Parser parser) {
   if (parser == NULL)
     return NULL;
   return parser->m_attInfo;
@@ -1526,10 +1471,8 @@
 #endif
 
 void XMLCALL
-XML_SetElementHandler(XML_Parser parser,
-                      XML_StartElementHandler start,
-                      XML_EndElementHandler end)
-{
+XML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,
+                      XML_EndElementHandler end) {
   if (parser == NULL)
     return;
   parser->m_startElementHandler = start;
@@ -1537,39 +1480,33 @@
 }
 
 void XMLCALL
-XML_SetStartElementHandler(XML_Parser parser,
-                           XML_StartElementHandler start) {
+XML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {
   if (parser != NULL)
     parser->m_startElementHandler = start;
 }
 
 void XMLCALL
-XML_SetEndElementHandler(XML_Parser parser,
-                         XML_EndElementHandler end) {
+XML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {
   if (parser != NULL)
     parser->m_endElementHandler = end;
 }
 
 void XMLCALL
 XML_SetCharacterDataHandler(XML_Parser parser,
-                            XML_CharacterDataHandler handler)
-{
+                            XML_CharacterDataHandler handler) {
   if (parser != NULL)
     parser->m_characterDataHandler = handler;
 }
 
 void XMLCALL
 XML_SetProcessingInstructionHandler(XML_Parser parser,
-                                    XML_ProcessingInstructionHandler handler)
-{
+                                    XML_ProcessingInstructionHandler handler) {
   if (parser != NULL)
     parser->m_processingInstructionHandler = handler;
 }
 
 void XMLCALL
-XML_SetCommentHandler(XML_Parser parser,
-                      XML_CommentHandler handler)
-{
+XML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {
   if (parser != NULL)
     parser->m_commentHandler = handler;
 }
@@ -1577,8 +1514,7 @@
 void XMLCALL
 XML_SetCdataSectionHandler(XML_Parser parser,
                            XML_StartCdataSectionHandler start,
-                           XML_EndCdataSectionHandler end)
-{
+                           XML_EndCdataSectionHandler end) {
   if (parser == NULL)
     return;
   parser->m_startCdataSectionHandler = start;
@@ -1600,9 +1536,7 @@
 }
 
 void XMLCALL
-XML_SetDefaultHandler(XML_Parser parser,
-                      XML_DefaultHandler handler)
-{
+XML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {
   if (parser == NULL)
     return;
   parser->m_defaultHandler = handler;
@@ -1610,9 +1544,7 @@
 }
 
 void XMLCALL
-XML_SetDefaultHandlerExpand(XML_Parser parser,
-                            XML_DefaultHandler handler)
-{
+XML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {
   if (parser == NULL)
     return;
   parser->m_defaultHandler = handler;
@@ -1620,10 +1552,8 @@
 }
 
 void XMLCALL
-XML_SetDoctypeDeclHandler(XML_Parser parser,
-                          XML_StartDoctypeDeclHandler start,
-                          XML_EndDoctypeDeclHandler end)
-{
+XML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,
+                          XML_EndDoctypeDeclHandler end) {
   if (parser == NULL)
     return;
   parser->m_startDoctypeDeclHandler = start;
@@ -1638,24 +1568,20 @@
 }
 
 void XMLCALL
-XML_SetEndDoctypeDeclHandler(XML_Parser parser,
-                             XML_EndDoctypeDeclHandler end) {
+XML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {
   if (parser != NULL)
     parser->m_endDoctypeDeclHandler = end;
 }
 
 void XMLCALL
 XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
-                                 XML_UnparsedEntityDeclHandler handler)
-{
+                                 XML_UnparsedEntityDeclHandler handler) {
   if (parser != NULL)
     parser->m_unparsedEntityDeclHandler = handler;
 }
 
 void XMLCALL
-XML_SetNotationDeclHandler(XML_Parser parser,
-                           XML_NotationDeclHandler handler)
-{
+XML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {
   if (parser != NULL)
     parser->m_notationDeclHandler = handler;
 }
@@ -1663,8 +1589,7 @@
 void XMLCALL
 XML_SetNamespaceDeclHandler(XML_Parser parser,
                             XML_StartNamespaceDeclHandler start,
-                            XML_EndNamespaceDeclHandler end)
-{
+                            XML_EndNamespaceDeclHandler end) {
   if (parser == NULL)
     return;
   parser->m_startNamespaceDeclHandler = start;
@@ -1687,23 +1612,20 @@
 
 void XMLCALL
 XML_SetNotStandaloneHandler(XML_Parser parser,
-                            XML_NotStandaloneHandler handler)
-{
+                            XML_NotStandaloneHandler handler) {
   if (parser != NULL)
     parser->m_notStandaloneHandler = handler;
 }
 
 void XMLCALL
 XML_SetExternalEntityRefHandler(XML_Parser parser,
-                                XML_ExternalEntityRefHandler handler)
-{
+                                XML_ExternalEntityRefHandler handler) {
   if (parser != NULL)
     parser->m_externalEntityRefHandler = handler;
 }
 
 void XMLCALL
-XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg)
-{
+XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {
   if (parser == NULL)
     return;
   if (arg)
@@ -1714,17 +1636,14 @@
 
 void XMLCALL
 XML_SetSkippedEntityHandler(XML_Parser parser,
-                            XML_SkippedEntityHandler handler)
-{
+                            XML_SkippedEntityHandler handler) {
   if (parser != NULL)
     parser->m_skippedEntityHandler = handler;
 }
 
 void XMLCALL
 XML_SetUnknownEncodingHandler(XML_Parser parser,
-                              XML_UnknownEncodingHandler handler,
-                              void *data)
-{
+                              XML_UnknownEncodingHandler handler, void *data) {
   if (parser == NULL)
     return;
   parser->m_unknownEncodingHandler = handler;
@@ -1732,44 +1651,37 @@
 }
 
 void XMLCALL
-XML_SetElementDeclHandler(XML_Parser parser,
-                          XML_ElementDeclHandler eldecl)
-{
+XML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {
   if (parser != NULL)
     parser->m_elementDeclHandler = eldecl;
 }
 
 void XMLCALL
-XML_SetAttlistDeclHandler(XML_Parser parser,
-                          XML_AttlistDeclHandler attdecl)
-{
+XML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {
   if (parser != NULL)
     parser->m_attlistDeclHandler = attdecl;
 }
 
 void XMLCALL
-XML_SetEntityDeclHandler(XML_Parser parser,
-                         XML_EntityDeclHandler handler)
-{
+XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {
   if (parser != NULL)
     parser->m_entityDeclHandler = handler;
 }
 
 void XMLCALL
-XML_SetXmlDeclHandler(XML_Parser parser,
-                      XML_XmlDeclHandler handler) {
+XML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {
   if (parser != NULL)
     parser->m_xmlDeclHandler = handler;
 }
 
 int XMLCALL
 XML_SetParamEntityParsing(XML_Parser parser,
-                          enum XML_ParamEntityParsing peParsing)
-{
+                          enum XML_ParamEntityParsing peParsing) {
   if (parser == NULL)
     return 0;
   /* block after XML_Parse()/XML_ParseBuffer() has been called */
-  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
+  if (parser->m_parsingStatus.parsing == XML_PARSING
+      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
     return 0;
 #ifdef XML_DTD
   parser->m_paramEntityParsing = peParsing;
@@ -1780,23 +1692,21 @@
 }
 
 int XMLCALL
-XML_SetHashSalt(XML_Parser parser,
-                unsigned long hash_salt)
-{
+XML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {
   if (parser == NULL)
     return 0;
   if (parser->m_parentParser)
     return XML_SetHashSalt(parser->m_parentParser, hash_salt);
   /* block after XML_Parse()/XML_ParseBuffer() has been called */
-  if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
+  if (parser->m_parsingStatus.parsing == XML_PARSING
+      || parser->m_parsingStatus.parsing == XML_SUSPENDED)
     return 0;
   parser->m_hash_secret_salt = hash_salt;
   return 1;
 }
 
 enum XML_Status XMLCALL
-XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
-{
+XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {
   if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
     if (parser != NULL)
       parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
@@ -1810,7 +1720,7 @@
     parser->m_errorCode = XML_ERROR_FINISHED;
     return XML_STATUS_ERROR;
   case XML_INITIALIZED:
-    if (parser->m_parentParser == NULL && !startParsing(parser)) {
+    if (parser->m_parentParser == NULL && ! startParsing(parser)) {
       parser->m_errorCode = XML_ERROR_NO_MEMORY;
       return XML_STATUS_ERROR;
     }
@@ -1821,7 +1731,7 @@
 
   if (len == 0) {
     parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
-    if (!isFinal)
+    if (! isFinal)
       return XML_STATUS_OK;
     parser->m_positionPtr = parser->m_bufferPtr;
     parser->m_parseEndPtr = parser->m_bufferEnd;
@@ -1830,7 +1740,9 @@
        data are the final chunk of input, then we have to check them again
        to detect errors based on that fact.
     */
-    parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
+    parser->m_errorCode
+        = parser->m_processor(parser, parser->m_bufferPtr,
+                              parser->m_parseEndPtr, &parser->m_bufferPtr);
 
     if (parser->m_errorCode == XML_ERROR_NONE) {
       switch (parser->m_parsingStatus.parsing) {
@@ -1847,7 +1759,8 @@
          *
          * LCOV_EXCL_START
          */
-        XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
+        XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
+                          parser->m_bufferPtr, &parser->m_position);
         parser->m_positionPtr = parser->m_bufferPtr;
         return XML_STATUS_SUSPENDED;
         /* LCOV_EXCL_STOP */
@@ -1870,23 +1783,23 @@
     enum XML_Status result;
     /* Detect overflow (a+b > MAX <==> b > MAX-a) */
     if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
-       parser->m_errorCode = XML_ERROR_NO_MEMORY;
-       parser->m_eventPtr = parser->m_eventEndPtr = NULL;
-       parser->m_processor = errorProcessor;
-       return XML_STATUS_ERROR;
+      parser->m_errorCode = XML_ERROR_NO_MEMORY;
+      parser->m_eventPtr = parser->m_eventEndPtr = NULL;
+      parser->m_processor = errorProcessor;
+      return XML_STATUS_ERROR;
     }
     parser->m_parseEndByteIndex += len;
     parser->m_positionPtr = s;
     parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
 
-    parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
+    parser->m_errorCode
+        = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
 
     if (parser->m_errorCode != XML_ERROR_NONE) {
       parser->m_eventEndPtr = parser->m_eventPtr;
       parser->m_processor = errorProcessor;
       return XML_STATUS_ERROR;
-    }
-    else {
+    } else {
       switch (parser->m_parsingStatus.parsing) {
       case XML_SUSPENDED:
         result = XML_STATUS_SUSPENDED;
@@ -1903,10 +1816,12 @@
       }
     }
 
-    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position);
+    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,
+                      &parser->m_position);
     nLeftOver = s + len - end;
     if (nLeftOver) {
-      if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) {
+      if (parser->m_buffer == NULL
+          || nLeftOver > parser->m_bufferLim - parser->m_buffer) {
         /* avoid _signed_ integer overflow */
         char *temp = NULL;
         const int bytesToAllocate = (int)((unsigned)len * 2U);
@@ -1932,7 +1847,7 @@
     parser->m_eventEndPtr = parser->m_bufferPtr;
     return result;
   }
-#endif  /* not defined XML_CONTEXT_BYTES */
+#endif /* not defined XML_CONTEXT_BYTES */
   else {
     void *buff = XML_GetBuffer(parser, len);
     if (buff == NULL)
@@ -1945,8 +1860,7 @@
 }
 
 enum XML_Status XMLCALL
-XML_ParseBuffer(XML_Parser parser, int len, int isFinal)
-{
+XML_ParseBuffer(XML_Parser parser, int len, int isFinal) {
   const char *start;
   enum XML_Status result = XML_STATUS_OK;
 
@@ -1960,7 +1874,7 @@
     parser->m_errorCode = XML_ERROR_FINISHED;
     return XML_STATUS_ERROR;
   case XML_INITIALIZED:
-    if (parser->m_parentParser == NULL && !startParsing(parser)) {
+    if (parser->m_parentParser == NULL && ! startParsing(parser)) {
       parser->m_errorCode = XML_ERROR_NO_MEMORY;
       return XML_STATUS_ERROR;
     }
@@ -1976,14 +1890,14 @@
   parser->m_parseEndByteIndex += len;
   parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
 
-  parser->m_errorCode = parser->m_processor(parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
+  parser->m_errorCode = parser->m_processor(
+      parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
 
   if (parser->m_errorCode != XML_ERROR_NONE) {
     parser->m_eventEndPtr = parser->m_eventPtr;
     parser->m_processor = errorProcessor;
     return XML_STATUS_ERROR;
-  }
-  else {
+  } else {
     switch (parser->m_parsingStatus.parsing) {
     case XML_SUSPENDED:
       result = XML_STATUS_SUSPENDED;
@@ -1994,18 +1908,18 @@
         parser->m_parsingStatus.parsing = XML_FINISHED;
         return result;
       }
-    default: ;  /* should not happen */
+    default:; /* should not happen */
     }
   }
 
-  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
+  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
+                    parser->m_bufferPtr, &parser->m_position);
   parser->m_positionPtr = parser->m_bufferPtr;
   return result;
 }
 
-void * XMLCALL
-XML_GetBuffer(XML_Parser parser, int len)
-{
+void *XMLCALL
+XML_GetBuffer(XML_Parser parser, int len) {
   if (parser == NULL)
     return NULL;
   if (len < 0) {
@@ -2019,17 +1933,17 @@
   case XML_FINISHED:
     parser->m_errorCode = XML_ERROR_FINISHED;
     return NULL;
-  default: ;
+  default:;
   }
 
   if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) {
 #ifdef XML_CONTEXT_BYTES
     int keep;
-#endif  /* defined XML_CONTEXT_BYTES */
+#endif /* defined XML_CONTEXT_BYTES */
     /* Do not invoke signed arithmetic overflow: */
-    int neededSize = (int) ((unsigned)len +
-                            (unsigned)EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd,
-                                                          parser->m_bufferPtr));
+    int neededSize = (int)((unsigned)len
+                           + (unsigned)EXPAT_SAFE_PTR_DIFF(
+                               parser->m_bufferEnd, parser->m_bufferPtr));
     if (neededSize < 0) {
       parser->m_errorCode = XML_ERROR_NO_MEMORY;
       return NULL;
@@ -2039,13 +1953,18 @@
     if (keep > XML_CONTEXT_BYTES)
       keep = XML_CONTEXT_BYTES;
     neededSize += keep;
-#endif  /* defined XML_CONTEXT_BYTES */
-    if (neededSize <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
+#endif /* defined XML_CONTEXT_BYTES */
+    if (neededSize
+        <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
 #ifdef XML_CONTEXT_BYTES
       if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
-          int offset = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer) - keep;
-        /* The buffer pointers cannot be NULL here; we have at least some bytes in the buffer */
-        memmove(parser->m_buffer, &parser->m_buffer[offset], parser->m_bufferEnd - parser->m_bufferPtr + keep);
+        int offset
+            = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)
+              - keep;
+        /* The buffer pointers cannot be NULL here; we have at least some bytes
+         * in the buffer */
+        memmove(parser->m_buffer, &parser->m_buffer[offset],
+                parser->m_bufferEnd - parser->m_bufferPtr + keep);
         parser->m_bufferEnd -= offset;
         parser->m_bufferPtr -= offset;
       }
@@ -2053,20 +1972,21 @@
       if (parser->m_buffer && parser->m_bufferPtr) {
         memmove(parser->m_buffer, parser->m_bufferPtr,
                 EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
-        parser->m_bufferEnd = parser->m_buffer +
-            EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
+        parser->m_bufferEnd
+            = parser->m_buffer
+              + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
         parser->m_bufferPtr = parser->m_buffer;
       }
-#endif  /* not defined XML_CONTEXT_BYTES */
-    }
-    else {
+#endif /* not defined XML_CONTEXT_BYTES */
+    } else {
       char *newBuf;
-      int bufferSize = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
+      int bufferSize
+          = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
       if (bufferSize == 0)
         bufferSize = INIT_BUFFER_SIZE;
       do {
         /* Do not invoke signed arithmetic overflow: */
-        bufferSize = (int) (2U * (unsigned) bufferSize);
+        bufferSize = (int)(2U * (unsigned)bufferSize);
       } while (bufferSize < neededSize && bufferSize > 0);
       if (bufferSize <= 0) {
         parser->m_errorCode = XML_ERROR_NO_MEMORY;
@@ -2080,18 +2000,17 @@
       parser->m_bufferLim = newBuf + bufferSize;
 #ifdef XML_CONTEXT_BYTES
       if (parser->m_bufferPtr) {
-        int keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
-        if (keep > XML_CONTEXT_BYTES)
-          keep = XML_CONTEXT_BYTES;
         memcpy(newBuf, &parser->m_bufferPtr[-keep],
-               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep);
+               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
+                   + keep);
         FREE(parser, parser->m_buffer);
         parser->m_buffer = newBuf;
-        parser->m_bufferEnd = parser->m_buffer +
-            EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep;
+        parser->m_bufferEnd
+            = parser->m_buffer
+              + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
+              + keep;
         parser->m_bufferPtr = parser->m_buffer + keep;
-      }
-      else {
+      } else {
         /* This must be a brand new buffer with no data in it yet */
         parser->m_bufferEnd = newBuf;
         parser->m_bufferPtr = parser->m_buffer = newBuf;
@@ -2101,15 +2020,15 @@
         memcpy(newBuf, parser->m_bufferPtr,
                EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
         FREE(parser, parser->m_buffer);
-        parser->m_bufferEnd = newBuf +
-            EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
-      }
-      else {
+        parser->m_bufferEnd
+            = newBuf
+              + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
+      } else {
         /* This must be a brand new buffer with no data in it yet */
         parser->m_bufferEnd = newBuf;
       }
       parser->m_bufferPtr = parser->m_buffer = newBuf;
-#endif  /* not defined XML_CONTEXT_BYTES */
+#endif /* not defined XML_CONTEXT_BYTES */
     }
     parser->m_eventPtr = parser->m_eventEndPtr = NULL;
     parser->m_positionPtr = NULL;
@@ -2118,8 +2037,7 @@
 }
 
 enum XML_Status XMLCALL
-XML_StopParser(XML_Parser parser, XML_Bool resumable)
-{
+XML_StopParser(XML_Parser parser, XML_Bool resumable) {
   if (parser == NULL)
     return XML_STATUS_ERROR;
   switch (parser->m_parsingStatus.parsing) {
@@ -2142,16 +2060,14 @@
       }
 #endif
       parser->m_parsingStatus.parsing = XML_SUSPENDED;
-    }
-    else
+    } else
       parser->m_parsingStatus.parsing = XML_FINISHED;
   }
   return XML_STATUS_OK;
 }
 
 enum XML_Status XMLCALL
-XML_ResumeParser(XML_Parser parser)
-{
+XML_ResumeParser(XML_Parser parser) {
   enum XML_Status result = XML_STATUS_OK;
 
   if (parser == NULL)
@@ -2162,14 +2078,14 @@
   }
   parser->m_parsingStatus.parsing = XML_PARSING;
 
-  parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
+  parser->m_errorCode = parser->m_processor(
+      parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
 
   if (parser->m_errorCode != XML_ERROR_NONE) {
     parser->m_eventEndPtr = parser->m_eventPtr;
     parser->m_processor = errorProcessor;
     return XML_STATUS_ERROR;
-  }
-  else {
+  } else {
     switch (parser->m_parsingStatus.parsing) {
     case XML_SUSPENDED:
       result = XML_STATUS_SUSPENDED;
@@ -2180,18 +2096,18 @@
         parser->m_parsingStatus.parsing = XML_FINISHED;
         return result;
       }
-    default: ;
+    default:;
     }
   }
 
-  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
+  XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
+                    parser->m_bufferPtr, &parser->m_position);
   parser->m_positionPtr = parser->m_bufferPtr;
   return result;
 }
 
 void XMLCALL
-XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status)
-{
+XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {
   if (parser == NULL)
     return;
   assert(status != NULL);
@@ -2199,26 +2115,24 @@
 }
 
 enum XML_Error XMLCALL
-XML_GetErrorCode(XML_Parser parser)
-{
+XML_GetErrorCode(XML_Parser parser) {
   if (parser == NULL)
     return XML_ERROR_INVALID_ARGUMENT;
   return parser->m_errorCode;
 }
 
 XML_Index XMLCALL
-XML_GetCurrentByteIndex(XML_Parser parser)
-{
+XML_GetCurrentByteIndex(XML_Parser parser) {
   if (parser == NULL)
     return -1;
   if (parser->m_eventPtr)
-    return (XML_Index)(parser->m_parseEndByteIndex - (parser->m_parseEndPtr - parser->m_eventPtr));
+    return (XML_Index)(parser->m_parseEndByteIndex
+                       - (parser->m_parseEndPtr - parser->m_eventPtr));
   return -1;
 }
 
 int XMLCALL
-XML_GetCurrentByteCount(XML_Parser parser)
-{
+XML_GetCurrentByteCount(XML_Parser parser) {
   if (parser == NULL)
     return 0;
   if (parser->m_eventEndPtr && parser->m_eventPtr)
@@ -2226,9 +2140,8 @@
   return 0;
 }
 
-const char * XMLCALL
-XML_GetInputContext(XML_Parser parser, int *offset, int *size)
-{
+const char *XMLCALL
+XML_GetInputContext(XML_Parser parser, int *offset, int *size) {
 #ifdef XML_CONTEXT_BYTES
   if (parser == NULL)
     return NULL;
@@ -2236,7 +2149,7 @@
     if (offset != NULL)
       *offset = (int)(parser->m_eventPtr - parser->m_buffer);
     if (size != NULL)
-      *size   = (int)(parser->m_bufferEnd - parser->m_buffer);
+      *size = (int)(parser->m_bufferEnd - parser->m_buffer);
     return parser->m_buffer;
   }
 #else
@@ -2244,82 +2157,76 @@
   (void)offset;
   (void)size;
 #endif /* defined XML_CONTEXT_BYTES */
-  return (char *) 0;
+  return (char *)0;
 }
 
 XML_Size XMLCALL
-XML_GetCurrentLineNumber(XML_Parser parser)
-{
+XML_GetCurrentLineNumber(XML_Parser parser) {
   if (parser == NULL)
     return 0;
   if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
-    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
+    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
+                      parser->m_eventPtr, &parser->m_position);
     parser->m_positionPtr = parser->m_eventPtr;
   }
   return parser->m_position.lineNumber + 1;
 }
 
 XML_Size XMLCALL
-XML_GetCurrentColumnNumber(XML_Parser parser)
-{
+XML_GetCurrentColumnNumber(XML_Parser parser) {
   if (parser == NULL)
     return 0;
   if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
-    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
+    XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,
+                      parser->m_eventPtr, &parser->m_position);
     parser->m_positionPtr = parser->m_eventPtr;
   }
   return parser->m_position.columnNumber;
 }
 
 void XMLCALL
-XML_FreeContentModel(XML_Parser parser, XML_Content *model)
-{
+XML_FreeContentModel(XML_Parser parser, XML_Content *model) {
   if (parser != NULL)
     FREE(parser, model);
 }
 
-void * XMLCALL
-XML_MemMalloc(XML_Parser parser, size_t size)
-{
+void *XMLCALL
+XML_MemMalloc(XML_Parser parser, size_t size) {
   if (parser == NULL)
     return NULL;
   return MALLOC(parser, size);
 }
 
-void * XMLCALL
-XML_MemRealloc(XML_Parser parser, void *ptr, size_t size)
-{
+void *XMLCALL
+XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {
   if (parser == NULL)
     return NULL;
   return REALLOC(parser, ptr, size);
 }
 
 void XMLCALL
-XML_MemFree(XML_Parser parser, void *ptr)
-{
+XML_MemFree(XML_Parser parser, void *ptr) {
   if (parser != NULL)
     FREE(parser, ptr);
 }
 
 void XMLCALL
-XML_DefaultCurrent(XML_Parser parser)
-{
+XML_DefaultCurrent(XML_Parser parser) {
   if (parser == NULL)
     return;
   if (parser->m_defaultHandler) {
     if (parser->m_openInternalEntities)
-      reportDefault(parser,
-                    parser->m_internalEncoding,
+      reportDefault(parser, parser->m_internalEncoding,
                     parser->m_openInternalEntities->internalEventPtr,
                     parser->m_openInternalEntities->internalEventEndPtr);
     else
-      reportDefault(parser, parser->m_encoding, parser->m_eventPtr, parser->m_eventEndPtr);
+      reportDefault(parser, parser->m_encoding, parser->m_eventPtr,
+                    parser->m_eventEndPtr);
   }
 }
 
-const XML_LChar * XMLCALL
-XML_ErrorString(enum XML_Error code)
-{
+const XML_LChar *XMLCALL
+XML_ErrorString(enum XML_Error code) {
   switch (code) {
   case XML_ERROR_NONE:
     return NULL;
@@ -2401,21 +2308,22 @@
     return XML_L("cannot suspend in external parameter entity");
   /* Added in 2.0.0. */
   case XML_ERROR_RESERVED_PREFIX_XML:
-    return XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name");
+    return XML_L(
+        "reserved prefix (xml) must not be undeclared or bound to another namespace name");
   case XML_ERROR_RESERVED_PREFIX_XMLNS:
     return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
   case XML_ERROR_RESERVED_NAMESPACE_URI:
-    return XML_L("prefix must not be bound to one of the reserved namespace names");
+    return XML_L(
+        "prefix must not be bound to one of the reserved namespace names");
   /* Added in 2.2.5. */
-  case XML_ERROR_INVALID_ARGUMENT:  /* Constant added in 2.2.1, already */
+  case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
     return XML_L("invalid argument");
   }
   return NULL;
 }
 
-const XML_LChar * XMLCALL
+const XML_LChar *XMLCALL
 XML_ExpatVersion(void) {
-
   /* V1 is used to string-ize the version number. However, it would
      string-ize the actual version macro *names* unless we get them
      substituted before being passed to V1. CPP is defined to expand
@@ -2424,8 +2332,8 @@
      with the correct numerals. */
   /* ### I'm assuming cpp is portable in this respect... */
 
-#define V1(a,b,c) XML_L(#a)XML_L(".")XML_L(#b)XML_L(".")XML_L(#c)
-#define V2(a,b,c) XML_L("expat_")V1(a,b,c)
+#define V1(a, b, c) XML_L(#a) XML_L(".") XML_L(#b) XML_L(".") XML_L(#c)
+#define V2(a, b, c) XML_L("expat_") V1(a, b, c)
 
   return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);
 
@@ -2434,8 +2342,7 @@
 }
 
 XML_Expat_Version XMLCALL
-XML_ExpatVersionInfo(void)
-{
+XML_ExpatVersionInfo(void) {
   XML_Expat_Version version;
 
   version.major = XML_MAJOR_VERSION;
@@ -2445,41 +2352,39 @@
   return version;
 }
 
-const XML_Feature * XMLCALL
-XML_GetFeatureList(void)
-{
-  static const XML_Feature features[] = {
-    {XML_FEATURE_SIZEOF_XML_CHAR,  XML_L("sizeof(XML_Char)"),
-     sizeof(XML_Char)},
-    {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
-     sizeof(XML_LChar)},
+const XML_Feature *XMLCALL
+XML_GetFeatureList(void) {
+  static const XML_Feature features[]
+      = {{XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"),
+          sizeof(XML_Char)},
+         {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"),
+          sizeof(XML_LChar)},
 #ifdef XML_UNICODE
-    {XML_FEATURE_UNICODE,          XML_L("XML_UNICODE"), 0},
+         {XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0},
 #endif
 #ifdef XML_UNICODE_WCHAR_T
-    {XML_FEATURE_UNICODE_WCHAR_T,  XML_L("XML_UNICODE_WCHAR_T"), 0},
+         {XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0},
 #endif
 #ifdef XML_DTD
-    {XML_FEATURE_DTD,              XML_L("XML_DTD"), 0},
+         {XML_FEATURE_DTD, XML_L("XML_DTD"), 0},
 #endif
 #ifdef XML_CONTEXT_BYTES
-    {XML_FEATURE_CONTEXT_BYTES,    XML_L("XML_CONTEXT_BYTES"),
-     XML_CONTEXT_BYTES},
+         {XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"),
+          XML_CONTEXT_BYTES},
 #endif
 #ifdef XML_MIN_SIZE
-    {XML_FEATURE_MIN_SIZE,         XML_L("XML_MIN_SIZE"), 0},
+         {XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0},
 #endif
 #ifdef XML_NS
-    {XML_FEATURE_NS,               XML_L("XML_NS"), 0},
+         {XML_FEATURE_NS, XML_L("XML_NS"), 0},
 #endif
 #ifdef XML_LARGE_SIZE
-    {XML_FEATURE_LARGE_SIZE,       XML_L("XML_LARGE_SIZE"), 0},
+         {XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0},
 #endif
 #ifdef XML_ATTR_INFO
-    {XML_FEATURE_ATTR_INFO,        XML_L("XML_ATTR_INFO"), 0},
+         {XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0},
 #endif
-    {XML_FEATURE_END,              NULL, 0}
-  };
+         {XML_FEATURE_END, NULL, 0}};
 
   return features;
 }
@@ -2490,8 +2395,7 @@
    permanent location, since the parse buffer is about to be discarded.
 */
 static XML_Bool
-storeRawNames(XML_Parser parser)
-{
+storeRawNames(XML_Parser parser) {
   TAG *tag = parser->m_tagStack;
   while (tag) {
     int bufSize;
@@ -2521,8 +2425,8 @@
          then update it as well, since it will always point into tag->buf
       */
       if (tag->name.localPart)
-        tag->name.localPart = (XML_Char *)temp + (tag->name.localPart -
-                                                  (XML_Char *)tag->buf);
+        tag->name.localPart
+            = (XML_Char *)temp + (tag->name.localPart - (XML_Char *)tag->buf);
       tag->buf = temp;
       tag->bufEnd = temp + bufSize;
       rawNameBuf = temp + nameLen;
@@ -2535,26 +2439,21 @@
 }
 
 static enum XML_Error PTRCALL
-contentProcessor(XML_Parser parser,
-                 const char *start,
-                 const char *end,
-                 const char **endPtr)
-{
-  enum XML_Error result = doContent(parser, 0, parser->m_encoding, start, end,
-                                    endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
+contentProcessor(XML_Parser parser, const char *start, const char *end,
+                 const char **endPtr) {
+  enum XML_Error result
+      = doContent(parser, 0, parser->m_encoding, start, end, endPtr,
+                  (XML_Bool)! parser->m_parsingStatus.finalBuffer);
   if (result == XML_ERROR_NONE) {
-    if (!storeRawNames(parser))
+    if (! storeRawNames(parser))
       return XML_ERROR_NO_MEMORY;
   }
   return result;
 }
 
 static enum XML_Error PTRCALL
-externalEntityInitProcessor(XML_Parser parser,
-                            const char *start,
-                            const char *end,
-                            const char **endPtr)
-{
+externalEntityInitProcessor(XML_Parser parser, const char *start,
+                            const char *end, const char **endPtr) {
   enum XML_Error result = initializeEncoding(parser);
   if (result != XML_ERROR_NONE)
     return result;
@@ -2563,11 +2462,8 @@
 }
 
 static enum XML_Error PTRCALL
-externalEntityInitProcessor2(XML_Parser parser,
-                             const char *start,
-                             const char *end,
-                             const char **endPtr)
-{
+externalEntityInitProcessor2(XML_Parser parser, const char *start,
+                             const char *end, const char **endPtr) {
   const char *next = start; /* XmlContentTok doesn't always set the last arg */
   int tok = XmlContentTok(parser->m_encoding, start, end, &next);
   switch (tok) {
@@ -2577,21 +2473,21 @@
        doContent (by detecting XML_TOK_NONE) without processing any xml text
        declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
     */
-    if (next == end && !parser->m_parsingStatus.finalBuffer) {
+    if (next == end && ! parser->m_parsingStatus.finalBuffer) {
       *endPtr = next;
       return XML_ERROR_NONE;
     }
     start = next;
     break;
   case XML_TOK_PARTIAL:
-    if (!parser->m_parsingStatus.finalBuffer) {
+    if (! parser->m_parsingStatus.finalBuffer) {
       *endPtr = start;
       return XML_ERROR_NONE;
     }
     parser->m_eventPtr = start;
     return XML_ERROR_UNCLOSED_TOKEN;
   case XML_TOK_PARTIAL_CHAR:
-    if (!parser->m_parsingStatus.finalBuffer) {
+    if (! parser->m_parsingStatus.finalBuffer) {
       *endPtr = start;
       return XML_ERROR_NONE;
     }
@@ -2603,11 +2499,8 @@
 }
 
 static enum XML_Error PTRCALL
-externalEntityInitProcessor3(XML_Parser parser,
-                             const char *start,
-                             const char *end,
-                             const char **endPtr)
-{
+externalEntityInitProcessor3(XML_Parser parser, const char *start,
+                             const char *end, const char **endPtr) {
   int tok;
   const char *next = start; /* XmlContentTok doesn't always set the last arg */
   parser->m_eventPtr = start;
@@ -2615,31 +2508,29 @@
   parser->m_eventEndPtr = next;
 
   switch (tok) {
-  case XML_TOK_XML_DECL:
-    {
-      enum XML_Error result;
-      result = processXmlDecl(parser, 1, start, next);
-      if (result != XML_ERROR_NONE)
-        return result;
-      switch (parser->m_parsingStatus.parsing) {
-      case XML_SUSPENDED:
-        *endPtr = next;
-        return XML_ERROR_NONE;
-      case XML_FINISHED:
-        return XML_ERROR_ABORTED;
-      default:
-        start = next;
-      }
+  case XML_TOK_XML_DECL: {
+    enum XML_Error result;
+    result = processXmlDecl(parser, 1, start, next);
+    if (result != XML_ERROR_NONE)
+      return result;
+    switch (parser->m_parsingStatus.parsing) {
+    case XML_SUSPENDED:
+      *endPtr = next;
+      return XML_ERROR_NONE;
+    case XML_FINISHED:
+      return XML_ERROR_ABORTED;
+    default:
+      start = next;
     }
-    break;
+  } break;
   case XML_TOK_PARTIAL:
-    if (!parser->m_parsingStatus.finalBuffer) {
+    if (! parser->m_parsingStatus.finalBuffer) {
       *endPtr = start;
       return XML_ERROR_NONE;
     }
     return XML_ERROR_UNCLOSED_TOKEN;
   case XML_TOK_PARTIAL_CHAR:
-    if (!parser->m_parsingStatus.finalBuffer) {
+    if (! parser->m_parsingStatus.finalBuffer) {
       *endPtr = start;
       return XML_ERROR_NONE;
     }
@@ -2651,39 +2542,31 @@
 }
 
 static enum XML_Error PTRCALL
-externalEntityContentProcessor(XML_Parser parser,
-                               const char *start,
-                               const char *end,
-                               const char **endPtr)
-{
-  enum XML_Error result = doContent(parser, 1, parser->m_encoding, start, end,
-                                    endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
+externalEntityContentProcessor(XML_Parser parser, const char *start,
+                               const char *end, const char **endPtr) {
+  enum XML_Error result
+      = doContent(parser, 1, parser->m_encoding, start, end, endPtr,
+                  (XML_Bool)! parser->m_parsingStatus.finalBuffer);
   if (result == XML_ERROR_NONE) {
-    if (!storeRawNames(parser))
+    if (! storeRawNames(parser))
       return XML_ERROR_NO_MEMORY;
   }
   return result;
 }
 
 static enum XML_Error
-doContent(XML_Parser parser,
-          int startTagLevel,
-          const ENCODING *enc,
-          const char *s,
-          const char *end,
-          const char **nextPtr,
-          XML_Bool haveMore)
-{
+doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
+          const char *s, const char *end, const char **nextPtr,
+          XML_Bool haveMore) {
   /* save one level of indirection */
-  DTD * const dtd = parser->m_dtd;
+  DTD *const dtd = parser->m_dtd;
 
   const char **eventPP;
   const char **eventEndPP;
   if (enc == parser->m_encoding) {
     eventPP = &parser->m_eventPtr;
     eventEndPP = &parser->m_eventEndPtr;
-  }
-  else {
+  } else {
     eventPP = &(parser->m_openInternalEntities->internalEventPtr);
     eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
   }
@@ -2703,8 +2586,7 @@
       if (parser->m_characterDataHandler) {
         XML_Char c = 0xA;
         parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
-      }
-      else if (parser->m_defaultHandler)
+      } else if (parser->m_defaultHandler)
         reportDefault(parser, enc, s, end);
       /* We are at the end of the final buffer, should we check for
          XML_SUSPENDED, XML_FINISHED?
@@ -2742,185 +2624,178 @@
         return XML_ERROR_NONE;
       }
       return XML_ERROR_PARTIAL_CHAR;
-    case XML_TOK_ENTITY_REF:
-      {
-        const XML_Char *name;
-        ENTITY *entity;
-        XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
-                                              s + enc->minBytesPerChar,
-                                              next - enc->minBytesPerChar);
-        if (ch) {
-          if (parser->m_characterDataHandler)
-            parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
-          else if (parser->m_defaultHandler)
-            reportDefault(parser, enc, s, next);
-          break;
-        }
-        name = poolStoreString(&dtd->pool, enc,
-                                s + enc->minBytesPerChar,
-                                next - enc->minBytesPerChar);
-        if (!name)
-          return XML_ERROR_NO_MEMORY;
-        entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
-        poolDiscard(&dtd->pool);
-        /* First, determine if a check for an existing declaration is needed;
-           if yes, check that the entity exists, and that it is internal,
-           otherwise call the skipped entity or default handler.
-        */
-        if (!dtd->hasParamEntityRefs || dtd->standalone) {
-          if (!entity)
-            return XML_ERROR_UNDEFINED_ENTITY;
-          else if (!entity->is_internal)
-            return XML_ERROR_ENTITY_DECLARED_IN_PE;
-        }
-        else if (!entity) {
-          if (parser->m_skippedEntityHandler)
-            parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
-          else if (parser->m_defaultHandler)
-            reportDefault(parser, enc, s, next);
-          break;
-        }
-        if (entity->open)
-          return XML_ERROR_RECURSIVE_ENTITY_REF;
-        if (entity->notation)
-          return XML_ERROR_BINARY_ENTITY_REF;
-        if (entity->textPtr) {
-          enum XML_Error result;
-          if (!parser->m_defaultExpandInternalEntities) {
-            if (parser->m_skippedEntityHandler)
-              parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name, 0);
-            else if (parser->m_defaultHandler)
-              reportDefault(parser, enc, s, next);
-            break;
-          }
-          result = processInternalEntity(parser, entity, XML_FALSE);
-          if (result != XML_ERROR_NONE)
-            return result;
-        }
-        else if (parser->m_externalEntityRefHandler) {
-          const XML_Char *context;
-          entity->open = XML_TRUE;
-          context = getContext(parser);
-          entity->open = XML_FALSE;
-          if (!context)
-            return XML_ERROR_NO_MEMORY;
-          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
-                                        context,
-                                        entity->base,
-                                        entity->systemId,
-                                        entity->publicId))
-            return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
-          poolDiscard(&parser->m_tempPool);
-        }
+    case XML_TOK_ENTITY_REF: {
+      const XML_Char *name;
+      ENTITY *entity;
+      XML_Char ch = (XML_Char)XmlPredefinedEntityName(
+          enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
+      if (ch) {
+        if (parser->m_characterDataHandler)
+          parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
         else if (parser->m_defaultHandler)
           reportDefault(parser, enc, s, next);
         break;
       }
+      name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
+                             next - enc->minBytesPerChar);
+      if (! name)
+        return XML_ERROR_NO_MEMORY;
+      entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
+      poolDiscard(&dtd->pool);
+      /* First, determine if a check for an existing declaration is needed;
+         if yes, check that the entity exists, and that it is internal,
+         otherwise call the skipped entity or default handler.
+      */
+      if (! dtd->hasParamEntityRefs || dtd->standalone) {
+        if (! entity)
+          return XML_ERROR_UNDEFINED_ENTITY;
+        else if (! entity->is_internal)
+          return XML_ERROR_ENTITY_DECLARED_IN_PE;
+      } else if (! entity) {
+        if (parser->m_skippedEntityHandler)
+          parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
+        else if (parser->m_defaultHandler)
+          reportDefault(parser, enc, s, next);
+        break;
+      }
+      if (entity->open)
+        return XML_ERROR_RECURSIVE_ENTITY_REF;
+      if (entity->notation)
+        return XML_ERROR_BINARY_ENTITY_REF;
+      if (entity->textPtr) {
+        enum XML_Error result;
+        if (! parser->m_defaultExpandInternalEntities) {
+          if (parser->m_skippedEntityHandler)
+            parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,
+                                           0);
+          else if (parser->m_defaultHandler)
+            reportDefault(parser, enc, s, next);
+          break;
+        }
+        result = processInternalEntity(parser, entity, XML_FALSE);
+        if (result != XML_ERROR_NONE)
+          return result;
+      } else if (parser->m_externalEntityRefHandler) {
+        const XML_Char *context;
+        entity->open = XML_TRUE;
+        context = getContext(parser);
+        entity->open = XML_FALSE;
+        if (! context)
+          return XML_ERROR_NO_MEMORY;
+        if (! parser->m_externalEntityRefHandler(
+                parser->m_externalEntityRefHandlerArg, context, entity->base,
+                entity->systemId, entity->publicId))
+          return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
+        poolDiscard(&parser->m_tempPool);
+      } else if (parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+      break;
+    }
     case XML_TOK_START_TAG_NO_ATTS:
       /* fall through */
-    case XML_TOK_START_TAG_WITH_ATTS:
-      {
-        TAG *tag;
-        enum XML_Error result;
-        XML_Char *toPtr;
-        if (parser->m_freeTagList) {
-          tag = parser->m_freeTagList;
-          parser->m_freeTagList = parser->m_freeTagList->parent;
+    case XML_TOK_START_TAG_WITH_ATTS: {
+      TAG *tag;
+      enum XML_Error result;
+      XML_Char *toPtr;
+      if (parser->m_freeTagList) {
+        tag = parser->m_freeTagList;
+        parser->m_freeTagList = parser->m_freeTagList->parent;
+      } else {
+        tag = (TAG *)MALLOC(parser, sizeof(TAG));
+        if (! tag)
+          return XML_ERROR_NO_MEMORY;
+        tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
+        if (! tag->buf) {
+          FREE(parser, tag);
+          return XML_ERROR_NO_MEMORY;
         }
-        else {
-          tag = (TAG *)MALLOC(parser, sizeof(TAG));
-          if (!tag)
-            return XML_ERROR_NO_MEMORY;
-          tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
-          if (!tag->buf) {
-            FREE(parser, tag);
-            return XML_ERROR_NO_MEMORY;
-          }
-          tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
-        }
-        tag->bindings = NULL;
-        tag->parent = parser->m_tagStack;
-        parser->m_tagStack = tag;
-        tag->name.localPart = NULL;
-        tag->name.prefix = NULL;
-        tag->rawName = s + enc->minBytesPerChar;
-        tag->rawNameLength = XmlNameLength(enc, tag->rawName);
-        ++parser->m_tagLevel;
-        {
-          const char *rawNameEnd = tag->rawName + tag->rawNameLength;
-          const char *fromPtr = tag->rawName;
-          toPtr = (XML_Char *)tag->buf;
-          for (;;) {
-            int bufSize;
-            int convLen;
-            const enum XML_Convert_Result convert_res = XmlConvert(enc,
-                       &fromPtr, rawNameEnd,
-                       (ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1);
-            convLen = (int)(toPtr - (XML_Char *)tag->buf);
-            if ((fromPtr >= rawNameEnd) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
-              tag->name.strLen = convLen;
-              break;
-            }
-            bufSize = (int)(tag->bufEnd - tag->buf) << 1;
-            {
-              char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
-              if (temp == NULL)
-                return XML_ERROR_NO_MEMORY;
-              tag->buf = temp;
-              tag->bufEnd = temp + bufSize;
-              toPtr = (XML_Char *)temp + convLen;
-            }
-          }
-        }
-        tag->name.str = (XML_Char *)tag->buf;
-        *toPtr = XML_T('\0');
-        result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
-        if (result)
-          return result;
-        if (parser->m_startElementHandler)
-          parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
-                              (const XML_Char **)parser->m_atts);
-        else if (parser->m_defaultHandler)
-          reportDefault(parser, enc, s, next);
-        poolClear(&parser->m_tempPool);
-        break;
+        tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
       }
+      tag->bindings = NULL;
+      tag->parent = parser->m_tagStack;
+      parser->m_tagStack = tag;
+      tag->name.localPart = NULL;
+      tag->name.prefix = NULL;
+      tag->rawName = s + enc->minBytesPerChar;
+      tag->rawNameLength = XmlNameLength(enc, tag->rawName);
+      ++parser->m_tagLevel;
+      {
+        const char *rawNameEnd = tag->rawName + tag->rawNameLength;
+        const char *fromPtr = tag->rawName;
+        toPtr = (XML_Char *)tag->buf;
+        for (;;) {
+          int bufSize;
+          int convLen;
+          const enum XML_Convert_Result convert_res
+              = XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,
+                           (ICHAR *)tag->bufEnd - 1);
+          convLen = (int)(toPtr - (XML_Char *)tag->buf);
+          if ((fromPtr >= rawNameEnd)
+              || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {
+            tag->name.strLen = convLen;
+            break;
+          }
+          bufSize = (int)(tag->bufEnd - tag->buf) << 1;
+          {
+            char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
+            if (temp == NULL)
+              return XML_ERROR_NO_MEMORY;
+            tag->buf = temp;
+            tag->bufEnd = temp + bufSize;
+            toPtr = (XML_Char *)temp + convLen;
+          }
+        }
+      }
+      tag->name.str = (XML_Char *)tag->buf;
+      *toPtr = XML_T('\0');
+      result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
+      if (result)
+        return result;
+      if (parser->m_startElementHandler)
+        parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
+                                      (const XML_Char **)parser->m_atts);
+      else if (parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+      poolClear(&parser->m_tempPool);
+      break;
+    }
     case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
       /* fall through */
-    case XML_TOK_EMPTY_ELEMENT_WITH_ATTS:
-      {
-        const char *rawName = s + enc->minBytesPerChar;
-        enum XML_Error result;
-        BINDING *bindings = NULL;
-        XML_Bool noElmHandlers = XML_TRUE;
-        TAG_NAME name;
-        name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
-                                   rawName + XmlNameLength(enc, rawName));
-        if (!name.str)
-          return XML_ERROR_NO_MEMORY;
-        poolFinish(&parser->m_tempPool);
-        result = storeAtts(parser, enc, s, &name, &bindings);
-        if (result != XML_ERROR_NONE) {
-          freeBindings(parser, bindings);
-          return result;
-        }
-        poolFinish(&parser->m_tempPool);
-        if (parser->m_startElementHandler) {
-          parser->m_startElementHandler(parser->m_handlerArg, name.str, (const XML_Char **)parser->m_atts);
-          noElmHandlers = XML_FALSE;
-        }
-        if (parser->m_endElementHandler) {
-          if (parser->m_startElementHandler)
-            *eventPP = *eventEndPP;
-          parser->m_endElementHandler(parser->m_handlerArg, name.str);
-          noElmHandlers = XML_FALSE;
-        }
-        if (noElmHandlers && parser->m_defaultHandler)
-          reportDefault(parser, enc, s, next);
-        poolClear(&parser->m_tempPool);
+    case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {
+      const char *rawName = s + enc->minBytesPerChar;
+      enum XML_Error result;
+      BINDING *bindings = NULL;
+      XML_Bool noElmHandlers = XML_TRUE;
+      TAG_NAME name;
+      name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
+                                 rawName + XmlNameLength(enc, rawName));
+      if (! name.str)
+        return XML_ERROR_NO_MEMORY;
+      poolFinish(&parser->m_tempPool);
+      result = storeAtts(parser, enc, s, &name, &bindings);
+      if (result != XML_ERROR_NONE) {
         freeBindings(parser, bindings);
+        return result;
       }
-      if ((parser->m_tagLevel == 0) && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
+      poolFinish(&parser->m_tempPool);
+      if (parser->m_startElementHandler) {
+        parser->m_startElementHandler(parser->m_handlerArg, name.str,
+                                      (const XML_Char **)parser->m_atts);
+        noElmHandlers = XML_FALSE;
+      }
+      if (parser->m_endElementHandler) {
+        if (parser->m_startElementHandler)
+          *eventPP = *eventEndPP;
+        parser->m_endElementHandler(parser->m_handlerArg, name.str);
+        noElmHandlers = XML_FALSE;
+      }
+      if (noElmHandlers && parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+      poolClear(&parser->m_tempPool);
+      freeBindings(parser, bindings);
+    }
+      if ((parser->m_tagLevel == 0)
+          && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
         if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
           parser->m_processor = epilogProcessor;
         else
@@ -2937,7 +2812,7 @@
         parser->m_tagStack = tag->parent;
         tag->parent = parser->m_freeTagList;
         parser->m_freeTagList = tag;
-        rawName = s + enc->minBytesPerChar*2;
+        rawName = s + enc->minBytesPerChar * 2;
         len = XmlNameLength(enc, rawName);
         if (len != tag->rawNameLength
             || memcmp(tag->rawName, rawName, len) != 0) {
@@ -2957,86 +2832,89 @@
             */
             uri = (XML_Char *)tag->name.str + tag->name.uriLen;
             /* don't need to check for space - already done in storeAtts() */
-            while (*localPart) *uri++ = *localPart++;
+            while (*localPart)
+              *uri++ = *localPart++;
             prefix = (XML_Char *)tag->name.prefix;
             if (parser->m_ns_triplets && prefix) {
               *uri++ = parser->m_namespaceSeparator;
-              while (*prefix) *uri++ = *prefix++;
-             }
+              while (*prefix)
+                *uri++ = *prefix++;
+            }
             *uri = XML_T('\0');
           }
           parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
-        }
-        else if (parser->m_defaultHandler)
+        } else if (parser->m_defaultHandler)
           reportDefault(parser, enc, s, next);
         while (tag->bindings) {
           BINDING *b = tag->bindings;
           if (parser->m_endNamespaceDeclHandler)
-            parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
+            parser->m_endNamespaceDeclHandler(parser->m_handlerArg,
+                                              b->prefix->name);
           tag->bindings = tag->bindings->nextTagBinding;
           b->nextTagBinding = parser->m_freeBindingList;
           parser->m_freeBindingList = b;
           b->prefix->binding = b->prevPrefixBinding;
         }
-        if (parser->m_tagLevel == 0)
-          return epilogProcessor(parser, next, end, nextPtr);
-      }
-      break;
-    case XML_TOK_CHAR_REF:
-      {
-        int n = XmlCharRefNumber(enc, s);
-        if (n < 0)
-          return XML_ERROR_BAD_CHAR_REF;
-        if (parser->m_characterDataHandler) {
-          XML_Char buf[XML_ENCODE_MAX];
-          parser->m_characterDataHandler(parser->m_handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
+        if ((parser->m_tagLevel == 0)
+            && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
+          if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
+            parser->m_processor = epilogProcessor;
+          else
+            return epilogProcessor(parser, next, end, nextPtr);
         }
-        else if (parser->m_defaultHandler)
-          reportDefault(parser, enc, s, next);
       }
       break;
+    case XML_TOK_CHAR_REF: {
+      int n = XmlCharRefNumber(enc, s);
+      if (n < 0)
+        return XML_ERROR_BAD_CHAR_REF;
+      if (parser->m_characterDataHandler) {
+        XML_Char buf[XML_ENCODE_MAX];
+        parser->m_characterDataHandler(parser->m_handlerArg, buf,
+                                       XmlEncode(n, (ICHAR *)buf));
+      } else if (parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+    } break;
     case XML_TOK_XML_DECL:
       return XML_ERROR_MISPLACED_XML_PI;
     case XML_TOK_DATA_NEWLINE:
       if (parser->m_characterDataHandler) {
         XML_Char c = 0xA;
         parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
-      }
-      else if (parser->m_defaultHandler)
+      } else if (parser->m_defaultHandler)
         reportDefault(parser, enc, s, next);
       break;
-    case XML_TOK_CDATA_SECT_OPEN:
-      {
-        enum XML_Error result;
-        if (parser->m_startCdataSectionHandler)
-          parser->m_startCdataSectionHandler(parser->m_handlerArg);
-#if 0
-        /* Suppose you doing a transformation on a document that involves
-           changing only the character data.  You set up a defaultHandler
-           and a characterDataHandler.  The defaultHandler simply copies
-           characters through.  The characterDataHandler does the
-           transformation and writes the characters out escaping them as
-           necessary.  This case will fail to work if we leave out the
-           following two lines (because & and < inside CDATA sections will
-           be incorrectly escaped).
+    case XML_TOK_CDATA_SECT_OPEN: {
+      enum XML_Error result;
+      if (parser->m_startCdataSectionHandler)
+        parser->m_startCdataSectionHandler(parser->m_handlerArg);
+      /* BEGIN disabled code */
+      /* Suppose you doing a transformation on a document that involves
+         changing only the character data.  You set up a defaultHandler
+         and a characterDataHandler.  The defaultHandler simply copies
+         characters through.  The characterDataHandler does the
+         transformation and writes the characters out escaping them as
+         necessary.  This case will fail to work if we leave out the
+         following two lines (because & and < inside CDATA sections will
+         be incorrectly escaped).
 
-           However, now we have a start/endCdataSectionHandler, so it seems
-           easier to let the user deal with this.
-        */
-        else if (parser->m_characterDataHandler)
-          parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
-#endif
-        else if (parser->m_defaultHandler)
-          reportDefault(parser, enc, s, next);
-        result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
-        if (result != XML_ERROR_NONE)
-          return result;
-        else if (!next) {
-          parser->m_processor = cdataSectionProcessor;
-          return result;
-        }
+         However, now we have a start/endCdataSectionHandler, so it seems
+         easier to let the user deal with this.
+      */
+      else if (0 && parser->m_characterDataHandler)
+        parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
+                                       0);
+      /* END disabled code */
+      else if (parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+      result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
+      if (result != XML_ERROR_NONE)
+        return result;
+      else if (! next) {
+        parser->m_processor = cdataSectionProcessor;
+        return result;
       }
-      break;
+    } break;
     case XML_TOK_TRAILING_RSQB:
       if (haveMore) {
         *nextPtr = s;
@@ -3046,15 +2924,14 @@
         if (MUST_CONVERT(enc, s)) {
           ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
           XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
-          parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
-                               (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
-        }
-        else
-          parser->m_characterDataHandler(parser->m_handlerArg,
-                               (XML_Char *)s,
-                               (int)((XML_Char *)end - (XML_Char *)s));
-      }
-      else if (parser->m_defaultHandler)
+          parser->m_characterDataHandler(
+              parser->m_handlerArg, parser->m_dataBuf,
+              (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
+        } else
+          parser->m_characterDataHandler(
+              parser->m_handlerArg, (XML_Char *)s,
+              (int)((XML_Char *)end - (XML_Char *)s));
+      } else if (parser->m_defaultHandler)
         reportDefault(parser, enc, s, end);
       /* We are at the end of the final buffer, should we check for
          XML_SUSPENDED, XML_FINISHED?
@@ -3069,37 +2946,34 @@
       }
       *nextPtr = end;
       return XML_ERROR_NONE;
-    case XML_TOK_DATA_CHARS:
-      {
-        XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
-        if (charDataHandler) {
-          if (MUST_CONVERT(enc, s)) {
-            for (;;) {
-              ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
-              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
-              *eventEndPP = s;
-              charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
-                              (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
-              if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
-                break;
-              *eventPP = s;
-            }
+    case XML_TOK_DATA_CHARS: {
+      XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
+      if (charDataHandler) {
+        if (MUST_CONVERT(enc, s)) {
+          for (;;) {
+            ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
+            const enum XML_Convert_Result convert_res = XmlConvert(
+                enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
+            *eventEndPP = s;
+            charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
+                            (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
+            if ((convert_res == XML_CONVERT_COMPLETED)
+                || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
+              break;
+            *eventPP = s;
           }
-          else
-            charDataHandler(parser->m_handlerArg,
-                            (XML_Char *)s,
-                            (int)((XML_Char *)next - (XML_Char *)s));
-        }
-        else if (parser->m_defaultHandler)
-          reportDefault(parser, enc, s, next);
-      }
-      break;
+        } else
+          charDataHandler(parser->m_handlerArg, (XML_Char *)s,
+                          (int)((XML_Char *)next - (XML_Char *)s));
+      } else if (parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+    } break;
     case XML_TOK_PI:
-      if (!reportProcessingInstruction(parser, enc, s, next))
+      if (! reportProcessingInstruction(parser, enc, s, next))
         return XML_ERROR_NO_MEMORY;
       break;
     case XML_TOK_COMMENT:
-      if (!reportComment(parser, enc, s, next))
+      if (! reportComment(parser, enc, s, next))
         return XML_ERROR_NO_MEMORY;
       break;
     default:
@@ -3122,7 +2996,7 @@
       return XML_ERROR_NONE;
     case XML_FINISHED:
       return XML_ERROR_ABORTED;
-    default: ;
+    default:;
     }
   }
   /* not reached */
@@ -3133,8 +3007,7 @@
  * reused as appropriate.
  */
 static void
-freeBindings(XML_Parser parser, BINDING *bindings)
-{
+freeBindings(XML_Parser parser, BINDING *bindings) {
   while (bindings) {
     BINDING *b = bindings;
 
@@ -3142,7 +3015,7 @@
      * binding in addBindings(), so call the end handler now.
      */
     if (parser->m_endNamespaceDeclHandler)
-        parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
+      parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
 
     bindings = bindings->nextTagBinding;
     b->nextTagBinding = parser->m_freeBindingList;
@@ -3162,14 +3035,12 @@
    - generate namespace aware element name (URI, prefix)
 */
 static enum XML_Error
-storeAtts(XML_Parser parser, const ENCODING *enc,
-          const char *attStr, TAG_NAME *tagNamePtr,
-          BINDING **bindingsPtr)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
+          TAG_NAME *tagNamePtr, BINDING **bindingsPtr) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   ELEMENT_TYPE *elementType;
   int nDefaultAtts;
-  const XML_Char **appAtts;   /* the attribute list for the application */
+  const XML_Char **appAtts; /* the attribute list for the application */
   int attIndex = 0;
   int prefixLen;
   int i;
@@ -3180,16 +3051,17 @@
   const XML_Char *localPart;
 
   /* lookup the element type name */
-  elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str,0);
-  if (!elementType) {
+  elementType
+      = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);
+  if (! elementType) {
     const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);
-    if (!name)
+    if (! name)
       return XML_ERROR_NO_MEMORY;
     elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
                                          sizeof(ELEMENT_TYPE));
-    if (!elementType)
+    if (! elementType)
       return XML_ERROR_NO_MEMORY;
-    if (parser->m_ns && !setElementTypePrefix(parser, elementType))
+    if (parser->m_ns && ! setElementTypePrefix(parser, elementType))
       return XML_ERROR_NO_MEMORY;
   }
   nDefaultAtts = elementType->nDefaultAtts;
@@ -3203,14 +3075,16 @@
     XML_AttrInfo *temp2;
 #endif
     parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
-    temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts, parser->m_attsSize * sizeof(ATTRIBUTE));
+    temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts,
+                                parser->m_attsSize * sizeof(ATTRIBUTE));
     if (temp == NULL) {
       parser->m_attsSize = oldAttsSize;
       return XML_ERROR_NO_MEMORY;
     }
     parser->m_atts = temp;
 #ifdef XML_ATTR_INFO
-    temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo, parser->m_attsSize * sizeof(XML_AttrInfo));
+    temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo,
+                                    parser->m_attsSize * sizeof(XML_AttrInfo));
     if (temp2 == NULL) {
       parser->m_attsSize = oldAttsSize;
       return XML_ERROR_NO_MEMORY;
@@ -3228,18 +3102,20 @@
     XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
 #endif
     /* add the name and value to the attribute list */
-    ATTRIBUTE_ID *attId = getAttributeId(parser, enc, currAtt->name,
-                                         currAtt->name
-                                         + XmlNameLength(enc, currAtt->name));
-    if (!attId)
+    ATTRIBUTE_ID *attId
+        = getAttributeId(parser, enc, currAtt->name,
+                         currAtt->name + XmlNameLength(enc, currAtt->name));
+    if (! attId)
       return XML_ERROR_NO_MEMORY;
 #ifdef XML_ATTR_INFO
-    currAttInfo->nameStart = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
-    currAttInfo->nameEnd = currAttInfo->nameStart +
-                           XmlNameLength(enc, currAtt->name);
-    currAttInfo->valueStart = parser->m_parseEndByteIndex -
-                            (parser->m_parseEndPtr - currAtt->valuePtr);
-    currAttInfo->valueEnd = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->valueEnd);
+    currAttInfo->nameStart
+        = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
+    currAttInfo->nameEnd
+        = currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);
+    currAttInfo->valueStart = parser->m_parseEndByteIndex
+                              - (parser->m_parseEndPtr - currAtt->valuePtr);
+    currAttInfo->valueEnd = parser->m_parseEndByteIndex
+                            - (parser->m_parseEndPtr - currAtt->valueEnd);
 #endif
     /* Detect duplicate attributes by their QNames. This does not work when
        namespace processing is turned on and different prefixes for the same
@@ -3252,7 +3128,7 @@
     }
     (attId->name)[-1] = 1;
     appAtts[attIndex++] = attId->name;
-    if (!parser->m_atts[i].normalized) {
+    if (! parser->m_atts[i].normalized) {
       enum XML_Error result;
       XML_Bool isCdata = XML_TRUE;
 
@@ -3268,17 +3144,17 @@
       }
 
       /* normalize the attribute value */
-      result = storeAttributeValue(parser, enc, isCdata,
-                                   parser->m_atts[i].valuePtr, parser->m_atts[i].valueEnd,
-                                   &parser->m_tempPool);
+      result = storeAttributeValue(
+          parser, enc, isCdata, parser->m_atts[i].valuePtr,
+          parser->m_atts[i].valueEnd, &parser->m_tempPool);
       if (result)
         return result;
       appAtts[attIndex] = poolStart(&parser->m_tempPool);
       poolFinish(&parser->m_tempPool);
-    }
-    else {
+    } else {
       /* the value did not need normalizing */
-      appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc, parser->m_atts[i].valuePtr,
+      appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,
+                                          parser->m_atts[i].valuePtr,
                                           parser->m_atts[i].valueEnd);
       if (appAtts[attIndex] == 0)
         return XML_ERROR_NO_MEMORY;
@@ -3293,15 +3169,13 @@
         if (result)
           return result;
         --attIndex;
-      }
-      else {
+      } else {
         /* deal with other prefixed names later */
         attIndex++;
         nPrefixes++;
         (attId->name)[-1] = 2;
       }
-    }
-    else
+    } else
       attIndex++;
   }
 
@@ -3313,29 +3187,26 @@
         parser->m_idAttIndex = i;
         break;
       }
-  }
-  else
+  } else
     parser->m_idAttIndex = -1;
 
   /* do attribute defaulting */
   for (i = 0; i < nDefaultAtts; i++) {
     const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;
-    if (!(da->id->name)[-1] && da->value) {
+    if (! (da->id->name)[-1] && da->value) {
       if (da->id->prefix) {
         if (da->id->xmlns) {
           enum XML_Error result = addBinding(parser, da->id->prefix, da->id,
                                              da->value, bindingsPtr);
           if (result)
             return result;
-        }
-        else {
+        } else {
           (da->id->name)[-1] = 2;
           nPrefixes++;
           appAtts[attIndex++] = da->id->name;
           appAtts[attIndex++] = da->value;
         }
-      }
-      else {
+      } else {
         (da->id->name)[-1] = 1;
         appAtts[attIndex++] = da->id->name;
         appAtts[attIndex++] = da->value;
@@ -3348,31 +3219,34 @@
      and clear flags that say whether attributes were specified */
   i = 0;
   if (nPrefixes) {
-    int j;  /* hash table index */
+    int j; /* hash table index */
     unsigned long version = parser->m_nsAttsVersion;
     int nsAttsSize = (int)1 << parser->m_nsAttsPower;
     unsigned char oldNsAttsPower = parser->m_nsAttsPower;
     /* size of hash table must be at least 2 * (# of prefixed attributes) */
-    if ((nPrefixes << 1) >> parser->m_nsAttsPower) {  /* true for m_nsAttsPower = 0 */
+    if ((nPrefixes << 1)
+        >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
       NS_ATT *temp;
       /* hash table size must also be a power of 2 and >= 8 */
-      while (nPrefixes >> parser->m_nsAttsPower++);
+      while (nPrefixes >> parser->m_nsAttsPower++)
+        ;
       if (parser->m_nsAttsPower < 3)
         parser->m_nsAttsPower = 3;
       nsAttsSize = (int)1 << parser->m_nsAttsPower;
-      temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));
-      if (!temp) {
+      temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts,
+                               nsAttsSize * sizeof(NS_ATT));
+      if (! temp) {
         /* Restore actual size of memory in m_nsAtts */
         parser->m_nsAttsPower = oldNsAttsPower;
         return XML_ERROR_NO_MEMORY;
       }
       parser->m_nsAtts = temp;
-      version = 0;  /* force re-initialization of m_nsAtts hash table */
+      version = 0; /* force re-initialization of m_nsAtts hash table */
     }
     /* using a version flag saves us from initializing m_nsAtts every time */
-    if (!version) {  /* initialize version flags when version wraps around */
+    if (! version) { /* initialize version flags when version wraps around */
       version = INIT_ATTS_VERSION;
-      for (j = nsAttsSize; j != 0; )
+      for (j = nsAttsSize; j != 0;)
         parser->m_nsAtts[--j].version = version;
     }
     parser->m_nsAttsVersion = --version;
@@ -3380,7 +3254,7 @@
     /* expand prefixed names and check for duplicates */
     for (; i < attIndex; i += 2) {
       const XML_Char *s = appAtts[i];
-      if (s[-1] == 2) {  /* prefixed */
+      if (s[-1] == 2) { /* prefixed */
         ATTRIBUTE_ID *id;
         const BINDING *b;
         unsigned long uriHash;
@@ -3390,9 +3264,9 @@
         copy_salt_to_sipkey(parser, &sip_key);
         sip24_init(&sip_state, &sip_key);
 
-        ((XML_Char *)s)[-1] = 0;  /* clear flag */
+        ((XML_Char *)s)[-1] = 0; /* clear flag */
         id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
-        if (!id || !id->prefix) {
+        if (! id || ! id->prefix) {
           /* This code is walking through the appAtts array, dealing
            * with (in this case) a prefixed attribute name.  To be in
            * the array, the attribute must have already been bound, so
@@ -3410,12 +3284,12 @@
           return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
         }
         b = id->prefix->binding;
-        if (!b)
+        if (! b)
           return XML_ERROR_UNBOUND_PREFIX;
 
         for (j = 0; j < b->uriLen; j++) {
           const XML_Char c = b->uri[j];
-          if (!poolAppendChar(&parser->m_tempPool, c))
+          if (! poolAppendChar(&parser->m_tempPool, c))
             return XML_ERROR_NO_MEMORY;
         }
 
@@ -3426,8 +3300,8 @@
 
         sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
 
-        do {  /* copies null terminator */
-          if (!poolAppendChar(&parser->m_tempPool, *s))
+        do { /* copies null terminator */
+          if (! poolAppendChar(&parser->m_tempPool, *s))
             return XML_ERROR_NO_MEMORY;
         } while (*s++);
 
@@ -3438,28 +3312,29 @@
           */
           unsigned char step = 0;
           unsigned long mask = nsAttsSize - 1;
-          j = uriHash & mask;  /* index into hash table */
+          j = uriHash & mask; /* index into hash table */
           while (parser->m_nsAtts[j].version == version) {
             /* for speed we compare stored hash values first */
             if (uriHash == parser->m_nsAtts[j].hash) {
               const XML_Char *s1 = poolStart(&parser->m_tempPool);
               const XML_Char *s2 = parser->m_nsAtts[j].uriName;
               /* s1 is null terminated, but not s2 */
-              for (; *s1 == *s2 && *s1 != 0; s1++, s2++);
+              for (; *s1 == *s2 && *s1 != 0; s1++, s2++)
+                ;
               if (*s1 == 0)
                 return XML_ERROR_DUPLICATE_ATTRIBUTE;
             }
-            if (!step)
+            if (! step)
               step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
             j < step ? (j += nsAttsSize - step) : (j -= step);
           }
         }
 
-        if (parser->m_ns_triplets) {  /* append namespace separator and prefix */
+        if (parser->m_ns_triplets) { /* append namespace separator and prefix */
           parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
           s = b->prefix->name;
           do {
-            if (!poolAppendChar(&parser->m_tempPool, *s))
+            if (! poolAppendChar(&parser->m_tempPool, *s))
               return XML_ERROR_NO_MEMORY;
           } while (*s++);
         }
@@ -3474,13 +3349,12 @@
         parser->m_nsAtts[j].hash = uriHash;
         parser->m_nsAtts[j].uriName = s;
 
-        if (!--nPrefixes) {
+        if (! --nPrefixes) {
           i += 2;
           break;
         }
-      }
-      else  /* not prefixed */
-        ((XML_Char *)s)[-1] = 0;  /* clear flag */
+      } else                     /* not prefixed */
+        ((XML_Char *)s)[-1] = 0; /* clear flag */
     }
   }
   /* clear flags for the remaining attributes */
@@ -3489,40 +3363,38 @@
   for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
     binding->attId->name[-1] = 0;
 
-  if (!parser->m_ns)
+  if (! parser->m_ns)
     return XML_ERROR_NONE;
 
   /* expand the element type name */
   if (elementType->prefix) {
     binding = elementType->prefix->binding;
-    if (!binding)
+    if (! binding)
       return XML_ERROR_UNBOUND_PREFIX;
     localPart = tagNamePtr->str;
     while (*localPart++ != XML_T(ASCII_COLON))
       ;
-  }
-  else if (dtd->defaultPrefix.binding) {
+  } else if (dtd->defaultPrefix.binding) {
     binding = dtd->defaultPrefix.binding;
     localPart = tagNamePtr->str;
-  }
-  else
+  } else
     return XML_ERROR_NONE;
   prefixLen = 0;
   if (parser->m_ns_triplets && binding->prefix->name) {
     for (; binding->prefix->name[prefixLen++];)
-      ;  /* prefixLen includes null terminator */
+      ; /* prefixLen includes null terminator */
   }
   tagNamePtr->localPart = localPart;
   tagNamePtr->uriLen = binding->uriLen;
   tagNamePtr->prefix = binding->prefix->name;
   tagNamePtr->prefixLen = prefixLen;
   for (i = 0; localPart[i++];)
-    ;  /* i includes null terminator */
+    ; /* i includes null terminator */
   n = i + binding->uriLen + prefixLen;
   if (n > binding->uriAlloc) {
     TAG *p;
     uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
-    if (!uri)
+    if (! uri)
       return XML_ERROR_NO_MEMORY;
     binding->uriAlloc = n + EXPAND_SPARE;
     memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
@@ -3538,7 +3410,7 @@
   /* we always have a namespace separator between localPart and prefix */
   if (prefixLen) {
     uri += i - 1;
-    *uri = parser->m_namespaceSeparator;  /* replace null terminator */
+    *uri = parser->m_namespaceSeparator; /* replace null terminator */
     memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
   }
   tagNamePtr->str = binding->uri;
@@ -3550,27 +3422,25 @@
 */
 static enum XML_Error
 addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
-           const XML_Char *uri, BINDING **bindingsPtr)
-{
-  static const XML_Char xmlNamespace[] = {
-    ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH,
-    ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD,
-    ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,
-    ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8, ASCII_SLASH,
-    ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,
-    ASCII_e, '\0'
-  };
-  static const int xmlLen =
-    (int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1;
-  static const XML_Char xmlnsNamespace[] = {
-    ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH,
-    ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD,
-    ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0,
-    ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s,
-    ASCII_SLASH, '\0'
-  };
-  static const int xmlnsLen =
-    (int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1;
+           const XML_Char *uri, BINDING **bindingsPtr) {
+  static const XML_Char xmlNamespace[]
+      = {ASCII_h,      ASCII_t,     ASCII_t,     ASCII_p,      ASCII_COLON,
+         ASCII_SLASH,  ASCII_SLASH, ASCII_w,     ASCII_w,      ASCII_w,
+         ASCII_PERIOD, ASCII_w,     ASCII_3,     ASCII_PERIOD, ASCII_o,
+         ASCII_r,      ASCII_g,     ASCII_SLASH, ASCII_X,      ASCII_M,
+         ASCII_L,      ASCII_SLASH, ASCII_1,     ASCII_9,      ASCII_9,
+         ASCII_8,      ASCII_SLASH, ASCII_n,     ASCII_a,      ASCII_m,
+         ASCII_e,      ASCII_s,     ASCII_p,     ASCII_a,      ASCII_c,
+         ASCII_e,      '\0'};
+  static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;
+  static const XML_Char xmlnsNamespace[]
+      = {ASCII_h,     ASCII_t,      ASCII_t, ASCII_p, ASCII_COLON,  ASCII_SLASH,
+         ASCII_SLASH, ASCII_w,      ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,
+         ASCII_3,     ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g,      ASCII_SLASH,
+         ASCII_2,     ASCII_0,      ASCII_0, ASCII_0, ASCII_SLASH,  ASCII_x,
+         ASCII_m,     ASCII_l,      ASCII_n, ASCII_s, ASCII_SLASH,  '\0'};
+  static const int xmlnsLen
+      = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;
 
   XML_Bool mustBeXML = XML_FALSE;
   XML_Bool isXML = XML_TRUE;
@@ -3583,14 +3453,11 @@
   if (*uri == XML_T('\0') && prefix->name)
     return XML_ERROR_UNDECLARING_PREFIX;
 
-  if (prefix->name
-      && prefix->name[0] == XML_T(ASCII_x)
+  if (prefix->name && prefix->name[0] == XML_T(ASCII_x)
       && prefix->name[1] == XML_T(ASCII_m)
       && prefix->name[2] == XML_T(ASCII_l)) {
-
     /* Not allowed to bind xmlns */
-    if (prefix->name[3] == XML_T(ASCII_n)
-        && prefix->name[4] == XML_T(ASCII_s)
+    if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)
         && prefix->name[5] == XML_T('\0'))
       return XML_ERROR_RESERVED_PREFIX_XMLNS;
 
@@ -3602,7 +3469,7 @@
     if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))
       isXML = XML_FALSE;
 
-    if (!mustBeXML && isXMLNS
+    if (! mustBeXML && isXMLNS
         && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))
       isXMLNS = XML_FALSE;
   }
@@ -3621,21 +3488,21 @@
   if (parser->m_freeBindingList) {
     b = parser->m_freeBindingList;
     if (len > b->uriAlloc) {
-      XML_Char *temp = (XML_Char *)REALLOC(parser, b->uri,
-                          sizeof(XML_Char) * (len + EXPAND_SPARE));
+      XML_Char *temp = (XML_Char *)REALLOC(
+          parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));
       if (temp == NULL)
         return XML_ERROR_NO_MEMORY;
       b->uri = temp;
       b->uriAlloc = len + EXPAND_SPARE;
     }
     parser->m_freeBindingList = b->nextTagBinding;
-  }
-  else {
+  } else {
     b = (BINDING *)MALLOC(parser, sizeof(BINDING));
-    if (!b)
+    if (! b)
       return XML_ERROR_NO_MEMORY;
-    b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
-    if (!b->uri) {
+    b->uri
+        = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
+    if (! b->uri) {
       FREE(parser, b);
       return XML_ERROR_NO_MEMORY;
     }
@@ -3658,7 +3525,7 @@
   /* if attId == NULL then we are not starting a namespace scope */
   if (attId && parser->m_startNamespaceDeclHandler)
     parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
-                              prefix->binding ? uri : 0);
+                                        prefix->binding ? uri : 0);
   return XML_ERROR_NONE;
 }
 
@@ -3666,21 +3533,18 @@
    the whole file is parsed with one call.
 */
 static enum XML_Error PTRCALL
-cdataSectionProcessor(XML_Parser parser,
-                      const char *start,
-                      const char *end,
-                      const char **endPtr)
-{
-  enum XML_Error result = doCdataSection(parser, parser->m_encoding, &start, end,
-                                         endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
+cdataSectionProcessor(XML_Parser parser, const char *start, const char *end,
+                      const char **endPtr) {
+  enum XML_Error result
+      = doCdataSection(parser, parser->m_encoding, &start, end, endPtr,
+                       (XML_Bool)! parser->m_parsingStatus.finalBuffer);
   if (result != XML_ERROR_NONE)
     return result;
   if (start) {
-    if (parser->m_parentParser) {  /* we are parsing an external entity */
+    if (parser->m_parentParser) { /* we are parsing an external entity */
       parser->m_processor = externalEntityContentProcessor;
       return externalEntityContentProcessor(parser, start, end, endPtr);
-    }
-    else {
+    } else {
       parser->m_processor = contentProcessor;
       return contentProcessor(parser, start, end, endPtr);
     }
@@ -3692,13 +3556,8 @@
    the section is not yet closed.
 */
 static enum XML_Error
-doCdataSection(XML_Parser parser,
-               const ENCODING *enc,
-               const char **startPtr,
-               const char *end,
-               const char **nextPtr,
-               XML_Bool haveMore)
-{
+doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
+               const char *end, const char **nextPtr, XML_Bool haveMore) {
   const char *s = *startPtr;
   const char **eventPP;
   const char **eventEndPP;
@@ -3706,8 +3565,7 @@
     eventPP = &parser->m_eventPtr;
     *eventPP = s;
     eventEndPP = &parser->m_eventEndPtr;
-  }
-  else {
+  } else {
     eventPP = &(parser->m_openInternalEntities->internalEventPtr);
     eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
   }
@@ -3722,11 +3580,12 @@
     case XML_TOK_CDATA_SECT_CLOSE:
       if (parser->m_endCdataSectionHandler)
         parser->m_endCdataSectionHandler(parser->m_handlerArg);
-#if 0
+      /* BEGIN disabled code */
       /* see comment under XML_TOK_CDATA_SECT_OPEN */
-      else if (parser->m_characterDataHandler)
-        parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
-#endif
+      else if (0 && parser->m_characterDataHandler)
+        parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
+                                       0);
+      /* END disabled code */
       else if (parser->m_defaultHandler)
         reportDefault(parser, enc, s, next);
       *startPtr = next;
@@ -3739,35 +3598,31 @@
       if (parser->m_characterDataHandler) {
         XML_Char c = 0xA;
         parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
-      }
-      else if (parser->m_defaultHandler)
+      } else if (parser->m_defaultHandler)
         reportDefault(parser, enc, s, next);
       break;
-    case XML_TOK_DATA_CHARS:
-      {
-        XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
-        if (charDataHandler) {
-          if (MUST_CONVERT(enc, s)) {
-            for (;;) {
-              ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
-              const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
-              *eventEndPP = next;
-              charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
-                              (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
-              if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
-                break;
-              *eventPP = s;
-            }
+    case XML_TOK_DATA_CHARS: {
+      XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
+      if (charDataHandler) {
+        if (MUST_CONVERT(enc, s)) {
+          for (;;) {
+            ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
+            const enum XML_Convert_Result convert_res = XmlConvert(
+                enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
+            *eventEndPP = next;
+            charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
+                            (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
+            if ((convert_res == XML_CONVERT_COMPLETED)
+                || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
+              break;
+            *eventPP = s;
           }
-          else
-            charDataHandler(parser->m_handlerArg,
-                            (XML_Char *)s,
-                            (int)((XML_Char *)next - (XML_Char *)s));
-        }
-        else if (parser->m_defaultHandler)
-          reportDefault(parser, enc, s, next);
-      }
-      break;
+        } else
+          charDataHandler(parser->m_handlerArg, (XML_Char *)s,
+                          (int)((XML_Char *)next - (XML_Char *)s));
+      } else if (parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+    } break;
     case XML_TOK_INVALID:
       *eventPP = next;
       return XML_ERROR_INVALID_TOKEN;
@@ -3791,7 +3646,7 @@
        * statistics.
        *
        * LCOV_EXCL_START
-      */
+       */
       *eventPP = next;
       return XML_ERROR_UNEXPECTED_STATE;
       /* LCOV_EXCL_STOP */
@@ -3804,7 +3659,7 @@
       return XML_ERROR_NONE;
     case XML_FINISHED:
       return XML_ERROR_ABORTED;
-    default: ;
+    default:;
     }
   }
   /* not reached */
@@ -3816,13 +3671,11 @@
    the whole file is parsed with one call.
 */
 static enum XML_Error PTRCALL
-ignoreSectionProcessor(XML_Parser parser,
-                       const char *start,
-                       const char *end,
-                       const char **endPtr)
-{
-  enum XML_Error result = doIgnoreSection(parser, parser->m_encoding, &start, end,
-                                          endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
+ignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,
+                       const char **endPtr) {
+  enum XML_Error result
+      = doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,
+                        (XML_Bool)! parser->m_parsingStatus.finalBuffer);
   if (result != XML_ERROR_NONE)
     return result;
   if (start) {
@@ -3836,13 +3689,8 @@
    if the section is not yet closed.
 */
 static enum XML_Error
-doIgnoreSection(XML_Parser parser,
-                const ENCODING *enc,
-                const char **startPtr,
-                const char *end,
-                const char **nextPtr,
-                XML_Bool haveMore)
-{
+doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
+                const char *end, const char **nextPtr, XML_Bool haveMore) {
   const char *next;
   int tok;
   const char *s = *startPtr;
@@ -3852,8 +3700,7 @@
     eventPP = &parser->m_eventPtr;
     *eventPP = s;
     eventEndPP = &parser->m_eventEndPtr;
-  }
-  else {
+  } else {
     /* It's not entirely clear, but it seems the following two lines
      * of code cannot be executed.  The only occasions on which 'enc'
      * is not 'encoding' are when this function is called
@@ -3917,13 +3764,12 @@
 #endif /* XML_DTD */
 
 static enum XML_Error
-initializeEncoding(XML_Parser parser)
-{
+initializeEncoding(XML_Parser parser) {
   const char *s;
 #ifdef XML_UNICODE
   char encodingBuf[128];
   /* See comments abount `protoclEncodingName` in parserInit() */
-  if (!parser->m_protocolEncodingName)
+  if (! parser->m_protocolEncodingName)
     s = NULL;
   else {
     int i;
@@ -3941,15 +3787,15 @@
 #else
   s = parser->m_protocolEncodingName;
 #endif
-  if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(&parser->m_initEncoding, &parser->m_encoding, s))
+  if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(
+          &parser->m_initEncoding, &parser->m_encoding, s))
     return XML_ERROR_NONE;
   return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
 }
 
 static enum XML_Error
-processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
-               const char *s, const char *next)
-{
+processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
+               const char *next) {
   const char *encodingName = NULL;
   const XML_Char *storedEncName = NULL;
   const ENCODING *newEncoding = NULL;
@@ -3957,52 +3803,41 @@
   const char *versionend;
   const XML_Char *storedversion = NULL;
   int standalone = -1;
-  if (!(parser->m_ns
-        ? XmlParseXmlDeclNS
-        : XmlParseXmlDecl)(isGeneralTextEntity,
-                           parser->m_encoding,
-                           s,
-                           next,
-                           &parser->m_eventPtr,
-                           &version,
-                           &versionend,
-                           &encodingName,
-                           &newEncoding,
-                           &standalone)) {
+  if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(
+          isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,
+          &version, &versionend, &encodingName, &newEncoding, &standalone)) {
     if (isGeneralTextEntity)
       return XML_ERROR_TEXT_DECL;
     else
       return XML_ERROR_XML_DECL;
   }
-  if (!isGeneralTextEntity && standalone == 1) {
+  if (! isGeneralTextEntity && standalone == 1) {
     parser->m_dtd->standalone = XML_TRUE;
 #ifdef XML_DTD
-    if (parser->m_paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
+    if (parser->m_paramEntityParsing
+        == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
       parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
 #endif /* XML_DTD */
   }
   if (parser->m_xmlDeclHandler) {
     if (encodingName != NULL) {
-      storedEncName = poolStoreString(&parser->m_temp2Pool,
-                                      parser->m_encoding,
-                                      encodingName,
-                                      encodingName
-                                      + XmlNameLength(parser->m_encoding, encodingName));
-      if (!storedEncName)
-              return XML_ERROR_NO_MEMORY;
+      storedEncName = poolStoreString(
+          &parser->m_temp2Pool, parser->m_encoding, encodingName,
+          encodingName + XmlNameLength(parser->m_encoding, encodingName));
+      if (! storedEncName)
+        return XML_ERROR_NO_MEMORY;
       poolFinish(&parser->m_temp2Pool);
     }
     if (version) {
-      storedversion = poolStoreString(&parser->m_temp2Pool,
-                                      parser->m_encoding,
-                                      version,
-                                      versionend - parser->m_encoding->minBytesPerChar);
-      if (!storedversion)
+      storedversion
+          = poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,
+                            versionend - parser->m_encoding->minBytesPerChar);
+      if (! storedversion)
         return XML_ERROR_NO_MEMORY;
     }
-    parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName, standalone);
-  }
-  else if (parser->m_defaultHandler)
+    parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,
+                             standalone);
+  } else if (parser->m_defaultHandler)
     reportDefault(parser, parser->m_encoding, s, next);
   if (parser->m_protocolEncodingName == NULL) {
     if (newEncoding) {
@@ -4012,20 +3847,19 @@
        * this is UTF-16, is it the same endianness?
        */
       if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
-          || (newEncoding->minBytesPerChar == 2 &&
-              newEncoding != parser->m_encoding)) {
+          || (newEncoding->minBytesPerChar == 2
+              && newEncoding != parser->m_encoding)) {
         parser->m_eventPtr = encodingName;
         return XML_ERROR_INCORRECT_ENCODING;
       }
       parser->m_encoding = newEncoding;
-    }
-    else if (encodingName) {
+    } else if (encodingName) {
       enum XML_Error result;
-      if (!storedEncName) {
+      if (! storedEncName) {
         storedEncName = poolStoreString(
-          &parser->m_temp2Pool, parser->m_encoding, encodingName,
-          encodingName + XmlNameLength(parser->m_encoding, encodingName));
-        if (!storedEncName)
+            &parser->m_temp2Pool, parser->m_encoding, encodingName,
+            encodingName + XmlNameLength(parser->m_encoding, encodingName));
+        if (! storedEncName)
           return XML_ERROR_NO_MEMORY;
       }
       result = handleUnknownEncoding(parser, storedEncName);
@@ -4043,8 +3877,7 @@
 }
 
 static enum XML_Error
-handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
-{
+handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {
   if (parser->m_unknownEncodingHandler) {
     XML_Encoding info;
     int i;
@@ -4053,21 +3886,17 @@
     info.convert = NULL;
     info.data = NULL;
     info.release = NULL;
-    if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName,
-                               &info)) {
+    if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,
+                                         encodingName, &info)) {
       ENCODING *enc;
       parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
-      if (!parser->m_unknownEncodingMem) {
+      if (! parser->m_unknownEncodingMem) {
         if (info.release)
           info.release(info.data);
         return XML_ERROR_NO_MEMORY;
       }
-      enc = (parser->m_ns
-             ? XmlInitUnknownEncodingNS
-             : XmlInitUnknownEncoding)(parser->m_unknownEncodingMem,
-                                       info.map,
-                                       info.convert,
-                                       info.data);
+      enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(
+          parser->m_unknownEncodingMem, info.map, info.convert, info.data);
       if (enc) {
         parser->m_unknownEncodingData = info.data;
         parser->m_unknownEncodingRelease = info.release;
@@ -4082,11 +3911,8 @@
 }
 
 static enum XML_Error PTRCALL
-prologInitProcessor(XML_Parser parser,
-                    const char *s,
-                    const char *end,
-                    const char **nextPtr)
-{
+prologInitProcessor(XML_Parser parser, const char *s, const char *end,
+                    const char **nextPtr) {
   enum XML_Error result = initializeEncoding(parser);
   if (result != XML_ERROR_NONE)
     return result;
@@ -4097,11 +3923,8 @@
 #ifdef XML_DTD
 
 static enum XML_Error PTRCALL
-externalParEntInitProcessor(XML_Parser parser,
-                            const char *s,
-                            const char *end,
-                            const char **nextPtr)
-{
+externalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,
+                            const char **nextPtr) {
   enum XML_Error result = initializeEncoding(parser);
   if (result != XML_ERROR_NONE)
     return result;
@@ -4113,19 +3936,15 @@
   if (parser->m_prologState.inEntityValue) {
     parser->m_processor = entityValueInitProcessor;
     return entityValueInitProcessor(parser, s, end, nextPtr);
-  }
-  else {
+  } else {
     parser->m_processor = externalParEntProcessor;
     return externalParEntProcessor(parser, s, end, nextPtr);
   }
 }
 
 static enum XML_Error PTRCALL
-entityValueInitProcessor(XML_Parser parser,
-                         const char *s,
-                         const char *end,
-                         const char **nextPtr)
-{
+entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
+                         const char **nextPtr) {
   int tok;
   const char *start = s;
   const char *next = start;
@@ -4135,7 +3954,7 @@
     tok = XmlPrologTok(parser->m_encoding, start, end, &next);
     parser->m_eventEndPtr = next;
     if (tok <= 0) {
-      if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
+      if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
         *nextPtr = s;
         return XML_ERROR_NONE;
       }
@@ -4146,22 +3965,21 @@
         return XML_ERROR_UNCLOSED_TOKEN;
       case XML_TOK_PARTIAL_CHAR:
         return XML_ERROR_PARTIAL_CHAR;
-      case XML_TOK_NONE:   /* start == end */
+      case XML_TOK_NONE: /* start == end */
       default:
         break;
       }
       /* found end of entity value - can store it now */
       return storeEntityValue(parser, parser->m_encoding, s, end);
-    }
-    else if (tok == XML_TOK_XML_DECL) {
+    } else if (tok == XML_TOK_XML_DECL) {
       enum XML_Error result;
       result = processXmlDecl(parser, 0, start, next);
       if (result != XML_ERROR_NONE)
         return result;
-      /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED.  For that
-       * to happen, a parameter entity parsing handler must have
-       * attempted to suspend the parser, which fails and raises an
-       * error.  The parser can be aborted, but can't be suspended.
+      /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED.  For
+       * that to happen, a parameter entity parsing handler must have attempted
+       * to suspend the parser, which fails and raises an error.  The parser can
+       * be aborted, but can't be suspended.
        */
       if (parser->m_parsingStatus.parsing == XML_FINISHED)
         return XML_ERROR_ABORTED;
@@ -4177,7 +3995,8 @@
        then, when this routine is entered the next time, XmlPrologTok will
        return XML_TOK_INVALID, since the BOM is still in the buffer
     */
-    else if (tok == XML_TOK_BOM && next == end && !parser->m_parsingStatus.finalBuffer) {
+    else if (tok == XML_TOK_BOM && next == end
+             && ! parser->m_parsingStatus.finalBuffer) {
       *nextPtr = next;
       return XML_ERROR_NONE;
     }
@@ -4195,17 +4014,14 @@
 }
 
 static enum XML_Error PTRCALL
-externalParEntProcessor(XML_Parser parser,
-                        const char *s,
-                        const char *end,
-                        const char **nextPtr)
-{
+externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
+                        const char **nextPtr) {
   const char *next = s;
   int tok;
 
   tok = XmlPrologTok(parser->m_encoding, s, end, &next);
   if (tok <= 0) {
-    if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
+    if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
       *nextPtr = s;
       return XML_ERROR_NONE;
     }
@@ -4216,7 +4032,7 @@
       return XML_ERROR_UNCLOSED_TOKEN;
     case XML_TOK_PARTIAL_CHAR:
       return XML_ERROR_PARTIAL_CHAR;
-    case XML_TOK_NONE:   /* start == end */
+    case XML_TOK_NONE: /* start == end */
     default:
       break;
     }
@@ -4231,16 +4047,13 @@
   }
 
   parser->m_processor = prologProcessor;
-  return doProlog(parser, parser->m_encoding, s, end, tok, next,
-                  nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
+  return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
+                  (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
 }
 
 static enum XML_Error PTRCALL
-entityValueProcessor(XML_Parser parser,
-                     const char *s,
-                     const char *end,
-                     const char **nextPtr)
-{
+entityValueProcessor(XML_Parser parser, const char *s, const char *end,
+                     const char **nextPtr) {
   const char *start = s;
   const char *next = s;
   const ENCODING *enc = parser->m_encoding;
@@ -4249,7 +4062,7 @@
   for (;;) {
     tok = XmlPrologTok(enc, start, end, &next);
     if (tok <= 0) {
-      if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
+      if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
         *nextPtr = s;
         return XML_ERROR_NONE;
       }
@@ -4260,7 +4073,7 @@
         return XML_ERROR_UNCLOSED_TOKEN;
       case XML_TOK_PARTIAL_CHAR:
         return XML_ERROR_PARTIAL_CHAR;
-      case XML_TOK_NONE:   /* start == end */
+      case XML_TOK_NONE: /* start == end */
       default:
         break;
       }
@@ -4274,52 +4087,46 @@
 #endif /* XML_DTD */
 
 static enum XML_Error PTRCALL
-prologProcessor(XML_Parser parser,
-                const char *s,
-                const char *end,
-                const char **nextPtr)
-{
+prologProcessor(XML_Parser parser, const char *s, const char *end,
+                const char **nextPtr) {
   const char *next = s;
   int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
-  return doProlog(parser, parser->m_encoding, s, end, tok, next,
-                  nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
+  return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
+                  (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
 }
 
 static enum XML_Error
-doProlog(XML_Parser parser,
-         const ENCODING *enc,
-         const char *s,
-         const char *end,
-         int tok,
-         const char *next,
-         const char **nextPtr,
-         XML_Bool haveMore)
-{
+doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+         int tok, const char *next, const char **nextPtr, XML_Bool haveMore,
+         XML_Bool allowClosingDoctype) {
 #ifdef XML_DTD
-  static const XML_Char externalSubsetName[] = { ASCII_HASH , '\0' };
+  static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
 #endif /* XML_DTD */
-  static const XML_Char atypeCDATA[] =
-      { ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' };
-  static const XML_Char atypeID[] = { ASCII_I, ASCII_D, '\0' };
-  static const XML_Char atypeIDREF[] =
-      { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' };
-  static const XML_Char atypeIDREFS[] =
-      { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' };
-  static const XML_Char atypeENTITY[] =
-      { ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' };
-  static const XML_Char atypeENTITIES[] = { ASCII_E, ASCII_N,
-      ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\0' };
-  static const XML_Char atypeNMTOKEN[] = {
-      ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' };
-  static const XML_Char atypeNMTOKENS[] = { ASCII_N, ASCII_M, ASCII_T,
-      ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\0' };
-  static const XML_Char notationPrefix[] = { ASCII_N, ASCII_O, ASCII_T,
-      ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0' };
-  static const XML_Char enumValueSep[] = { ASCII_PIPE, '\0' };
-  static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' };
+  static const XML_Char atypeCDATA[]
+      = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
+  static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
+  static const XML_Char atypeIDREF[]
+      = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
+  static const XML_Char atypeIDREFS[]
+      = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
+  static const XML_Char atypeENTITY[]
+      = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
+  static const XML_Char atypeENTITIES[]
+      = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
+         ASCII_I, ASCII_E, ASCII_S, '\0'};
+  static const XML_Char atypeNMTOKEN[]
+      = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
+  static const XML_Char atypeNMTOKENS[]
+      = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
+         ASCII_E, ASCII_N, ASCII_S, '\0'};
+  static const XML_Char notationPrefix[]
+      = {ASCII_N, ASCII_O, ASCII_T, ASCII_A,      ASCII_T,
+         ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
+  static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
+  static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
 
   /* save one level of indirection */
-  DTD * const dtd = parser->m_dtd;
+  DTD *const dtd = parser->m_dtd;
 
   const char **eventPP;
   const char **eventEndPP;
@@ -4328,8 +4135,7 @@
   if (enc == parser->m_encoding) {
     eventPP = &parser->m_eventPtr;
     eventEndPP = &parser->m_eventEndPtr;
-  }
-  else {
+  } else {
     eventPP = &(parser->m_openInternalEntities->internalEventPtr);
     eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
   }
@@ -4358,7 +4164,8 @@
       case XML_TOK_NONE:
 #ifdef XML_DTD
         /* for internal PE NOT referenced between declarations */
-        if (enc != parser->m_encoding && !parser->m_openInternalEntities->betweenDecl) {
+        if (enc != parser->m_encoding
+            && ! parser->m_openInternalEntities->betweenDecl) {
           *nextPtr = s;
           return XML_ERROR_NONE;
         }
@@ -4383,19 +4190,18 @@
     }
     role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
     switch (role) {
-    case XML_ROLE_XML_DECL:
-      {
-        enum XML_Error result = processXmlDecl(parser, 0, s, next);
-        if (result != XML_ERROR_NONE)
-          return result;
-        enc = parser->m_encoding;
-        handleDefault = XML_FALSE;
-      }
-      break;
+    case XML_ROLE_XML_DECL: {
+      enum XML_Error result = processXmlDecl(parser, 0, s, next);
+      if (result != XML_ERROR_NONE)
+        return result;
+      enc = parser->m_encoding;
+      handleDefault = XML_FALSE;
+    } break;
     case XML_ROLE_DOCTYPE_NAME:
       if (parser->m_startDoctypeDeclHandler) {
-        parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next);
-        if (!parser->m_doctypeName)
+        parser->m_doctypeName
+            = poolStoreString(&parser->m_tempPool, enc, s, next);
+        if (! parser->m_doctypeName)
           return XML_ERROR_NO_MEMORY;
         poolFinish(&parser->m_tempPool);
         parser->m_doctypePubid = NULL;
@@ -4405,43 +4211,40 @@
       break;
     case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
       if (parser->m_startDoctypeDeclHandler) {
-        parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
-                                parser->m_doctypePubid, 1);
+        parser->m_startDoctypeDeclHandler(
+            parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
+            parser->m_doctypePubid, 1);
         parser->m_doctypeName = NULL;
         poolClear(&parser->m_tempPool);
         handleDefault = XML_FALSE;
       }
       break;
 #ifdef XML_DTD
-    case XML_ROLE_TEXT_DECL:
-      {
-        enum XML_Error result = processXmlDecl(parser, 1, s, next);
-        if (result != XML_ERROR_NONE)
-          return result;
-        enc = parser->m_encoding;
-        handleDefault = XML_FALSE;
-      }
-      break;
+    case XML_ROLE_TEXT_DECL: {
+      enum XML_Error result = processXmlDecl(parser, 1, s, next);
+      if (result != XML_ERROR_NONE)
+        return result;
+      enc = parser->m_encoding;
+      handleDefault = XML_FALSE;
+    } break;
 #endif /* XML_DTD */
     case XML_ROLE_DOCTYPE_PUBLIC_ID:
 #ifdef XML_DTD
       parser->m_useForeignDTD = XML_FALSE;
-      parser->m_declEntity = (ENTITY *)lookup(parser,
-                                    &dtd->paramEntities,
-                                    externalSubsetName,
-                                    sizeof(ENTITY));
-      if (!parser->m_declEntity)
+      parser->m_declEntity = (ENTITY *)lookup(
+          parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
+      if (! parser->m_declEntity)
         return XML_ERROR_NO_MEMORY;
 #endif /* XML_DTD */
       dtd->hasParamEntityRefs = XML_TRUE;
       if (parser->m_startDoctypeDeclHandler) {
         XML_Char *pubId;
-        if (!XmlIsPublicId(enc, s, next, eventPP))
+        if (! XmlIsPublicId(enc, s, next, eventPP))
           return XML_ERROR_PUBLICID;
         pubId = poolStoreString(&parser->m_tempPool, enc,
                                 s + enc->minBytesPerChar,
                                 next - enc->minBytesPerChar);
-        if (!pubId)
+        if (! pubId)
           return XML_ERROR_NO_MEMORY;
         normalizePublicId(pubId);
         poolFinish(&parser->m_tempPool);
@@ -4451,15 +4254,14 @@
       }
       /* fall through */
     case XML_ROLE_ENTITY_PUBLIC_ID:
-      if (!XmlIsPublicId(enc, s, next, eventPP))
+      if (! XmlIsPublicId(enc, s, next, eventPP))
         return XML_ERROR_PUBLICID;
     alreadyChecked:
       if (dtd->keepProcessing && parser->m_declEntity) {
-        XML_Char *tem = poolStoreString(&dtd->pool,
-                                        enc,
-                                        s + enc->minBytesPerChar,
-                                        next - enc->minBytesPerChar);
-        if (!tem)
+        XML_Char *tem
+            = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
+                              next - enc->minBytesPerChar);
+        if (! tem)
           return XML_ERROR_NO_MEMORY;
         normalizePublicId(tem);
         parser->m_declEntity->publicId = tem;
@@ -4472,9 +4274,15 @@
       }
       break;
     case XML_ROLE_DOCTYPE_CLOSE:
+      if (allowClosingDoctype != XML_TRUE) {
+        /* Must not close doctype from within expanded parameter entities */
+        return XML_ERROR_INVALID_TOKEN;
+      }
+
       if (parser->m_doctypeName) {
-        parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName,
-                                parser->m_doctypeSysid, parser->m_doctypePubid, 0);
+        parser->m_startDoctypeDeclHandler(
+            parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
+            parser->m_doctypePubid, 0);
         poolClear(&parser->m_tempPool);
         handleDefault = XML_FALSE;
       }
@@ -4486,12 +4294,11 @@
       if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
         XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
         dtd->hasParamEntityRefs = XML_TRUE;
-        if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
-          ENTITY *entity = (ENTITY *)lookup(parser,
-                                            &dtd->paramEntities,
-                                            externalSubsetName,
-                                            sizeof(ENTITY));
-          if (!entity) {
+        if (parser->m_paramEntityParsing
+            && parser->m_externalEntityRefHandler) {
+          ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
+                                            externalSubsetName, sizeof(ENTITY));
+          if (! entity) {
             /* The external subset name "#" will have already been
              * inserted into the hash table at the start of the
              * external entity parsing, so no allocation will happen
@@ -4502,22 +4309,19 @@
           if (parser->m_useForeignDTD)
             entity->base = parser->m_curBase;
           dtd->paramEntityRead = XML_FALSE;
-          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
-                                        0,
-                                        entity->base,
-                                        entity->systemId,
-                                        entity->publicId))
+          if (! parser->m_externalEntityRefHandler(
+                  parser->m_externalEntityRefHandlerArg, 0, entity->base,
+                  entity->systemId, entity->publicId))
             return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
           if (dtd->paramEntityRead) {
-            if (!dtd->standalone &&
-                parser->m_notStandaloneHandler &&
-                !parser->m_notStandaloneHandler(parser->m_handlerArg))
+            if (! dtd->standalone && parser->m_notStandaloneHandler
+                && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
               return XML_ERROR_NOT_STANDALONE;
           }
           /* if we didn't read the foreign DTD then this means that there
              is no external subset and we must reset dtd->hasParamEntityRefs
           */
-          else if (!parser->m_doctypeSysid)
+          else if (! parser->m_doctypeSysid)
             dtd->hasParamEntityRefs = hadParamEntityRefs;
           /* end of DTD - no need to update dtd->keepProcessing */
         }
@@ -4537,24 +4341,21 @@
       if (parser->m_useForeignDTD) {
         XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
         dtd->hasParamEntityRefs = XML_TRUE;
-        if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
+        if (parser->m_paramEntityParsing
+            && parser->m_externalEntityRefHandler) {
           ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
-                                            externalSubsetName,
-                                            sizeof(ENTITY));
-          if (!entity)
+                                            externalSubsetName, sizeof(ENTITY));
+          if (! entity)
             return XML_ERROR_NO_MEMORY;
           entity->base = parser->m_curBase;
           dtd->paramEntityRead = XML_FALSE;
-          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
-                                        0,
-                                        entity->base,
-                                        entity->systemId,
-                                        entity->publicId))
+          if (! parser->m_externalEntityRefHandler(
+                  parser->m_externalEntityRefHandlerArg, 0, entity->base,
+                  entity->systemId, entity->publicId))
             return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
           if (dtd->paramEntityRead) {
-            if (!dtd->standalone &&
-                parser->m_notStandaloneHandler &&
-                !parser->m_notStandaloneHandler(parser->m_handlerArg))
+            if (! dtd->standalone && parser->m_notStandaloneHandler
+                && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
               return XML_ERROR_NOT_STANDALONE;
           }
           /* if we didn't read the foreign DTD then this means that there
@@ -4570,12 +4371,12 @@
       return contentProcessor(parser, s, end, nextPtr);
     case XML_ROLE_ATTLIST_ELEMENT_NAME:
       parser->m_declElementType = getElementType(parser, enc, s, next);
-      if (!parser->m_declElementType)
+      if (! parser->m_declElementType)
         return XML_ERROR_NO_MEMORY;
       goto checkAttListDeclHandler;
     case XML_ROLE_ATTRIBUTE_NAME:
       parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
-      if (!parser->m_declAttributeId)
+      if (! parser->m_declAttributeId)
         return XML_ERROR_NO_MEMORY;
       parser->m_declAttributeIsCdata = XML_FALSE;
       parser->m_declAttributeType = NULL;
@@ -4616,15 +4417,13 @@
         const XML_Char *prefix;
         if (parser->m_declAttributeType) {
           prefix = enumValueSep;
+        } else {
+          prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
+                                                              : enumValueStart);
         }
-        else {
-          prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE
-                    ? notationPrefix
-                    : enumValueStart);
-        }
-        if (!poolAppendString(&parser->m_tempPool, prefix))
+        if (! poolAppendString(&parser->m_tempPool, prefix))
           return XML_ERROR_NO_MEMORY;
-        if (!poolAppend(&parser->m_tempPool, enc, s, next))
+        if (! poolAppend(&parser->m_tempPool, enc, s, next))
           return XML_ERROR_NO_MEMORY;
         parser->m_declAttributeType = parser->m_tempPool.start;
         handleDefault = XML_FALSE;
@@ -4633,25 +4432,27 @@
     case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
     case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
       if (dtd->keepProcessing) {
-        if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
-                             parser->m_declAttributeIsCdata, parser->m_declAttributeIsId,
-                             0, parser))
+        if (! defineAttribute(parser->m_declElementType,
+                              parser->m_declAttributeId,
+                              parser->m_declAttributeIsCdata,
+                              parser->m_declAttributeIsId, 0, parser))
           return XML_ERROR_NO_MEMORY;
         if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
           if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
               || (*parser->m_declAttributeType == XML_T(ASCII_N)
                   && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
             /* Enumerated or Notation type */
-            if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
-                || !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
+            if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
+                || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
               return XML_ERROR_NO_MEMORY;
             parser->m_declAttributeType = parser->m_tempPool.start;
             poolFinish(&parser->m_tempPool);
           }
           *eventEndPP = s;
-          parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
-                             parser->m_declAttributeId->name, parser->m_declAttributeType,
-                             0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
+          parser->m_attlistDeclHandler(
+              parser->m_handlerArg, parser->m_declElementType->name,
+              parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
+              role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
           poolClear(&parser->m_tempPool);
           handleDefault = XML_FALSE;
         }
@@ -4661,35 +4462,34 @@
     case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
       if (dtd->keepProcessing) {
         const XML_Char *attVal;
-        enum XML_Error result =
-          storeAttributeValue(parser, enc, parser->m_declAttributeIsCdata,
-                              s + enc->minBytesPerChar,
-                              next - enc->minBytesPerChar,
-                              &dtd->pool);
+        enum XML_Error result = storeAttributeValue(
+            parser, enc, parser->m_declAttributeIsCdata,
+            s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool);
         if (result)
           return result;
         attVal = poolStart(&dtd->pool);
         poolFinish(&dtd->pool);
         /* ID attributes aren't allowed to have a default */
-        if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
-                             parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
+        if (! defineAttribute(
+                parser->m_declElementType, parser->m_declAttributeId,
+                parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
           return XML_ERROR_NO_MEMORY;
         if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
           if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
               || (*parser->m_declAttributeType == XML_T(ASCII_N)
                   && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
             /* Enumerated or Notation type */
-            if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
-                || !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
+            if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
+                || ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
               return XML_ERROR_NO_MEMORY;
             parser->m_declAttributeType = parser->m_tempPool.start;
             poolFinish(&parser->m_tempPool);
           }
           *eventEndPP = s;
-          parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
-                             parser->m_declAttributeId->name, parser->m_declAttributeType,
-                             attVal,
-                             role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
+          parser->m_attlistDeclHandler(
+              parser->m_handlerArg, parser->m_declElementType->name,
+              parser->m_declAttributeId->name, parser->m_declAttributeType,
+              attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
           poolClear(&parser->m_tempPool);
           handleDefault = XML_FALSE;
         }
@@ -4697,25 +4497,22 @@
       break;
     case XML_ROLE_ENTITY_VALUE:
       if (dtd->keepProcessing) {
-        enum XML_Error result = storeEntityValue(parser, enc,
-                                            s + enc->minBytesPerChar,
-                                            next - enc->minBytesPerChar);
+        enum XML_Error result = storeEntityValue(
+            parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
         if (parser->m_declEntity) {
           parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
-          parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
+          parser->m_declEntity->textLen
+              = (int)(poolLength(&dtd->entityValuePool));
           poolFinish(&dtd->entityValuePool);
           if (parser->m_entityDeclHandler) {
             *eventEndPP = s;
-            parser->m_entityDeclHandler(parser->m_handlerArg,
-                              parser->m_declEntity->name,
-                              parser->m_declEntity->is_param,
-                              parser->m_declEntity->textPtr,
-                              parser->m_declEntity->textLen,
-                              parser->m_curBase, 0, 0, 0);
+            parser->m_entityDeclHandler(
+                parser->m_handlerArg, parser->m_declEntity->name,
+                parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
+                parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
             handleDefault = XML_FALSE;
           }
-        }
-        else
+        } else
           poolDiscard(&dtd->entityValuePool);
         if (result != XML_ERROR_NONE)
           return result;
@@ -4728,8 +4525,8 @@
       dtd->hasParamEntityRefs = XML_TRUE;
       if (parser->m_startDoctypeDeclHandler) {
         parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
-                                       s + enc->minBytesPerChar,
-                                       next - enc->minBytesPerChar);
+                                                 s + enc->minBytesPerChar,
+                                                 next - enc->minBytesPerChar);
         if (parser->m_doctypeSysid == NULL)
           return XML_ERROR_NO_MEMORY;
         poolFinish(&parser->m_tempPool);
@@ -4741,22 +4538,20 @@
            for the case where no parser->m_startDoctypeDeclHandler is set */
         parser->m_doctypeSysid = externalSubsetName;
 #endif /* XML_DTD */
-      if (!dtd->standalone
+      if (! dtd->standalone
 #ifdef XML_DTD
-          && !parser->m_paramEntityParsing
+          && ! parser->m_paramEntityParsing
 #endif /* XML_DTD */
           && parser->m_notStandaloneHandler
-          && !parser->m_notStandaloneHandler(parser->m_handlerArg))
+          && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
         return XML_ERROR_NOT_STANDALONE;
 #ifndef XML_DTD
       break;
-#else /* XML_DTD */
-      if (!parser->m_declEntity) {
-        parser->m_declEntity = (ENTITY *)lookup(parser,
-                                      &dtd->paramEntities,
-                                      externalSubsetName,
-                                      sizeof(ENTITY));
-        if (!parser->m_declEntity)
+#else  /* XML_DTD */
+      if (! parser->m_declEntity) {
+        parser->m_declEntity = (ENTITY *)lookup(
+            parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
+        if (! parser->m_declEntity)
           return XML_ERROR_NO_MEMORY;
         parser->m_declEntity->publicId = NULL;
       }
@@ -4764,10 +4559,10 @@
       /* fall through */
     case XML_ROLE_ENTITY_SYSTEM_ID:
       if (dtd->keepProcessing && parser->m_declEntity) {
-        parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc,
-                                               s + enc->minBytesPerChar,
-                                               next - enc->minBytesPerChar);
-        if (!parser->m_declEntity->systemId)
+        parser->m_declEntity->systemId
+            = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
+                              next - enc->minBytesPerChar);
+        if (! parser->m_declEntity->systemId)
           return XML_ERROR_NO_MEMORY;
         parser->m_declEntity->base = parser->m_curBase;
         poolFinish(&dtd->pool);
@@ -4779,115 +4574,103 @@
       }
       break;
     case XML_ROLE_ENTITY_COMPLETE:
-      if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) {
+      if (dtd->keepProcessing && parser->m_declEntity
+          && parser->m_entityDeclHandler) {
         *eventEndPP = s;
-        parser->m_entityDeclHandler(parser->m_handlerArg,
-                          parser->m_declEntity->name,
-                          parser->m_declEntity->is_param,
-                          0,0,
-                          parser->m_declEntity->base,
-                          parser->m_declEntity->systemId,
-                          parser->m_declEntity->publicId,
-                          0);
+        parser->m_entityDeclHandler(
+            parser->m_handlerArg, parser->m_declEntity->name,
+            parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,
+            parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);
         handleDefault = XML_FALSE;
       }
       break;
     case XML_ROLE_ENTITY_NOTATION_NAME:
       if (dtd->keepProcessing && parser->m_declEntity) {
-        parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
-        if (!parser->m_declEntity->notation)
+        parser->m_declEntity->notation
+            = poolStoreString(&dtd->pool, enc, s, next);
+        if (! parser->m_declEntity->notation)
           return XML_ERROR_NO_MEMORY;
         poolFinish(&dtd->pool);
         if (parser->m_unparsedEntityDeclHandler) {
           *eventEndPP = s;
-          parser->m_unparsedEntityDeclHandler(parser->m_handlerArg,
-                                    parser->m_declEntity->name,
-                                    parser->m_declEntity->base,
-                                    parser->m_declEntity->systemId,
-                                    parser->m_declEntity->publicId,
-                                    parser->m_declEntity->notation);
+          parser->m_unparsedEntityDeclHandler(
+              parser->m_handlerArg, parser->m_declEntity->name,
+              parser->m_declEntity->base, parser->m_declEntity->systemId,
+              parser->m_declEntity->publicId, parser->m_declEntity->notation);
           handleDefault = XML_FALSE;
-        }
-        else if (parser->m_entityDeclHandler) {
+        } else if (parser->m_entityDeclHandler) {
           *eventEndPP = s;
-          parser->m_entityDeclHandler(parser->m_handlerArg,
-                            parser->m_declEntity->name,
-                            0,0,0,
-                            parser->m_declEntity->base,
-                            parser->m_declEntity->systemId,
-                            parser->m_declEntity->publicId,
-                            parser->m_declEntity->notation);
+          parser->m_entityDeclHandler(
+              parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,
+              parser->m_declEntity->base, parser->m_declEntity->systemId,
+              parser->m_declEntity->publicId, parser->m_declEntity->notation);
           handleDefault = XML_FALSE;
         }
       }
       break;
-    case XML_ROLE_GENERAL_ENTITY_NAME:
-      {
-        if (XmlPredefinedEntityName(enc, s, next)) {
-          parser->m_declEntity = NULL;
-          break;
-        }
-        if (dtd->keepProcessing) {
-          const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
-          if (!name)
-            return XML_ERROR_NO_MEMORY;
-          parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name,
-                                        sizeof(ENTITY));
-          if (!parser->m_declEntity)
-            return XML_ERROR_NO_MEMORY;
-          if (parser->m_declEntity->name != name) {
-            poolDiscard(&dtd->pool);
-            parser->m_declEntity = NULL;
-          }
-          else {
-            poolFinish(&dtd->pool);
-            parser->m_declEntity->publicId = NULL;
-            parser->m_declEntity->is_param = XML_FALSE;
-            /* if we have a parent parser or are reading an internal parameter
-               entity, then the entity declaration is not considered "internal"
-            */
-            parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
-            if (parser->m_entityDeclHandler)
-              handleDefault = XML_FALSE;
-          }
-        }
-        else {
-          poolDiscard(&dtd->pool);
-          parser->m_declEntity = NULL;
-        }
+    case XML_ROLE_GENERAL_ENTITY_NAME: {
+      if (XmlPredefinedEntityName(enc, s, next)) {
+        parser->m_declEntity = NULL;
+        break;
       }
-      break;
-    case XML_ROLE_PARAM_ENTITY_NAME:
-#ifdef XML_DTD
       if (dtd->keepProcessing) {
         const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
-        if (!name)
+        if (! name)
           return XML_ERROR_NO_MEMORY;
-        parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
-                                           name, sizeof(ENTITY));
-        if (!parser->m_declEntity)
+        parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,
+                                                name, sizeof(ENTITY));
+        if (! parser->m_declEntity)
           return XML_ERROR_NO_MEMORY;
         if (parser->m_declEntity->name != name) {
           poolDiscard(&dtd->pool);
           parser->m_declEntity = NULL;
+        } else {
+          poolFinish(&dtd->pool);
+          parser->m_declEntity->publicId = NULL;
+          parser->m_declEntity->is_param = XML_FALSE;
+          /* if we have a parent parser or are reading an internal parameter
+             entity, then the entity declaration is not considered "internal"
+          */
+          parser->m_declEntity->is_internal
+              = ! (parser->m_parentParser || parser->m_openInternalEntities);
+          if (parser->m_entityDeclHandler)
+            handleDefault = XML_FALSE;
         }
-        else {
+      } else {
+        poolDiscard(&dtd->pool);
+        parser->m_declEntity = NULL;
+      }
+    } break;
+    case XML_ROLE_PARAM_ENTITY_NAME:
+#ifdef XML_DTD
+      if (dtd->keepProcessing) {
+        const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
+        if (! name)
+          return XML_ERROR_NO_MEMORY;
+        parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
+                                                name, sizeof(ENTITY));
+        if (! parser->m_declEntity)
+          return XML_ERROR_NO_MEMORY;
+        if (parser->m_declEntity->name != name) {
+          poolDiscard(&dtd->pool);
+          parser->m_declEntity = NULL;
+        } else {
           poolFinish(&dtd->pool);
           parser->m_declEntity->publicId = NULL;
           parser->m_declEntity->is_param = XML_TRUE;
           /* if we have a parent parser or are reading an internal parameter
              entity, then the entity declaration is not considered "internal"
           */
-          parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
+          parser->m_declEntity->is_internal
+              = ! (parser->m_parentParser || parser->m_openInternalEntities);
           if (parser->m_entityDeclHandler)
             handleDefault = XML_FALSE;
         }
-      }
-      else {
+      } else {
         poolDiscard(&dtd->pool);
         parser->m_declEntity = NULL;
       }
-#else /* not XML_DTD */
+#else  /* not XML_DTD */
       parser->m_declEntity = NULL;
 #endif /* XML_DTD */
       break;
@@ -4895,22 +4678,23 @@
       parser->m_declNotationPublicId = NULL;
       parser->m_declNotationName = NULL;
       if (parser->m_notationDeclHandler) {
-        parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next);
-        if (!parser->m_declNotationName)
+        parser->m_declNotationName
+            = poolStoreString(&parser->m_tempPool, enc, s, next);
+        if (! parser->m_declNotationName)
           return XML_ERROR_NO_MEMORY;
         poolFinish(&parser->m_tempPool);
         handleDefault = XML_FALSE;
       }
       break;
     case XML_ROLE_NOTATION_PUBLIC_ID:
-      if (!XmlIsPublicId(enc, s, next, eventPP))
+      if (! XmlIsPublicId(enc, s, next, eventPP))
         return XML_ERROR_PUBLICID;
-      if (parser->m_declNotationName) {  /* means m_notationDeclHandler != NULL */
-        XML_Char *tem = poolStoreString(&parser->m_tempPool,
-                                        enc,
+      if (parser
+              ->m_declNotationName) { /* means m_notationDeclHandler != NULL */
+        XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,
                                         s + enc->minBytesPerChar,
                                         next - enc->minBytesPerChar);
-        if (!tem)
+        if (! tem)
           return XML_ERROR_NO_MEMORY;
         normalizePublicId(tem);
         parser->m_declNotationPublicId = tem;
@@ -4920,18 +4704,15 @@
       break;
     case XML_ROLE_NOTATION_SYSTEM_ID:
       if (parser->m_declNotationName && parser->m_notationDeclHandler) {
-        const XML_Char *systemId
-          = poolStoreString(&parser->m_tempPool, enc,
-                            s + enc->minBytesPerChar,
-                            next - enc->minBytesPerChar);
-        if (!systemId)
+        const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,
+                                                   s + enc->minBytesPerChar,
+                                                   next - enc->minBytesPerChar);
+        if (! systemId)
           return XML_ERROR_NO_MEMORY;
         *eventEndPP = s;
-        parser->m_notationDeclHandler(parser->m_handlerArg,
-                            parser->m_declNotationName,
-                            parser->m_curBase,
-                            systemId,
-                            parser->m_declNotationPublicId);
+        parser->m_notationDeclHandler(
+            parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
+            systemId, parser->m_declNotationPublicId);
         handleDefault = XML_FALSE;
       }
       poolClear(&parser->m_tempPool);
@@ -4939,11 +4720,9 @@
     case XML_ROLE_NOTATION_NO_SYSTEM_ID:
       if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
         *eventEndPP = s;
-        parser->m_notationDeclHandler(parser->m_handlerArg,
-                            parser->m_declNotationName,
-                            parser->m_curBase,
-                            0,
-                            parser->m_declNotationPublicId);
+        parser->m_notationDeclHandler(
+            parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
+            0, parser->m_declNotationPublicId);
         handleDefault = XML_FALSE;
       }
       poolClear(&parser->m_tempPool);
@@ -4960,42 +4739,44 @@
         return XML_ERROR_SYNTAX;
       }
 #ifdef XML_DTD
-    case XML_ROLE_IGNORE_SECT:
-      {
-        enum XML_Error result;
-        if (parser->m_defaultHandler)
-          reportDefault(parser, enc, s, next);
-        handleDefault = XML_FALSE;
-        result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
-        if (result != XML_ERROR_NONE)
-          return result;
-        else if (!next) {
-          parser->m_processor = ignoreSectionProcessor;
-          return result;
-        }
+    case XML_ROLE_IGNORE_SECT: {
+      enum XML_Error result;
+      if (parser->m_defaultHandler)
+        reportDefault(parser, enc, s, next);
+      handleDefault = XML_FALSE;
+      result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
+      if (result != XML_ERROR_NONE)
+        return result;
+      else if (! next) {
+        parser->m_processor = ignoreSectionProcessor;
+        return result;
       }
-      break;
+    } break;
 #endif /* XML_DTD */
     case XML_ROLE_GROUP_OPEN:
       if (parser->m_prologState.level >= parser->m_groupSize) {
         if (parser->m_groupSize) {
-          char *temp = (char *)REALLOC(parser, parser->m_groupConnector, parser->m_groupSize *= 2);
-          if (temp == NULL) {
-            parser->m_groupSize /= 2;
-            return XML_ERROR_NO_MEMORY;
-          }
-          parser->m_groupConnector = temp;
-          if (dtd->scaffIndex) {
-            int *temp = (int *)REALLOC(parser, dtd->scaffIndex,
-                          parser->m_groupSize * sizeof(int));
-            if (temp == NULL)
+          {
+            char *const new_connector = (char *)REALLOC(
+                parser, parser->m_groupConnector, parser->m_groupSize *= 2);
+            if (new_connector == NULL) {
+              parser->m_groupSize /= 2;
               return XML_ERROR_NO_MEMORY;
-            dtd->scaffIndex = temp;
+            }
+            parser->m_groupConnector = new_connector;
           }
-        }
-        else {
-          parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32);
-          if (!parser->m_groupConnector) {
+
+          if (dtd->scaffIndex) {
+            int *const new_scaff_index = (int *)REALLOC(
+                parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));
+            if (new_scaff_index == NULL)
+              return XML_ERROR_NO_MEMORY;
+            dtd->scaffIndex = new_scaff_index;
+          }
+        } else {
+          parser->m_groupConnector
+              = (char *)MALLOC(parser, parser->m_groupSize = 32);
+          if (! parser->m_groupConnector) {
             parser->m_groupSize = 0;
             return XML_ERROR_NO_MEMORY;
           }
@@ -5006,6 +4787,7 @@
         int myindex = nextScaffoldPart(parser);
         if (myindex < 0)
           return XML_ERROR_NO_MEMORY;
+        assert(dtd->scaffIndex != NULL);
         dtd->scaffIndex[dtd->scaffLevel] = myindex;
         dtd->scaffLevel++;
         dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
@@ -5024,10 +4806,9 @@
       if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
         return XML_ERROR_SYNTAX;
       if (dtd->in_eldecl
-          && !parser->m_groupConnector[parser->m_prologState.level]
+          && ! parser->m_groupConnector[parser->m_prologState.level]
           && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
-              != XML_CTYPE_MIXED)
-          ) {
+              != XML_CTYPE_MIXED)) {
         dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
             = XML_CTYPE_CHOICE;
         if (parser->m_elementDeclHandler)
@@ -5039,15 +4820,14 @@
 #ifdef XML_DTD
     case XML_ROLE_INNER_PARAM_ENTITY_REF:
       dtd->hasParamEntityRefs = XML_TRUE;
-      if (!parser->m_paramEntityParsing)
+      if (! parser->m_paramEntityParsing)
         dtd->keepProcessing = dtd->standalone;
       else {
         const XML_Char *name;
         ENTITY *entity;
-        name = poolStoreString(&dtd->pool, enc,
-                                s + enc->minBytesPerChar,
-                                next - enc->minBytesPerChar);
-        if (!name)
+        name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
+                               next - enc->minBytesPerChar);
+        if (! name)
           return XML_ERROR_NO_MEMORY;
         entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
         poolDiscard(&dtd->pool);
@@ -5055,13 +4835,12 @@
            if yes, check that the entity exists, and that it is internal,
            otherwise call the skipped entity handler
         */
-        if (parser->m_prologState.documentEntity &&
-            (dtd->standalone
-             ? !parser->m_openInternalEntities
-             : !dtd->hasParamEntityRefs)) {
-          if (!entity)
+        if (parser->m_prologState.documentEntity
+            && (dtd->standalone ? ! parser->m_openInternalEntities
+                                : ! dtd->hasParamEntityRefs)) {
+          if (! entity)
             return XML_ERROR_UNDEFINED_ENTITY;
-          else if (!entity->is_internal) {
+          else if (! entity->is_internal) {
             /* It's hard to exhaustively search the code to be sure,
              * but there doesn't seem to be a way of executing the
              * following line.  There are two cases:
@@ -5084,11 +4863,11 @@
              */
             return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
           }
-        }
-        else if (!entity) {
+        } else if (! entity) {
           dtd->keepProcessing = dtd->standalone;
           /* cannot report skipped entities in declarations */
-          if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) {
+          if ((role == XML_ROLE_PARAM_ENTITY_REF)
+              && parser->m_skippedEntityHandler) {
             parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
             handleDefault = XML_FALSE;
           }
@@ -5098,8 +4877,8 @@
           return XML_ERROR_RECURSIVE_ENTITY_REF;
         if (entity->textPtr) {
           enum XML_Error result;
-          XML_Bool betweenDecl =
-            (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
+          XML_Bool betweenDecl
+              = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
           result = processInternalEntity(parser, entity, betweenDecl);
           if (result != XML_ERROR_NONE)
             return result;
@@ -5109,39 +4888,35 @@
         if (parser->m_externalEntityRefHandler) {
           dtd->paramEntityRead = XML_FALSE;
           entity->open = XML_TRUE;
-          if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
-                                        0,
-                                        entity->base,
-                                        entity->systemId,
-                                        entity->publicId)) {
+          if (! parser->m_externalEntityRefHandler(
+                  parser->m_externalEntityRefHandlerArg, 0, entity->base,
+                  entity->systemId, entity->publicId)) {
             entity->open = XML_FALSE;
             return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
           }
           entity->open = XML_FALSE;
           handleDefault = XML_FALSE;
-          if (!dtd->paramEntityRead) {
+          if (! dtd->paramEntityRead) {
             dtd->keepProcessing = dtd->standalone;
             break;
           }
-        }
-        else {
+        } else {
           dtd->keepProcessing = dtd->standalone;
           break;
         }
       }
 #endif /* XML_DTD */
-      if (!dtd->standalone &&
-          parser->m_notStandaloneHandler &&
-          !parser->m_notStandaloneHandler(parser->m_handlerArg))
+      if (! dtd->standalone && parser->m_notStandaloneHandler
+          && ! parser->m_notStandaloneHandler(parser->m_handlerArg))
         return XML_ERROR_NOT_STANDALONE;
       break;
 
-    /* Element declaration stuff */
+      /* Element declaration stuff */
 
     case XML_ROLE_ELEMENT_NAME:
       if (parser->m_elementDeclHandler) {
         parser->m_declElementType = getElementType(parser, enc, s, next);
-        if (!parser->m_declElementType)
+        if (! parser->m_declElementType)
           return XML_ERROR_NO_MEMORY;
         dtd->scaffLevel = 0;
         dtd->scaffCount = 0;
@@ -5154,18 +4929,19 @@
     case XML_ROLE_CONTENT_EMPTY:
       if (dtd->in_eldecl) {
         if (parser->m_elementDeclHandler) {
-          XML_Content * content = (XML_Content *) MALLOC(parser, sizeof(XML_Content));
-          if (!content)
+          XML_Content *content
+              = (XML_Content *)MALLOC(parser, sizeof(XML_Content));
+          if (! content)
             return XML_ERROR_NO_MEMORY;
           content->quant = XML_CQUANT_NONE;
           content->name = NULL;
           content->numchildren = 0;
           content->children = NULL;
-          content->type = ((role == XML_ROLE_CONTENT_ANY) ?
-                           XML_CTYPE_ANY :
-                           XML_CTYPE_EMPTY);
+          content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY
+                                                          : XML_CTYPE_EMPTY);
           *eventEndPP = s;
-          parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, content);
+          parser->m_elementDeclHandler(
+              parser->m_handlerArg, parser->m_declElementType->name, content);
           handleDefault = XML_FALSE;
         }
         dtd->in_eldecl = XML_FALSE;
@@ -5197,22 +4973,22 @@
         ELEMENT_TYPE *el;
         const XML_Char *name;
         int nameLen;
-        const char *nxt = (quant == XML_CQUANT_NONE
-                           ? next
-                           : next - enc->minBytesPerChar);
+        const char *nxt
+            = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
         int myindex = nextScaffoldPart(parser);
         if (myindex < 0)
           return XML_ERROR_NO_MEMORY;
         dtd->scaffold[myindex].type = XML_CTYPE_NAME;
         dtd->scaffold[myindex].quant = quant;
         el = getElementType(parser, enc, s, nxt);
-        if (!el)
+        if (! el)
           return XML_ERROR_NO_MEMORY;
         name = el->name;
         dtd->scaffold[myindex].name = name;
         nameLen = 0;
-        for (; name[nameLen++]; );
-        dtd->contentStringLen +=  nameLen;
+        for (; name[nameLen++];)
+          ;
+        dtd->contentStringLen += nameLen;
         if (parser->m_elementDeclHandler)
           handleDefault = XML_FALSE;
       }
@@ -5236,12 +5012,13 @@
         dtd->scaffLevel--;
         dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
         if (dtd->scaffLevel == 0) {
-          if (!handleDefault) {
+          if (! handleDefault) {
             XML_Content *model = build_model(parser);
-            if (!model)
+            if (! model)
               return XML_ERROR_NO_MEMORY;
             *eventEndPP = s;
-            parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, model);
+            parser->m_elementDeclHandler(
+                parser->m_handlerArg, parser->m_declElementType->name, model);
           }
           dtd->in_eldecl = XML_FALSE;
           dtd->contentStringLen = 0;
@@ -5251,12 +5028,12 @@
       /* End element declaration stuff */
 
     case XML_ROLE_PI:
-      if (!reportProcessingInstruction(parser, enc, s, next))
+      if (! reportProcessingInstruction(parser, enc, s, next))
         return XML_ERROR_NO_MEMORY;
       handleDefault = XML_FALSE;
       break;
     case XML_ROLE_COMMENT:
-      if (!reportComment(parser, enc, s, next))
+      if (! reportComment(parser, enc, s, next))
         return XML_ERROR_NO_MEMORY;
       handleDefault = XML_FALSE;
       break;
@@ -5307,11 +5084,8 @@
 }
 
 static enum XML_Error PTRCALL
-epilogProcessor(XML_Parser parser,
-                const char *s,
-                const char *end,
-                const char **nextPtr)
-{
+epilogProcessor(XML_Parser parser, const char *s, const char *end,
+                const char **nextPtr) {
   parser->m_processor = epilogProcessor;
   parser->m_eventPtr = s;
   for (;;) {
@@ -5336,24 +5110,24 @@
         reportDefault(parser, parser->m_encoding, s, next);
       break;
     case XML_TOK_PI:
-      if (!reportProcessingInstruction(parser, parser->m_encoding, s, next))
+      if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))
         return XML_ERROR_NO_MEMORY;
       break;
     case XML_TOK_COMMENT:
-      if (!reportComment(parser, parser->m_encoding, s, next))
+      if (! reportComment(parser, parser->m_encoding, s, next))
         return XML_ERROR_NO_MEMORY;
       break;
     case XML_TOK_INVALID:
       parser->m_eventPtr = next;
       return XML_ERROR_INVALID_TOKEN;
     case XML_TOK_PARTIAL:
-      if (!parser->m_parsingStatus.finalBuffer) {
+      if (! parser->m_parsingStatus.finalBuffer) {
         *nextPtr = s;
         return XML_ERROR_NONE;
       }
       return XML_ERROR_UNCLOSED_TOKEN;
     case XML_TOK_PARTIAL_CHAR:
-      if (!parser->m_parsingStatus.finalBuffer) {
+      if (! parser->m_parsingStatus.finalBuffer) {
         *nextPtr = s;
         return XML_ERROR_NONE;
       }
@@ -5368,15 +5142,13 @@
       return XML_ERROR_NONE;
     case XML_FINISHED:
       return XML_ERROR_ABORTED;
-    default: ;
+    default:;
     }
   }
 }
 
 static enum XML_Error
-processInternalEntity(XML_Parser parser, ENTITY *entity,
-                      XML_Bool betweenDecl)
-{
+processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
   const char *textStart, *textEnd;
   const char *next;
   enum XML_Error result;
@@ -5385,10 +5157,10 @@
   if (parser->m_freeInternalEntities) {
     openEntity = parser->m_freeInternalEntities;
     parser->m_freeInternalEntities = openEntity->next;
-  }
-  else {
-    openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
-    if (!openEntity)
+  } else {
+    openEntity
+        = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
+    if (! openEntity)
       return XML_ERROR_NO_MEMORY;
   }
   entity->open = XML_TRUE;
@@ -5407,21 +5179,20 @@
 
 #ifdef XML_DTD
   if (entity->is_param) {
-    int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
-    result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
-                      next, &next, XML_FALSE);
-  }
-  else
+    int tok
+        = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
+    result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
+                      tok, next, &next, XML_FALSE, XML_FALSE);
+  } else
 #endif /* XML_DTD */
-    result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart,
-                       textEnd, &next, XML_FALSE);
+    result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
+                       textStart, textEnd, &next, XML_FALSE);
 
   if (result == XML_ERROR_NONE) {
     if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
       entity->processed = (int)(next - textStart);
       parser->m_processor = internalEntityProcessor;
-    }
-    else {
+    } else {
       entity->open = XML_FALSE;
       parser->m_openInternalEntities = openEntity->next;
       /* put openEntity back in list of free instances */
@@ -5433,17 +5204,14 @@
 }
 
 static enum XML_Error PTRCALL
-internalEntityProcessor(XML_Parser parser,
-                        const char *s,
-                        const char *end,
-                        const char **nextPtr)
-{
+internalEntityProcessor(XML_Parser parser, const char *s, const char *end,
+                        const char **nextPtr) {
   ENTITY *entity;
   const char *textStart, *textEnd;
   const char *next;
   enum XML_Error result;
   OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
-  if (!openEntity)
+  if (! openEntity)
     return XML_ERROR_UNEXPECTED_STATE;
 
   entity = openEntity->entity;
@@ -5454,22 +5222,23 @@
 
 #ifdef XML_DTD
   if (entity->is_param) {
-    int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
-    result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
-                      next, &next, XML_FALSE);
-  }
-  else
+    int tok
+        = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
+    result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
+                      tok, next, &next, XML_FALSE, XML_TRUE);
+  } else
 #endif /* XML_DTD */
-    result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding,
-                       textStart, textEnd, &next, XML_FALSE);
+    result = doContent(parser, openEntity->startTagLevel,
+                       parser->m_internalEncoding, textStart, textEnd, &next,
+                       XML_FALSE);
 
   if (result != XML_ERROR_NONE)
     return result;
-  else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
+  else if (textEnd != next
+           && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
     entity->processed = (int)(next - (char *)entity->textPtr);
     return result;
-  }
-  else {
+  } else {
     entity->open = XML_FALSE;
     parser->m_openInternalEntities = openEntity->next;
     /* put openEntity back in list of free instances */
@@ -5483,49 +5252,45 @@
     parser->m_processor = prologProcessor;
     tok = XmlPrologTok(parser->m_encoding, s, end, &next);
     return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
-                    (XML_Bool)!parser->m_parsingStatus.finalBuffer);
-  }
-  else
+                    (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE);
+  } else
 #endif /* XML_DTD */
   {
     parser->m_processor = contentProcessor;
     /* see externalEntityContentProcessor vs contentProcessor */
-    return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end,
-                     nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
+    return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding,
+                     s, end, nextPtr,
+                     (XML_Bool)! parser->m_parsingStatus.finalBuffer);
   }
 }
 
 static enum XML_Error PTRCALL
-errorProcessor(XML_Parser parser,
-               const char *UNUSED_P(s),
-               const char *UNUSED_P(end),
-               const char **UNUSED_P(nextPtr))
-{
+errorProcessor(XML_Parser parser, const char *s, const char *end,
+               const char **nextPtr) {
+  UNUSED_P(s);
+  UNUSED_P(end);
+  UNUSED_P(nextPtr);
   return parser->m_errorCode;
 }
 
 static enum XML_Error
 storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
-                    const char *ptr, const char *end,
-                    STRING_POOL *pool)
-{
-  enum XML_Error result = appendAttributeValue(parser, enc, isCdata, ptr,
-                                               end, pool);
+                    const char *ptr, const char *end, STRING_POOL *pool) {
+  enum XML_Error result
+      = appendAttributeValue(parser, enc, isCdata, ptr, end, pool);
   if (result)
     return result;
-  if (!isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
+  if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)
     poolChop(pool);
-  if (!poolAppendChar(pool, XML_T('\0')))
+  if (! poolAppendChar(pool, XML_T('\0')))
     return XML_ERROR_NO_MEMORY;
   return XML_ERROR_NONE;
 }
 
 static enum XML_Error
 appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
-                     const char *ptr, const char *end,
-                     STRING_POOL *pool)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+                     const char *ptr, const char *end, STRING_POOL *pool) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   for (;;) {
     const char *next;
     int tok = XmlAttributeValueTok(enc, ptr, end, &next);
@@ -5540,38 +5305,35 @@
       if (enc == parser->m_encoding)
         parser->m_eventPtr = ptr;
       return XML_ERROR_INVALID_TOKEN;
-    case XML_TOK_CHAR_REF:
-      {
-        XML_Char buf[XML_ENCODE_MAX];
-        int i;
-        int n = XmlCharRefNumber(enc, ptr);
-        if (n < 0) {
-          if (enc == parser->m_encoding)
-            parser->m_eventPtr = ptr;
-          return XML_ERROR_BAD_CHAR_REF;
-        }
-        if (!isCdata
-            && n == 0x20 /* space */
-            && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
-          break;
-        n = XmlEncode(n, (ICHAR *)buf);
-        /* The XmlEncode() functions can never return 0 here.  That
-         * error return happens if the code point passed in is either
-         * negative or greater than or equal to 0x110000.  The
-         * XmlCharRefNumber() functions will all return a number
-         * strictly less than 0x110000 or a negative value if an error
-         * occurred.  The negative value is intercepted above, so
-         * XmlEncode() is never passed a value it might return an
-         * error for.
-         */
-        for (i = 0; i < n; i++) {
-          if (!poolAppendChar(pool, buf[i]))
-            return XML_ERROR_NO_MEMORY;
-        }
+    case XML_TOK_CHAR_REF: {
+      XML_Char buf[XML_ENCODE_MAX];
+      int i;
+      int n = XmlCharRefNumber(enc, ptr);
+      if (n < 0) {
+        if (enc == parser->m_encoding)
+          parser->m_eventPtr = ptr;
+        return XML_ERROR_BAD_CHAR_REF;
       }
-      break;
+      if (! isCdata && n == 0x20 /* space */
+          && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
+        break;
+      n = XmlEncode(n, (ICHAR *)buf);
+      /* The XmlEncode() functions can never return 0 here.  That
+       * error return happens if the code point passed in is either
+       * negative or greater than or equal to 0x110000.  The
+       * XmlCharRefNumber() functions will all return a number
+       * strictly less than 0x110000 or a negative value if an error
+       * occurred.  The negative value is intercepted above, so
+       * XmlEncode() is never passed a value it might return an
+       * error for.
+       */
+      for (i = 0; i < n; i++) {
+        if (! poolAppendChar(pool, buf[i]))
+          return XML_ERROR_NO_MEMORY;
+      }
+    } break;
     case XML_TOK_DATA_CHARS:
-      if (!poolAppend(pool, enc, ptr, next))
+      if (! poolAppend(pool, enc, ptr, next))
         return XML_ERROR_NO_MEMORY;
       break;
     case XML_TOK_TRAILING_CR:
@@ -5579,109 +5341,103 @@
       /* fall through */
     case XML_TOK_ATTRIBUTE_VALUE_S:
     case XML_TOK_DATA_NEWLINE:
-      if (!isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
+      if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
         break;
-      if (!poolAppendChar(pool, 0x20))
+      if (! poolAppendChar(pool, 0x20))
         return XML_ERROR_NO_MEMORY;
       break;
-    case XML_TOK_ENTITY_REF:
-      {
-        const XML_Char *name;
-        ENTITY *entity;
-        char checkEntityDecl;
-        XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc,
-                                              ptr + enc->minBytesPerChar,
-                                              next - enc->minBytesPerChar);
-        if (ch) {
-          if (!poolAppendChar(pool, ch))
-                return XML_ERROR_NO_MEMORY;
-          break;
-        }
-        name = poolStoreString(&parser->m_temp2Pool, enc,
-                               ptr + enc->minBytesPerChar,
-                               next - enc->minBytesPerChar);
-        if (!name)
+    case XML_TOK_ENTITY_REF: {
+      const XML_Char *name;
+      ENTITY *entity;
+      char checkEntityDecl;
+      XML_Char ch = (XML_Char)XmlPredefinedEntityName(
+          enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);
+      if (ch) {
+        if (! poolAppendChar(pool, ch))
           return XML_ERROR_NO_MEMORY;
-        entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
-        poolDiscard(&parser->m_temp2Pool);
-        /* First, determine if a check for an existing declaration is needed;
-           if yes, check that the entity exists, and that it is internal.
-        */
-        if (pool == &dtd->pool)  /* are we called from prolog? */
-          checkEntityDecl =
-#ifdef XML_DTD
-              parser->m_prologState.documentEntity &&
-#endif /* XML_DTD */
-              (dtd->standalone
-               ? !parser->m_openInternalEntities
-               : !dtd->hasParamEntityRefs);
-        else /* if (pool == &parser->m_tempPool): we are called from content */
-          checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone;
-        if (checkEntityDecl) {
-          if (!entity)
-            return XML_ERROR_UNDEFINED_ENTITY;
-          else if (!entity->is_internal)
-            return XML_ERROR_ENTITY_DECLARED_IN_PE;
-        }
-        else if (!entity) {
-          /* Cannot report skipped entity here - see comments on
-             parser->m_skippedEntityHandler.
-          if (parser->m_skippedEntityHandler)
-            parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
-          */
-          /* Cannot call the default handler because this would be
-             out of sync with the call to the startElementHandler.
-          if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
-            reportDefault(parser, enc, ptr, next);
-          */
-          break;
-        }
-        if (entity->open) {
-          if (enc == parser->m_encoding) {
-            /* It does not appear that this line can be executed.
-             *
-             * The "if (entity->open)" check catches recursive entity
-             * definitions.  In order to be called with an open
-             * entity, it must have gone through this code before and
-             * been through the recursive call to
-             * appendAttributeValue() some lines below.  That call
-             * sets the local encoding ("enc") to the parser's
-             * internal encoding (internal_utf8 or internal_utf16),
-             * which can never be the same as the principle encoding.
-             * It doesn't appear there is another code path that gets
-             * here with entity->open being TRUE.
-             *
-             * Since it is not certain that this logic is watertight,
-             * we keep the line and merely exclude it from coverage
-             * tests.
-             */
-            parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
-          }
-          return XML_ERROR_RECURSIVE_ENTITY_REF;
-        }
-        if (entity->notation) {
-          if (enc == parser->m_encoding)
-            parser->m_eventPtr = ptr;
-          return XML_ERROR_BINARY_ENTITY_REF;
-        }
-        if (!entity->textPtr) {
-          if (enc == parser->m_encoding)
-            parser->m_eventPtr = ptr;
-          return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
-        }
-        else {
-          enum XML_Error result;
-          const XML_Char *textEnd = entity->textPtr + entity->textLen;
-          entity->open = XML_TRUE;
-          result = appendAttributeValue(parser, parser->m_internalEncoding, isCdata,
-                                        (char *)entity->textPtr,
-                                        (char *)textEnd, pool);
-          entity->open = XML_FALSE;
-          if (result)
-            return result;
-        }
+        break;
       }
-      break;
+      name = poolStoreString(&parser->m_temp2Pool, enc,
+                             ptr + enc->minBytesPerChar,
+                             next - enc->minBytesPerChar);
+      if (! name)
+        return XML_ERROR_NO_MEMORY;
+      entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
+      poolDiscard(&parser->m_temp2Pool);
+      /* First, determine if a check for an existing declaration is needed;
+         if yes, check that the entity exists, and that it is internal.
+      */
+      if (pool == &dtd->pool) /* are we called from prolog? */
+        checkEntityDecl =
+#ifdef XML_DTD
+            parser->m_prologState.documentEntity &&
+#endif /* XML_DTD */
+            (dtd->standalone ? ! parser->m_openInternalEntities
+                             : ! dtd->hasParamEntityRefs);
+      else /* if (pool == &parser->m_tempPool): we are called from content */
+        checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;
+      if (checkEntityDecl) {
+        if (! entity)
+          return XML_ERROR_UNDEFINED_ENTITY;
+        else if (! entity->is_internal)
+          return XML_ERROR_ENTITY_DECLARED_IN_PE;
+      } else if (! entity) {
+        /* Cannot report skipped entity here - see comments on
+           parser->m_skippedEntityHandler.
+        if (parser->m_skippedEntityHandler)
+          parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
+        */
+        /* Cannot call the default handler because this would be
+           out of sync with the call to the startElementHandler.
+        if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
+          reportDefault(parser, enc, ptr, next);
+        */
+        break;
+      }
+      if (entity->open) {
+        if (enc == parser->m_encoding) {
+          /* It does not appear that this line can be executed.
+           *
+           * The "if (entity->open)" check catches recursive entity
+           * definitions.  In order to be called with an open
+           * entity, it must have gone through this code before and
+           * been through the recursive call to
+           * appendAttributeValue() some lines below.  That call
+           * sets the local encoding ("enc") to the parser's
+           * internal encoding (internal_utf8 or internal_utf16),
+           * which can never be the same as the principle encoding.
+           * It doesn't appear there is another code path that gets
+           * here with entity->open being TRUE.
+           *
+           * Since it is not certain that this logic is watertight,
+           * we keep the line and merely exclude it from coverage
+           * tests.
+           */
+          parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
+        }
+        return XML_ERROR_RECURSIVE_ENTITY_REF;
+      }
+      if (entity->notation) {
+        if (enc == parser->m_encoding)
+          parser->m_eventPtr = ptr;
+        return XML_ERROR_BINARY_ENTITY_REF;
+      }
+      if (! entity->textPtr) {
+        if (enc == parser->m_encoding)
+          parser->m_eventPtr = ptr;
+        return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
+      } else {
+        enum XML_Error result;
+        const XML_Char *textEnd = entity->textPtr + entity->textLen;
+        entity->open = XML_TRUE;
+        result = appendAttributeValue(parser, parser->m_internalEncoding,
+                                      isCdata, (char *)entity->textPtr,
+                                      (char *)textEnd, pool);
+        entity->open = XML_FALSE;
+        if (result)
+          return result;
+      }
+    } break;
     default:
       /* The only token returned by XmlAttributeValueTok() that does
        * not have an explicit case here is XML_TOK_PARTIAL_CHAR.
@@ -5705,12 +5461,9 @@
 }
 
 static enum XML_Error
-storeEntityValue(XML_Parser parser,
-                 const ENCODING *enc,
-                 const char *entityTextPtr,
-                 const char *entityTextEnd)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+storeEntityValue(XML_Parser parser, const ENCODING *enc,
+                 const char *entityTextPtr, const char *entityTextEnd) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   STRING_POOL *pool = &(dtd->entityValuePool);
   enum XML_Error result = XML_ERROR_NONE;
 #ifdef XML_DTD
@@ -5720,8 +5473,8 @@
   /* never return Null for the value argument in EntityDeclHandler,
      since this would indicate an external entity; therefore we
      have to make sure that entityValuePool.start is not null */
-  if (!pool->blocks) {
-    if (!poolGrow(pool))
+  if (! pool->blocks) {
+    if (! poolGrow(pool))
       return XML_ERROR_NO_MEMORY;
   }
 
@@ -5737,13 +5490,13 @@
         name = poolStoreString(&parser->m_tempPool, enc,
                                entityTextPtr + enc->minBytesPerChar,
                                next - enc->minBytesPerChar);
-        if (!name) {
+        if (! name) {
           result = XML_ERROR_NO_MEMORY;
           goto endEntityValue;
         }
         entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
         poolDiscard(&parser->m_tempPool);
-        if (!entity) {
+        if (! entity) {
           /* not a well-formedness error - see XML 1.0: WFC Entity Declared */
           /* cannot report skipped entity here - see comments on
              parser->m_skippedEntityHandler
@@ -5763,29 +5516,23 @@
           if (parser->m_externalEntityRefHandler) {
             dtd->paramEntityRead = XML_FALSE;
             entity->open = XML_TRUE;
-            if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
-                                          0,
-                                          entity->base,
-                                          entity->systemId,
-                                          entity->publicId)) {
+            if (! parser->m_externalEntityRefHandler(
+                    parser->m_externalEntityRefHandlerArg, 0, entity->base,
+                    entity->systemId, entity->publicId)) {
               entity->open = XML_FALSE;
               result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;
               goto endEntityValue;
             }
             entity->open = XML_FALSE;
-            if (!dtd->paramEntityRead)
+            if (! dtd->paramEntityRead)
               dtd->keepProcessing = dtd->standalone;
-          }
-          else
+          } else
             dtd->keepProcessing = dtd->standalone;
-        }
-        else {
+        } else {
           entity->open = XML_TRUE;
-          result = storeEntityValue(parser,
-                                    parser->m_internalEncoding,
-                                    (char *)entity->textPtr,
-                                    (char *)(entity->textPtr
-                                             + entity->textLen));
+          result = storeEntityValue(
+              parser, parser->m_internalEncoding, (char *)entity->textPtr,
+              (char *)(entity->textPtr + entity->textLen));
           entity->open = XML_FALSE;
           if (result)
             goto endEntityValue;
@@ -5803,7 +5550,7 @@
       goto endEntityValue;
     case XML_TOK_ENTITY_REF:
     case XML_TOK_DATA_CHARS:
-      if (!poolAppend(pool, enc, entityTextPtr, next)) {
+      if (! poolAppend(pool, enc, entityTextPtr, next)) {
         result = XML_ERROR_NO_MEMORY;
         goto endEntityValue;
       }
@@ -5812,42 +5559,40 @@
       next = entityTextPtr + enc->minBytesPerChar;
       /* fall through */
     case XML_TOK_DATA_NEWLINE:
-      if (pool->end == pool->ptr && !poolGrow(pool)) {
-              result = XML_ERROR_NO_MEMORY;
+      if (pool->end == pool->ptr && ! poolGrow(pool)) {
+        result = XML_ERROR_NO_MEMORY;
         goto endEntityValue;
       }
       *(pool->ptr)++ = 0xA;
       break;
-    case XML_TOK_CHAR_REF:
-      {
-        XML_Char buf[XML_ENCODE_MAX];
-        int i;
-        int n = XmlCharRefNumber(enc, entityTextPtr);
-        if (n < 0) {
-          if (enc == parser->m_encoding)
-            parser->m_eventPtr = entityTextPtr;
-          result = XML_ERROR_BAD_CHAR_REF;
+    case XML_TOK_CHAR_REF: {
+      XML_Char buf[XML_ENCODE_MAX];
+      int i;
+      int n = XmlCharRefNumber(enc, entityTextPtr);
+      if (n < 0) {
+        if (enc == parser->m_encoding)
+          parser->m_eventPtr = entityTextPtr;
+        result = XML_ERROR_BAD_CHAR_REF;
+        goto endEntityValue;
+      }
+      n = XmlEncode(n, (ICHAR *)buf);
+      /* The XmlEncode() functions can never return 0 here.  That
+       * error return happens if the code point passed in is either
+       * negative or greater than or equal to 0x110000.  The
+       * XmlCharRefNumber() functions will all return a number
+       * strictly less than 0x110000 or a negative value if an error
+       * occurred.  The negative value is intercepted above, so
+       * XmlEncode() is never passed a value it might return an
+       * error for.
+       */
+      for (i = 0; i < n; i++) {
+        if (pool->end == pool->ptr && ! poolGrow(pool)) {
+          result = XML_ERROR_NO_MEMORY;
           goto endEntityValue;
         }
-        n = XmlEncode(n, (ICHAR *)buf);
-        /* The XmlEncode() functions can never return 0 here.  That
-         * error return happens if the code point passed in is either
-         * negative or greater than or equal to 0x110000.  The
-         * XmlCharRefNumber() functions will all return a number
-         * strictly less than 0x110000 or a negative value if an error
-         * occurred.  The negative value is intercepted above, so
-         * XmlEncode() is never passed a value it might return an
-         * error for.
-         */
-        for (i = 0; i < n; i++) {
-          if (pool->end == pool->ptr && !poolGrow(pool)) {
-            result = XML_ERROR_NO_MEMORY;
-            goto endEntityValue;
-          }
-          *(pool->ptr)++ = buf[i];
-        }
+        *(pool->ptr)++ = buf[i];
       }
-      break;
+    } break;
     case XML_TOK_PARTIAL:
       if (enc == parser->m_encoding)
         parser->m_eventPtr = entityTextPtr;
@@ -5882,8 +5627,7 @@
 }
 
 static void FASTCALL
-normalizeLines(XML_Char *s)
-{
+normalizeLines(XML_Char *s) {
   XML_Char *p;
   for (;; s++) {
     if (*s == XML_T('\0'))
@@ -5897,8 +5641,7 @@
       *p++ = 0xA;
       if (*++s == 0xA)
         s++;
-    }
-    else
+    } else
       *p++ = *s++;
   } while (*s);
   *p = XML_T('\0');
@@ -5906,12 +5649,11 @@
 
 static int
 reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
-                            const char *start, const char *end)
-{
+                            const char *start, const char *end) {
   const XML_Char *target;
   XML_Char *data;
   const char *tem;
-  if (!parser->m_processingInstructionHandler) {
+  if (! parser->m_processingInstructionHandler) {
     if (parser->m_defaultHandler)
       reportDefault(parser, enc, start, end);
     return 1;
@@ -5919,13 +5661,12 @@
   start += enc->minBytesPerChar * 2;
   tem = start + XmlNameLength(enc, start);
   target = poolStoreString(&parser->m_tempPool, enc, start, tem);
-  if (!target)
+  if (! target)
     return 0;
   poolFinish(&parser->m_tempPool);
-  data = poolStoreString(&parser->m_tempPool, enc,
-                        XmlSkipS(enc, tem),
-                        end - enc->minBytesPerChar*2);
-  if (!data)
+  data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),
+                         end - enc->minBytesPerChar * 2);
+  if (! data)
     return 0;
   normalizeLines(data);
   parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
@@ -5934,20 +5675,18 @@
 }
 
 static int
-reportComment(XML_Parser parser, const ENCODING *enc,
-              const char *start, const char *end)
-{
+reportComment(XML_Parser parser, const ENCODING *enc, const char *start,
+              const char *end) {
   XML_Char *data;
-  if (!parser->m_commentHandler) {
+  if (! parser->m_commentHandler) {
     if (parser->m_defaultHandler)
       reportDefault(parser, enc, start, end);
     return 1;
   }
-  data = poolStoreString(&parser->m_tempPool,
-                         enc,
+  data = poolStoreString(&parser->m_tempPool, enc,
                          start + enc->minBytesPerChar * 4,
                          end - enc->minBytesPerChar * 3);
-  if (!data)
+  if (! data)
     return 0;
   normalizeLines(data);
   parser->m_commentHandler(parser->m_handlerArg, data);
@@ -5956,9 +5695,8 @@
 }
 
 static void
-reportDefault(XML_Parser parser, const ENCODING *enc,
-              const char *s, const char *end)
-{
+reportDefault(XML_Parser parser, const ENCODING *enc, const char *s,
+              const char *end) {
   if (MUST_CONVERT(enc, s)) {
     enum XML_Convert_Result convert_res;
     const char **eventPP;
@@ -5966,8 +5704,7 @@
     if (enc == parser->m_encoding) {
       eventPP = &parser->m_eventPtr;
       eventEndPP = &parser->m_eventEndPtr;
-    }
-    else {
+    } else {
       /* To get here, two things must be true; the parser must be
        * using a character encoding that is not the same as the
        * encoding passed in, and the encoding passed in must need
@@ -5990,21 +5727,22 @@
     }
     do {
       ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
-      convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
+      convert_res
+          = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
       *eventEndPP = s;
-      parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf, (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
+      parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,
+                               (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
       *eventPP = s;
-    } while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
-  }
-  else
-    parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
+    } while ((convert_res != XML_CONVERT_COMPLETED)
+             && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
+  } else
+    parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s,
+                             (int)((XML_Char *)end - (XML_Char *)s));
 }
 
-
 static int
 defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
-                XML_Bool isId, const XML_Char *value, XML_Parser parser)
-{
+                XML_Bool isId, const XML_Char *value, XML_Parser parser) {
   DEFAULT_ATTRIBUTE *att;
   if (value || isId) {
     /* The handling of default attributes gets messed up if we have
@@ -6013,24 +5751,23 @@
     for (i = 0; i < type->nDefaultAtts; i++)
       if (attId == type->defaultAtts[i].id)
         return 1;
-    if (isId && !type->idAtt && !attId->xmlns)
+    if (isId && ! type->idAtt && ! attId->xmlns)
       type->idAtt = attId;
   }
   if (type->nDefaultAtts == type->allocDefaultAtts) {
     if (type->allocDefaultAtts == 0) {
       type->allocDefaultAtts = 8;
-      type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(parser, type->allocDefaultAtts
-                            * sizeof(DEFAULT_ATTRIBUTE));
-      if (!type->defaultAtts) {
+      type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(
+          parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
+      if (! type->defaultAtts) {
         type->allocDefaultAtts = 0;
         return 0;
       }
-    }
-    else {
+    } else {
       DEFAULT_ATTRIBUTE *temp;
       int count = type->allocDefaultAtts * 2;
-      temp = (DEFAULT_ATTRIBUTE *)
-        REALLOC(parser, type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
+      temp = (DEFAULT_ATTRIBUTE *)REALLOC(parser, type->defaultAtts,
+                                          (count * sizeof(DEFAULT_ATTRIBUTE)));
       if (temp == NULL)
         return 0;
       type->allocDefaultAtts = count;
@@ -6041,92 +5778,89 @@
   att->id = attId;
   att->value = value;
   att->isCdata = isCdata;
-  if (!isCdata)
+  if (! isCdata)
     attId->maybeTokenized = XML_TRUE;
   type->nDefaultAtts += 1;
   return 1;
 }
 
 static int
-setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   const XML_Char *name;
   for (name = elementType->name; *name; name++) {
     if (*name == XML_T(ASCII_COLON)) {
       PREFIX *prefix;
       const XML_Char *s;
       for (s = elementType->name; s != name; s++) {
-        if (!poolAppendChar(&dtd->pool, *s))
+        if (! poolAppendChar(&dtd->pool, *s))
           return 0;
       }
-      if (!poolAppendChar(&dtd->pool, XML_T('\0')))
+      if (! poolAppendChar(&dtd->pool, XML_T('\0')))
         return 0;
       prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
                                 sizeof(PREFIX));
-      if (!prefix)
+      if (! prefix)
         return 0;
       if (prefix->name == poolStart(&dtd->pool))
         poolFinish(&dtd->pool);
       else
         poolDiscard(&dtd->pool);
       elementType->prefix = prefix;
-
+      break;
     }
   }
   return 1;
 }
 
 static ATTRIBUTE_ID *
-getAttributeId(XML_Parser parser, const ENCODING *enc,
-               const char *start, const char *end)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,
+               const char *end) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   ATTRIBUTE_ID *id;
   const XML_Char *name;
-  if (!poolAppendChar(&dtd->pool, XML_T('\0')))
+  if (! poolAppendChar(&dtd->pool, XML_T('\0')))
     return NULL;
   name = poolStoreString(&dtd->pool, enc, start, end);
-  if (!name)
+  if (! name)
     return NULL;
   /* skip quotation mark - its storage will be re-used (like in name[-1]) */
   ++name;
-  id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name, sizeof(ATTRIBUTE_ID));
-  if (!id)
+  id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,
+                              sizeof(ATTRIBUTE_ID));
+  if (! id)
     return NULL;
   if (id->name != name)
     poolDiscard(&dtd->pool);
   else {
     poolFinish(&dtd->pool);
-    if (!parser->m_ns)
+    if (! parser->m_ns)
       ;
-    else if (name[0] == XML_T(ASCII_x)
-        && name[1] == XML_T(ASCII_m)
-        && name[2] == XML_T(ASCII_l)
-        && name[3] == XML_T(ASCII_n)
-        && name[4] == XML_T(ASCII_s)
-        && (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
+    else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)
+             && name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)
+             && name[4] == XML_T(ASCII_s)
+             && (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) {
       if (name[5] == XML_T('\0'))
         id->prefix = &dtd->defaultPrefix;
       else
-        id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6, sizeof(PREFIX));
+        id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,
+                                      sizeof(PREFIX));
       id->xmlns = XML_TRUE;
-    }
-    else {
+    } else {
       int i;
       for (i = 0; name[i]; i++) {
         /* attributes without prefix are *not* in the default namespace */
         if (name[i] == XML_T(ASCII_COLON)) {
           int j;
           for (j = 0; j < i; j++) {
-            if (!poolAppendChar(&dtd->pool, name[j]))
+            if (! poolAppendChar(&dtd->pool, name[j]))
               return NULL;
           }
-          if (!poolAppendChar(&dtd->pool, XML_T('\0')))
+          if (! poolAppendChar(&dtd->pool, XML_T('\0')))
             return NULL;
-          id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),
-                                        sizeof(PREFIX));
-          if (!id->prefix)
+          id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,
+                                        poolStart(&dtd->pool), sizeof(PREFIX));
+          if (! id->prefix)
             return NULL;
           if (id->prefix->name == poolStart(&dtd->pool))
             poolFinish(&dtd->pool);
@@ -6143,22 +5877,22 @@
 #define CONTEXT_SEP XML_T(ASCII_FF)
 
 static const XML_Char *
-getContext(XML_Parser parser)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+getContext(XML_Parser parser) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   HASH_TABLE_ITER iter;
   XML_Bool needSep = XML_FALSE;
 
   if (dtd->defaultPrefix.binding) {
     int i;
     int len;
-    if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
+    if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
       return NULL;
     len = dtd->defaultPrefix.binding->uriLen;
     if (parser->m_namespaceSeparator)
       len--;
     for (i = 0; i < len; i++) {
-      if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) {
+      if (! poolAppendChar(&parser->m_tempPool,
+                           dtd->defaultPrefix.binding->uri[i])) {
         /* Because of memory caching, I don't believe this line can be
          * executed.
          *
@@ -6190,9 +5924,9 @@
     int len;
     const XML_Char *s;
     PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
-    if (!prefix)
+    if (! prefix)
       break;
-    if (!prefix->binding) {
+    if (! prefix->binding) {
       /* This test appears to be (justifiable) paranoia.  There does
        * not seem to be a way of injecting a prefix without a binding
        * that doesn't get errored long before this function is called.
@@ -6201,98 +5935,96 @@
        */
       continue; /* LCOV_EXCL_LINE */
     }
-    if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
+    if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
       return NULL;
     for (s = prefix->name; *s; s++)
-      if (!poolAppendChar(&parser->m_tempPool, *s))
+      if (! poolAppendChar(&parser->m_tempPool, *s))
         return NULL;
-    if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
+    if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
       return NULL;
     len = prefix->binding->uriLen;
     if (parser->m_namespaceSeparator)
       len--;
     for (i = 0; i < len; i++)
-      if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
+      if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
         return NULL;
     needSep = XML_TRUE;
   }
 
-
   hashTableIterInit(&iter, &(dtd->generalEntities));
   for (;;) {
     const XML_Char *s;
     ENTITY *e = (ENTITY *)hashTableIterNext(&iter);
-    if (!e)
+    if (! e)
       break;
-    if (!e->open)
+    if (! e->open)
       continue;
-    if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
+    if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
       return NULL;
     for (s = e->name; *s; s++)
-      if (!poolAppendChar(&parser->m_tempPool, *s))
+      if (! poolAppendChar(&parser->m_tempPool, *s))
         return 0;
     needSep = XML_TRUE;
   }
 
-  if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
+  if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
     return NULL;
   return parser->m_tempPool.start;
 }
 
 static XML_Bool
-setContext(XML_Parser parser, const XML_Char *context)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+setContext(XML_Parser parser, const XML_Char *context) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   const XML_Char *s = context;
 
   while (*context != XML_T('\0')) {
     if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
       ENTITY *e;
-      if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
+      if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
         return XML_FALSE;
-      e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&parser->m_tempPool), 0);
+      e = (ENTITY *)lookup(parser, &dtd->generalEntities,
+                           poolStart(&parser->m_tempPool), 0);
       if (e)
         e->open = XML_TRUE;
       if (*s != XML_T('\0'))
         s++;
       context = s;
       poolDiscard(&parser->m_tempPool);
-    }
-    else if (*s == XML_T(ASCII_EQUALS)) {
+    } else if (*s == XML_T(ASCII_EQUALS)) {
       PREFIX *prefix;
       if (poolLength(&parser->m_tempPool) == 0)
         prefix = &dtd->defaultPrefix;
       else {
-        if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
+        if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
           return XML_FALSE;
-        prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&parser->m_tempPool),
-                                  sizeof(PREFIX));
-        if (!prefix)
+        prefix
+            = (PREFIX *)lookup(parser, &dtd->prefixes,
+                               poolStart(&parser->m_tempPool), sizeof(PREFIX));
+        if (! prefix)
           return XML_FALSE;
         if (prefix->name == poolStart(&parser->m_tempPool)) {
           prefix->name = poolCopyString(&dtd->pool, prefix->name);
-          if (!prefix->name)
+          if (! prefix->name)
             return XML_FALSE;
         }
         poolDiscard(&parser->m_tempPool);
       }
-      for (context = s + 1;
-           *context != CONTEXT_SEP && *context != XML_T('\0');
+      for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\0');
            context++)
-        if (!poolAppendChar(&parser->m_tempPool, *context))
+        if (! poolAppendChar(&parser->m_tempPool, *context))
           return XML_FALSE;
-      if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
+      if (! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
         return XML_FALSE;
       if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
-                     &parser->m_inheritedBindings) != XML_ERROR_NONE)
+                     &parser->m_inheritedBindings)
+          != XML_ERROR_NONE)
         return XML_FALSE;
       poolDiscard(&parser->m_tempPool);
       if (*context != XML_T('\0'))
         ++context;
       s = context;
-    }
-    else {
-      if (!poolAppendChar(&parser->m_tempPool, *s))
+    } else {
+      if (! poolAppendChar(&parser->m_tempPool, *s))
         return XML_FALSE;
       s++;
     }
@@ -6301,8 +6033,7 @@
 }
 
 static void FASTCALL
-normalizePublicId(XML_Char *publicId)
-{
+normalizePublicId(XML_Char *publicId) {
   XML_Char *p = publicId;
   XML_Char *s;
   for (s = publicId; *s; s++) {
@@ -6323,8 +6054,7 @@
 }
 
 static DTD *
-dtdCreate(const XML_Memory_Handling_Suite *ms)
-{
+dtdCreate(const XML_Memory_Handling_Suite *ms) {
   DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD));
   if (p == NULL)
     return p;
@@ -6356,13 +6086,12 @@
 }
 
 static void
-dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms)
-{
+dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms) {
   HASH_TABLE_ITER iter;
   hashTableIterInit(&iter, &(p->elementTypes));
   for (;;) {
     ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
-    if (!e)
+    if (! e)
       break;
     if (e->allocDefaultAtts != 0)
       ms->free_fcn(e->defaultAtts);
@@ -6398,13 +6127,12 @@
 }
 
 static void
-dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms)
-{
+dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms) {
   HASH_TABLE_ITER iter;
   hashTableIterInit(&iter, &(p->elementTypes));
   for (;;) {
     ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);
-    if (!e)
+    if (! e)
       break;
     if (e->allocDefaultAtts != 0)
       ms->free_fcn(e->defaultAtts);
@@ -6429,8 +6157,8 @@
    The new DTD has already been initialized.
 */
 static int
-dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms)
-{
+dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,
+        const XML_Memory_Handling_Suite *ms) {
   HASH_TABLE_ITER iter;
 
   /* Copy the prefix table. */
@@ -6439,12 +6167,12 @@
   for (;;) {
     const XML_Char *name;
     const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);
-    if (!oldP)
+    if (! oldP)
       break;
     name = poolCopyString(&(newDtd->pool), oldP->name);
-    if (!name)
+    if (! name)
       return 0;
-    if (!lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
+    if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))
       return 0;
   }
 
@@ -6457,18 +6185,18 @@
     const XML_Char *name;
     const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);
 
-    if (!oldA)
+    if (! oldA)
       break;
     /* Remember to allocate the scratch byte before the name. */
-    if (!poolAppendChar(&(newDtd->pool), XML_T('\0')))
+    if (! poolAppendChar(&(newDtd->pool), XML_T('\0')))
       return 0;
     name = poolCopyString(&(newDtd->pool), oldA->name);
-    if (!name)
+    if (! name)
       return 0;
     ++name;
     newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,
                                   sizeof(ATTRIBUTE_ID));
-    if (!newA)
+    if (! newA)
       return 0;
     newA->maybeTokenized = oldA->maybeTokenized;
     if (oldA->prefix) {
@@ -6490,57 +6218,52 @@
     ELEMENT_TYPE *newE;
     const XML_Char *name;
     const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);
-    if (!oldE)
+    if (! oldE)
       break;
     name = poolCopyString(&(newDtd->pool), oldE->name);
-    if (!name)
+    if (! name)
       return 0;
     newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,
                                   sizeof(ELEMENT_TYPE));
-    if (!newE)
+    if (! newE)
       return 0;
     if (oldE->nDefaultAtts) {
-      newE->defaultAtts = (DEFAULT_ATTRIBUTE *)
-          ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
-      if (!newE->defaultAtts) {
+      newE->defaultAtts = (DEFAULT_ATTRIBUTE *)ms->malloc_fcn(
+          oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));
+      if (! newE->defaultAtts) {
         return 0;
       }
     }
     if (oldE->idAtt)
-      newE->idAtt = (ATTRIBUTE_ID *)
-          lookup(oldParser, &(newDtd->attributeIds), oldE->idAtt->name, 0);
+      newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),
+                                           oldE->idAtt->name, 0);
     newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;
     if (oldE->prefix)
       newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),
                                       oldE->prefix->name, 0);
     for (i = 0; i < newE->nDefaultAtts; i++) {
-      newE->defaultAtts[i].id = (ATTRIBUTE_ID *)
-          lookup(oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
+      newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(
+          oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);
       newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;
       if (oldE->defaultAtts[i].value) {
         newE->defaultAtts[i].value
             = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);
-        if (!newE->defaultAtts[i].value)
+        if (! newE->defaultAtts[i].value)
           return 0;
-      }
-      else
+      } else
         newE->defaultAtts[i].value = NULL;
     }
   }
 
   /* Copy the entity tables. */
-  if (!copyEntityTable(oldParser,
-                       &(newDtd->generalEntities),
-                       &(newDtd->pool),
-                       &(oldDtd->generalEntities)))
-      return 0;
+  if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),
+                        &(oldDtd->generalEntities)))
+    return 0;
 
 #ifdef XML_DTD
-  if (!copyEntityTable(oldParser,
-                       &(newDtd->paramEntities),
-                       &(newDtd->pool),
-                       &(oldDtd->paramEntities)))
-      return 0;
+  if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),
+                        &(oldDtd->paramEntities)))
+    return 0;
   newDtd->paramEntityRead = oldDtd->paramEntityRead;
 #endif /* XML_DTD */
 
@@ -6557,14 +6280,11 @@
   newDtd->scaffIndex = oldDtd->scaffIndex;
 
   return 1;
-}  /* End dtdCopy */
+} /* End dtdCopy */
 
 static int
-copyEntityTable(XML_Parser oldParser,
-                HASH_TABLE *newTable,
-                STRING_POOL *newPool,
-                const HASH_TABLE *oldTable)
-{
+copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
+                STRING_POOL *newPool, const HASH_TABLE *oldTable) {
   HASH_TABLE_ITER iter;
   const XML_Char *cachedOldBase = NULL;
   const XML_Char *cachedNewBase = NULL;
@@ -6575,17 +6295,17 @@
     ENTITY *newE;
     const XML_Char *name;
     const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);
-    if (!oldE)
+    if (! oldE)
       break;
     name = poolCopyString(newPool, oldE->name);
-    if (!name)
+    if (! name)
       return 0;
     newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));
-    if (!newE)
+    if (! newE)
       return 0;
     if (oldE->systemId) {
       const XML_Char *tem = poolCopyString(newPool, oldE->systemId);
-      if (!tem)
+      if (! tem)
         return 0;
       newE->systemId = tem;
       if (oldE->base) {
@@ -6594,29 +6314,28 @@
         else {
           cachedOldBase = oldE->base;
           tem = poolCopyString(newPool, cachedOldBase);
-          if (!tem)
+          if (! tem)
             return 0;
           cachedNewBase = newE->base = tem;
         }
       }
       if (oldE->publicId) {
         tem = poolCopyString(newPool, oldE->publicId);
-        if (!tem)
+        if (! tem)
           return 0;
         newE->publicId = tem;
       }
-    }
-    else {
-      const XML_Char *tem = poolCopyStringN(newPool, oldE->textPtr,
-                                            oldE->textLen);
-      if (!tem)
+    } else {
+      const XML_Char *tem
+          = poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);
+      if (! tem)
         return 0;
       newE->textPtr = tem;
       newE->textLen = oldE->textLen;
     }
     if (oldE->notation) {
       const XML_Char *tem = poolCopyString(newPool, oldE->notation);
-      if (!tem)
+      if (! tem)
         return 0;
       newE->notation = tem;
     }
@@ -6629,8 +6348,7 @@
 #define INIT_POWER 6
 
 static XML_Bool FASTCALL
-keyeq(KEY s1, KEY s2)
-{
+keyeq(KEY s1, KEY s2) {
   for (; *s1 == *s2; s1++, s2++)
     if (*s1 == 0)
       return XML_TRUE;
@@ -6638,23 +6356,21 @@
 }
 
 static size_t
-keylen(KEY s)
-{
+keylen(KEY s) {
   size_t len = 0;
-  for (; *s; s++, len++);
+  for (; *s; s++, len++)
+    ;
   return len;
 }
 
 static void
-copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key)
-{
+copy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {
   key->k[0] = 0;
   key->k[1] = get_hash_secret_salt(parser);
 }
 
 static unsigned long FASTCALL
-hash(XML_Parser parser, KEY s)
-{
+hash(XML_Parser parser, KEY s) {
   struct siphash state;
   struct sipkey key;
   (void)sip24_valid;
@@ -6665,26 +6381,24 @@
 }
 
 static NAMED *
-lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize)
-{
+lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {
   size_t i;
   if (table->size == 0) {
     size_t tsize;
-    if (!createSize)
+    if (! createSize)
       return NULL;
     table->power = INIT_POWER;
     /* table->size is a power of 2 */
     table->size = (size_t)1 << INIT_POWER;
     tsize = table->size * sizeof(NAMED *);
     table->v = (NAMED **)table->mem->malloc_fcn(tsize);
-    if (!table->v) {
+    if (! table->v) {
       table->size = 0;
       return NULL;
     }
     memset(table->v, 0, tsize);
     i = hash(parser, name) & ((unsigned long)table->size - 1);
-  }
-  else {
+  } else {
     unsigned long h = hash(parser, name);
     unsigned long mask = (unsigned long)table->size - 1;
     unsigned char step = 0;
@@ -6692,11 +6406,11 @@
     while (table->v[i]) {
       if (keyeq(name, table->v[i]->name))
         return table->v[i];
-      if (!step)
+      if (! step)
         step = PROBE_STEP(h, mask, table->power);
       i < step ? (i += table->size - step) : (i -= step);
     }
-    if (!createSize)
+    if (! createSize)
       return NULL;
 
     /* check for overflow (table is half full) */
@@ -6706,7 +6420,7 @@
       unsigned long newMask = (unsigned long)newSize - 1;
       size_t tsize = newSize * sizeof(NAMED *);
       NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize);
-      if (!newV)
+      if (! newV)
         return NULL;
       memset(newV, 0, tsize);
       for (i = 0; i < table->size; i++)
@@ -6715,7 +6429,7 @@
           size_t j = newHash & newMask;
           step = 0;
           while (newV[j]) {
-            if (!step)
+            if (! step)
               step = PROBE_STEP(newHash, newMask, newPower);
             j < step ? (j += newSize - step) : (j -= step);
           }
@@ -6728,14 +6442,14 @@
       i = h & newMask;
       step = 0;
       while (table->v[i]) {
-        if (!step)
+        if (! step)
           step = PROBE_STEP(h, newMask, newPower);
         i < step ? (i += newSize - step) : (i -= step);
       }
     }
   }
   table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize);
-  if (!table->v[i])
+  if (! table->v[i])
     return NULL;
   memset(table->v[i], 0, createSize);
   table->v[i]->name = name;
@@ -6744,8 +6458,7 @@
 }
 
 static void FASTCALL
-hashTableClear(HASH_TABLE *table)
-{
+hashTableClear(HASH_TABLE *table) {
   size_t i;
   for (i = 0; i < table->size; i++) {
     table->mem->free_fcn(table->v[i]);
@@ -6755,8 +6468,7 @@
 }
 
 static void FASTCALL
-hashTableDestroy(HASH_TABLE *table)
-{
+hashTableDestroy(HASH_TABLE *table) {
   size_t i;
   for (i = 0; i < table->size; i++)
     table->mem->free_fcn(table->v[i]);
@@ -6764,8 +6476,7 @@
 }
 
 static void FASTCALL
-hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms)
-{
+hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms) {
   p->power = 0;
   p->size = 0;
   p->used = 0;
@@ -6774,15 +6485,13 @@
 }
 
 static void FASTCALL
-hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table)
-{
+hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {
   iter->p = table->v;
   iter->end = iter->p + table->size;
 }
 
-static NAMED * FASTCALL
-hashTableIterNext(HASH_TABLE_ITER *iter)
-{
+static NAMED *FASTCALL
+hashTableIterNext(HASH_TABLE_ITER *iter) {
   while (iter->p != iter->end) {
     NAMED *tem = *(iter->p)++;
     if (tem)
@@ -6792,8 +6501,7 @@
 }
 
 static void FASTCALL
-poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms)
-{
+poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) {
   pool->blocks = NULL;
   pool->freeBlocks = NULL;
   pool->start = NULL;
@@ -6803,9 +6511,8 @@
 }
 
 static void FASTCALL
-poolClear(STRING_POOL *pool)
-{
-  if (!pool->freeBlocks)
+poolClear(STRING_POOL *pool) {
+  if (! pool->freeBlocks)
     pool->freeBlocks = pool->blocks;
   else {
     BLOCK *p = pool->blocks;
@@ -6823,8 +6530,7 @@
 }
 
 static void FASTCALL
-poolDestroy(STRING_POOL *pool)
-{
+poolDestroy(STRING_POOL *pool) {
   BLOCK *p = pool->blocks;
   while (p) {
     BLOCK *tem = p->next;
@@ -6840,26 +6546,26 @@
 }
 
 static XML_Char *
-poolAppend(STRING_POOL *pool, const ENCODING *enc,
-           const char *ptr, const char *end)
-{
-  if (!pool->ptr && !poolGrow(pool))
+poolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
+           const char *end) {
+  if (! pool->ptr && ! poolGrow(pool))
     return NULL;
   for (;;) {
-    const enum XML_Convert_Result convert_res = XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
-    if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
+    const enum XML_Convert_Result convert_res = XmlConvert(
+        enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end);
+    if ((convert_res == XML_CONVERT_COMPLETED)
+        || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
       break;
-    if (!poolGrow(pool))
+    if (! poolGrow(pool))
       return NULL;
   }
   return pool->start;
 }
 
-static const XML_Char * FASTCALL
-poolCopyString(STRING_POOL *pool, const XML_Char *s)
-{
+static const XML_Char *FASTCALL
+poolCopyString(STRING_POOL *pool, const XML_Char *s) {
   do {
-    if (!poolAppendChar(pool, *s))
+    if (! poolAppendChar(pool, *s))
       return NULL;
   } while (*s++);
   s = pool->start;
@@ -6868,9 +6574,8 @@
 }
 
 static const XML_Char *
-poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n)
-{
-  if (!pool->ptr && !poolGrow(pool)) {
+poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {
+  if (! pool->ptr && ! poolGrow(pool)) {
     /* The following line is unreachable given the current usage of
      * poolCopyStringN().  Currently it is called from exactly one
      * place to copy the text of a simple general entity.  By that
@@ -6885,7 +6590,7 @@
     return NULL; /* LCOV_EXCL_LINE */
   }
   for (; n > 0; --n, s++) {
-    if (!poolAppendChar(pool, *s))
+    if (! poolAppendChar(pool, *s))
       return NULL;
   }
   s = pool->start;
@@ -6893,11 +6598,10 @@
   return s;
 }
 
-static const XML_Char * FASTCALL
-poolAppendString(STRING_POOL *pool, const XML_Char *s)
-{
+static const XML_Char *FASTCALL
+poolAppendString(STRING_POOL *pool, const XML_Char *s) {
   while (*s) {
-    if (!poolAppendChar(pool, *s))
+    if (! poolAppendChar(pool, *s))
       return NULL;
     s++;
   }
@@ -6905,20 +6609,18 @@
 }
 
 static XML_Char *
-poolStoreString(STRING_POOL *pool, const ENCODING *enc,
-                const char *ptr, const char *end)
-{
-  if (!poolAppend(pool, enc, ptr, end))
+poolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,
+                const char *end) {
+  if (! poolAppend(pool, enc, ptr, end))
     return NULL;
-  if (pool->ptr == pool->end && !poolGrow(pool))
+  if (pool->ptr == pool->end && ! poolGrow(pool))
     return NULL;
   *(pool->ptr)++ = 0;
   return pool->start;
 }
 
 static size_t
-poolBytesToAllocateFor(int blockSize)
-{
+poolBytesToAllocateFor(int blockSize) {
   /* Unprotected math would be:
   ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);
   **
@@ -6926,7 +6628,7 @@
   ** For a + b * c we check b * c in isolation first, so that addition of a
   ** on top has no chance of making us accept a small non-negative number
   */
-  const size_t stretch = sizeof(XML_Char);  /* can be 4 bytes */
+  const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */
 
   if (blockSize <= 0)
     return 0;
@@ -6936,8 +6638,8 @@
 
   {
     const int stretchedBlockSize = blockSize * (int)stretch;
-    const int bytesToAllocate = (int)(
-        offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
+    const int bytesToAllocate
+        = (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);
     if (bytesToAllocate < 0)
       return 0;
 
@@ -6946,8 +6648,7 @@
 }
 
 static XML_Bool FASTCALL
-poolGrow(STRING_POOL *pool)
-{
+poolGrow(STRING_POOL *pool) {
   if (pool->freeBlocks) {
     if (pool->start == 0) {
       pool->blocks = pool->freeBlocks;
@@ -6973,7 +6674,7 @@
   }
   if (pool->blocks && pool->start == pool->blocks->s) {
     BLOCK *temp;
-    int blockSize = (int)((unsigned)(pool->end - pool->start)*2U);
+    int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);
     size_t bytesToAllocate;
 
     /* NOTE: Needs to be calculated prior to calling `realloc`
@@ -6994,8 +6695,8 @@
     if (bytesToAllocate == 0)
       return XML_FALSE;
 
-    temp = (BLOCK *)
-      pool->mem->realloc_fcn(pool->blocks, (unsigned)bytesToAllocate);
+    temp = (BLOCK *)pool->mem->realloc_fcn(pool->blocks,
+                                           (unsigned)bytesToAllocate);
     if (temp == NULL)
       return XML_FALSE;
     pool->blocks = temp;
@@ -7003,8 +6704,7 @@
     pool->ptr = pool->blocks->s + offsetInsideBlock;
     pool->start = pool->blocks->s;
     pool->end = pool->start + blockSize;
-  }
-  else {
+  } else {
     BLOCK *tem;
     int blockSize = (int)(pool->end - pool->start);
     size_t bytesToAllocate;
@@ -7019,7 +6719,7 @@
        * function).  Either way it isn't readily testable, so we
        * exclude it from the coverage statistics.
        */
-      return XML_FALSE;  /* LCOV_EXCL_LINE */
+      return XML_FALSE; /* LCOV_EXCL_LINE */
     }
 
     if (blockSize < INIT_BLOCK_SIZE)
@@ -7037,14 +6737,13 @@
       return XML_FALSE;
 
     tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate);
-    if (!tem)
+    if (! tem)
       return XML_FALSE;
     tem->size = blockSize;
     tem->next = pool->blocks;
     pool->blocks = tem;
     if (pool->ptr != pool->start)
-      memcpy(tem->s, pool->start,
-             (pool->ptr - pool->start) * sizeof(XML_Char));
+      memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));
     pool->ptr = tem->s + (pool->ptr - pool->start);
     pool->start = tem->s;
     pool->end = tem->s + blockSize;
@@ -7053,15 +6752,14 @@
 }
 
 static int FASTCALL
-nextScaffoldPart(XML_Parser parser)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
-  CONTENT_SCAFFOLD * me;
+nextScaffoldPart(XML_Parser parser) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
+  CONTENT_SCAFFOLD *me;
   int next;
 
-  if (!dtd->scaffIndex) {
+  if (! dtd->scaffIndex) {
     dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
-    if (!dtd->scaffIndex)
+    if (! dtd->scaffIndex)
       return -1;
     dtd->scaffIndex[0] = 0;
   }
@@ -7069,15 +6767,14 @@
   if (dtd->scaffCount >= dtd->scaffSize) {
     CONTENT_SCAFFOLD *temp;
     if (dtd->scaffold) {
-      temp = (CONTENT_SCAFFOLD *)
-        REALLOC(parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
+      temp = (CONTENT_SCAFFOLD *)REALLOC(
+          parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
       if (temp == NULL)
         return -1;
       dtd->scaffSize *= 2;
-    }
-    else {
+    } else {
       temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
-                                        * sizeof(CONTENT_SCAFFOLD));
+                                                    * sizeof(CONTENT_SCAFFOLD));
       if (temp == NULL)
         return -1;
       dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;
@@ -7087,11 +6784,12 @@
   next = dtd->scaffCount++;
   me = &dtd->scaffold[next];
   if (dtd->scaffLevel) {
-    CONTENT_SCAFFOLD *parent = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel-1]];
+    CONTENT_SCAFFOLD *parent
+        = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];
     if (parent->lastchild) {
       dtd->scaffold[parent->lastchild].nextsib = next;
     }
-    if (!parent->childcnt)
+    if (! parent->childcnt)
       parent->firstchild = next;
     parent->lastchild = next;
     parent->childcnt++;
@@ -7101,13 +6799,9 @@
 }
 
 static void
-build_node(XML_Parser parser,
-           int src_node,
-           XML_Content *dest,
-           XML_Content **contpos,
-           XML_Char **strpos)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+build_node(XML_Parser parser, int src_node, XML_Content *dest,
+           XML_Content **contpos, XML_Char **strpos) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   dest->type = dtd->scaffold[src_node].type;
   dest->quant = dtd->scaffold[src_node].quant;
   if (dest->type == XML_CTYPE_NAME) {
@@ -7116,21 +6810,19 @@
     src = dtd->scaffold[src_node].name;
     for (;;) {
       *(*strpos)++ = *src;
-      if (!*src)
+      if (! *src)
         break;
       src++;
     }
     dest->numchildren = 0;
     dest->children = NULL;
-  }
-  else {
+  } else {
     unsigned int i;
     int cn;
     dest->numchildren = dtd->scaffold[src_node].childcnt;
     dest->children = *contpos;
     *contpos += dest->numchildren;
-    for (i = 0, cn = dtd->scaffold[src_node].firstchild;
-         i < dest->numchildren;
+    for (i = 0, cn = dtd->scaffold[src_node].firstchild; i < dest->numchildren;
          i++, cn = dtd->scaffold[cn].nextsib) {
       build_node(parser, cn, &(dest->children[i]), contpos, strpos);
     }
@@ -7139,20 +6831,19 @@
 }
 
 static XML_Content *
-build_model (XML_Parser parser)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+build_model(XML_Parser parser) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   XML_Content *ret;
   XML_Content *cpos;
-  XML_Char * str;
+  XML_Char *str;
   int allocsize = (dtd->scaffCount * sizeof(XML_Content)
                    + (dtd->contentStringLen * sizeof(XML_Char)));
 
   ret = (XML_Content *)MALLOC(parser, allocsize);
-  if (!ret)
+  if (! ret)
     return NULL;
 
-  str =  (XML_Char *) (&ret[dtd->scaffCount]);
+  str = (XML_Char *)(&ret[dtd->scaffCount]);
   cpos = &ret[1];
 
   build_node(parser, 0, ret, &cpos, &str);
@@ -7160,49 +6851,45 @@
 }
 
 static ELEMENT_TYPE *
-getElementType(XML_Parser parser,
-               const ENCODING *enc,
-               const char *ptr,
-               const char *end)
-{
-  DTD * const dtd = parser->m_dtd;  /* save one level of indirection */
+getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,
+               const char *end) {
+  DTD *const dtd = parser->m_dtd; /* save one level of indirection */
   const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
   ELEMENT_TYPE *ret;
 
-  if (!name)
+  if (! name)
     return NULL;
-  ret = (ELEMENT_TYPE *) lookup(parser, &dtd->elementTypes, name, sizeof(ELEMENT_TYPE));
-  if (!ret)
+  ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,
+                               sizeof(ELEMENT_TYPE));
+  if (! ret)
     return NULL;
   if (ret->name != name)
     poolDiscard(&dtd->pool);
   else {
     poolFinish(&dtd->pool);
-    if (!setElementTypePrefix(parser, ret))
+    if (! setElementTypePrefix(parser, ret))
       return NULL;
   }
   return ret;
 }
 
 static XML_Char *
-copyString(const XML_Char *s,
-           const XML_Memory_Handling_Suite *memsuite)
-{
-    int charsRequired = 0;
-    XML_Char *result;
+copyString(const XML_Char *s, const XML_Memory_Handling_Suite *memsuite) {
+  int charsRequired = 0;
+  XML_Char *result;
 
-    /* First determine how long the string is */
-    while (s[charsRequired] != 0) {
-      charsRequired++;
-    }
-    /* Include the terminator */
+  /* First determine how long the string is */
+  while (s[charsRequired] != 0) {
     charsRequired++;
+  }
+  /* Include the terminator */
+  charsRequired++;
 
-    /* Now allocate space for the copy */
-    result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
-    if (result == NULL)
-        return NULL;
-    /* Copy the original into place */
-    memcpy(result, s, charsRequired * sizeof(XML_Char));
-    return result;
+  /* Now allocate space for the copy */
+  result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
+  if (result == NULL)
+    return NULL;
+  /* Copy the original into place */
+  memcpy(result, s, charsRequired * sizeof(XML_Char));
+  return result;
 }
diff --git a/third_party/expat/files/lib/xmlrole.c b/third_party/expat/files/lib/xmlrole.c
index 708507d..4d3e3e8 100644
--- a/third_party/expat/files/lib/xmlrole.c
+++ b/third_party/expat/files/lib/xmlrole.c
@@ -33,11 +33,11 @@
 #include <stddef.h>
 
 #ifdef _WIN32
-#include "winconfig.h"
+#  include "winconfig.h"
 #else
-#ifdef HAVE_EXPAT_CONFIG_H
-#include <expat_config.h>
-#endif
+#  ifdef HAVE_EXPAT_CONFIG_H
+#    include <expat_config.h>
+#  endif
 #endif /* ndef _WIN32 */
 
 #include "expat_external.h"
@@ -52,107 +52,88 @@
 
 */
 
-static const char KW_ANY[] = {
-    ASCII_A, ASCII_N, ASCII_Y, '\0' };
-static const char KW_ATTLIST[] = {
-    ASCII_A, ASCII_T, ASCII_T, ASCII_L, ASCII_I, ASCII_S, ASCII_T, '\0' };
-static const char KW_CDATA[] = {
-    ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' };
-static const char KW_DOCTYPE[] = {
-    ASCII_D, ASCII_O, ASCII_C, ASCII_T, ASCII_Y, ASCII_P, ASCII_E, '\0' };
-static const char KW_ELEMENT[] = {
-    ASCII_E, ASCII_L, ASCII_E, ASCII_M, ASCII_E, ASCII_N, ASCII_T, '\0' };
-static const char KW_EMPTY[] = {
-    ASCII_E, ASCII_M, ASCII_P, ASCII_T, ASCII_Y, '\0' };
-static const char KW_ENTITIES[] = {
-    ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S,
-    '\0' };
-static const char KW_ENTITY[] = {
-    ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' };
-static const char KW_FIXED[] = {
-    ASCII_F, ASCII_I, ASCII_X, ASCII_E, ASCII_D, '\0' };
-static const char KW_ID[] = {
-    ASCII_I, ASCII_D, '\0' };
-static const char KW_IDREF[] = {
-    ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' };
-static const char KW_IDREFS[] = {
-    ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' };
+static const char KW_ANY[] = {ASCII_A, ASCII_N, ASCII_Y, '\0'};
+static const char KW_ATTLIST[]
+    = {ASCII_A, ASCII_T, ASCII_T, ASCII_L, ASCII_I, ASCII_S, ASCII_T, '\0'};
+static const char KW_CDATA[]
+    = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
+static const char KW_DOCTYPE[]
+    = {ASCII_D, ASCII_O, ASCII_C, ASCII_T, ASCII_Y, ASCII_P, ASCII_E, '\0'};
+static const char KW_ELEMENT[]
+    = {ASCII_E, ASCII_L, ASCII_E, ASCII_M, ASCII_E, ASCII_N, ASCII_T, '\0'};
+static const char KW_EMPTY[]
+    = {ASCII_E, ASCII_M, ASCII_P, ASCII_T, ASCII_Y, '\0'};
+static const char KW_ENTITIES[] = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
+                                   ASCII_I, ASCII_E, ASCII_S, '\0'};
+static const char KW_ENTITY[]
+    = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
+static const char KW_FIXED[]
+    = {ASCII_F, ASCII_I, ASCII_X, ASCII_E, ASCII_D, '\0'};
+static const char KW_ID[] = {ASCII_I, ASCII_D, '\0'};
+static const char KW_IDREF[]
+    = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
+static const char KW_IDREFS[]
+    = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
 #ifdef XML_DTD
-static const char KW_IGNORE[] = {
-    ASCII_I, ASCII_G, ASCII_N, ASCII_O, ASCII_R, ASCII_E, '\0' };
+static const char KW_IGNORE[]
+    = {ASCII_I, ASCII_G, ASCII_N, ASCII_O, ASCII_R, ASCII_E, '\0'};
 #endif
-static const char KW_IMPLIED[] = {
-    ASCII_I, ASCII_M, ASCII_P, ASCII_L, ASCII_I, ASCII_E, ASCII_D, '\0' };
+static const char KW_IMPLIED[]
+    = {ASCII_I, ASCII_M, ASCII_P, ASCII_L, ASCII_I, ASCII_E, ASCII_D, '\0'};
 #ifdef XML_DTD
-static const char KW_INCLUDE[] = {
-    ASCII_I, ASCII_N, ASCII_C, ASCII_L, ASCII_U, ASCII_D, ASCII_E, '\0' };
+static const char KW_INCLUDE[]
+    = {ASCII_I, ASCII_N, ASCII_C, ASCII_L, ASCII_U, ASCII_D, ASCII_E, '\0'};
 #endif
-static const char KW_NDATA[] = {
-    ASCII_N, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' };
-static const char KW_NMTOKEN[] = {
-    ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' };
-static const char KW_NMTOKENS[] = {
-    ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S,
-    '\0' };
-static const char KW_NOTATION[] =
-    { ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N,
-      '\0' };
-static const char KW_PCDATA[] = {
-    ASCII_P, ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' };
-static const char KW_PUBLIC[] = {
-    ASCII_P, ASCII_U, ASCII_B, ASCII_L, ASCII_I, ASCII_C, '\0' };
-static const char KW_REQUIRED[] = {
-    ASCII_R, ASCII_E, ASCII_Q, ASCII_U, ASCII_I, ASCII_R, ASCII_E, ASCII_D,
-    '\0' };
-static const char KW_SYSTEM[] = {
-    ASCII_S, ASCII_Y, ASCII_S, ASCII_T, ASCII_E, ASCII_M, '\0' };
+static const char KW_NDATA[]
+    = {ASCII_N, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
+static const char KW_NMTOKEN[]
+    = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
+static const char KW_NMTOKENS[] = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
+                                   ASCII_E, ASCII_N, ASCII_S, '\0'};
+static const char KW_NOTATION[] = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,
+                                   ASCII_I, ASCII_O, ASCII_N, '\0'};
+static const char KW_PCDATA[]
+    = {ASCII_P, ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
+static const char KW_PUBLIC[]
+    = {ASCII_P, ASCII_U, ASCII_B, ASCII_L, ASCII_I, ASCII_C, '\0'};
+static const char KW_REQUIRED[] = {ASCII_R, ASCII_E, ASCII_Q, ASCII_U, ASCII_I,
+                                   ASCII_R, ASCII_E, ASCII_D, '\0'};
+static const char KW_SYSTEM[]
+    = {ASCII_S, ASCII_Y, ASCII_S, ASCII_T, ASCII_E, ASCII_M, '\0'};
 
 #ifndef MIN_BYTES_PER_CHAR
-#define MIN_BYTES_PER_CHAR(enc) ((enc)->minBytesPerChar)
+#  define MIN_BYTES_PER_CHAR(enc) ((enc)->minBytesPerChar)
 #endif
 
 #ifdef XML_DTD
-#define setTopLevel(state) \
-  ((state)->handler = ((state)->documentEntity \
-                       ? internalSubset \
-                       : externalSubset1))
+#  define setTopLevel(state)                                                   \
+    ((state)->handler                                                          \
+     = ((state)->documentEntity ? internalSubset : externalSubset1))
 #else /* not XML_DTD */
-#define setTopLevel(state) ((state)->handler = internalSubset)
+#  define setTopLevel(state) ((state)->handler = internalSubset)
 #endif /* not XML_DTD */
 
-typedef int PTRCALL PROLOG_HANDLER(PROLOG_STATE *state,
-                                   int tok,
-                                   const char *ptr,
-                                   const char *end,
+typedef int PTRCALL PROLOG_HANDLER(PROLOG_STATE *state, int tok,
+                                   const char *ptr, const char *end,
                                    const ENCODING *enc);
 
-static PROLOG_HANDLER
-  prolog0, prolog1, prolog2,
-  doctype0, doctype1, doctype2, doctype3, doctype4, doctype5,
-  internalSubset,
-  entity0, entity1, entity2, entity3, entity4, entity5, entity6,
-  entity7, entity8, entity9, entity10,
-  notation0, notation1, notation2, notation3, notation4,
-  attlist0, attlist1, attlist2, attlist3, attlist4, attlist5, attlist6,
-  attlist7, attlist8, attlist9,
-  element0, element1, element2, element3, element4, element5, element6,
-  element7,
+static PROLOG_HANDLER prolog0, prolog1, prolog2, doctype0, doctype1, doctype2,
+    doctype3, doctype4, doctype5, internalSubset, entity0, entity1, entity2,
+    entity3, entity4, entity5, entity6, entity7, entity8, entity9, entity10,
+    notation0, notation1, notation2, notation3, notation4, attlist0, attlist1,
+    attlist2, attlist3, attlist4, attlist5, attlist6, attlist7, attlist8,
+    attlist9, element0, element1, element2, element3, element4, element5,
+    element6, element7,
 #ifdef XML_DTD
-  externalSubset0, externalSubset1,
-  condSect0, condSect1, condSect2,
+    externalSubset0, externalSubset1, condSect0, condSect1, condSect2,
 #endif /* XML_DTD */
-  declClose,
-  error;
+    declClose, error;
 
 static int FASTCALL common(PROLOG_STATE *state, int tok);
 
 static int PTRCALL
-prolog0(PROLOG_STATE *state,
-        int tok,
-        const char *ptr,
-        const char *end,
-        const ENCODING *enc)
-{
+prolog0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     state->handler = prolog1;
@@ -169,10 +150,8 @@
   case XML_TOK_BOM:
     return XML_ROLE_NONE;
   case XML_TOK_DECL_OPEN:
-    if (!XmlNameMatchesAscii(enc,
-                             ptr + 2 * MIN_BYTES_PER_CHAR(enc),
-                             end,
-                             KW_DOCTYPE))
+    if (! XmlNameMatchesAscii(enc, ptr + 2 * MIN_BYTES_PER_CHAR(enc), end,
+                              KW_DOCTYPE))
       break;
     state->handler = doctype0;
     return XML_ROLE_DOCTYPE_NONE;
@@ -184,12 +163,8 @@
 }
 
 static int PTRCALL
-prolog1(PROLOG_STATE *state,
-        int tok,
-        const char *ptr,
-        const char *end,
-        const ENCODING *enc)
-{
+prolog1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NONE;
@@ -207,10 +182,8 @@
      */
     return XML_ROLE_NONE; /* LCOV_EXCL_LINE */
   case XML_TOK_DECL_OPEN:
-    if (!XmlNameMatchesAscii(enc,
-                             ptr + 2 * MIN_BYTES_PER_CHAR(enc),
-                             end,
-                             KW_DOCTYPE))
+    if (! XmlNameMatchesAscii(enc, ptr + 2 * MIN_BYTES_PER_CHAR(enc), end,
+                              KW_DOCTYPE))
       break;
     state->handler = doctype0;
     return XML_ROLE_DOCTYPE_NONE;
@@ -222,12 +195,11 @@
 }
 
 static int PTRCALL
-prolog2(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+prolog2(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NONE;
@@ -243,12 +215,11 @@
 }
 
 static int PTRCALL
-doctype0(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+doctype0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_DOCTYPE_NONE;
@@ -261,12 +232,8 @@
 }
 
 static int PTRCALL
-doctype1(PROLOG_STATE *state,
-         int tok,
-         const char *ptr,
-         const char *end,
-         const ENCODING *enc)
-{
+doctype1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_DOCTYPE_NONE;
@@ -291,12 +258,11 @@
 }
 
 static int PTRCALL
-doctype2(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+doctype2(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_DOCTYPE_NONE;
@@ -308,12 +274,11 @@
 }
 
 static int PTRCALL
-doctype3(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+doctype3(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_DOCTYPE_NONE;
@@ -325,12 +290,11 @@
 }
 
 static int PTRCALL
-doctype4(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+doctype4(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_DOCTYPE_NONE;
@@ -345,12 +309,11 @@
 }
 
 static int PTRCALL
-doctype5(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+doctype5(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_DOCTYPE_NONE;
@@ -362,40 +325,28 @@
 }
 
 static int PTRCALL
-internalSubset(PROLOG_STATE *state,
-               int tok,
-               const char *ptr,
-               const char *end,
-               const ENCODING *enc)
-{
+internalSubset(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+               const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NONE;
   case XML_TOK_DECL_OPEN:
-    if (XmlNameMatchesAscii(enc,
-                            ptr + 2 * MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + 2 * MIN_BYTES_PER_CHAR(enc), end,
                             KW_ENTITY)) {
       state->handler = entity0;
       return XML_ROLE_ENTITY_NONE;
     }
-    if (XmlNameMatchesAscii(enc,
-                            ptr + 2 * MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + 2 * MIN_BYTES_PER_CHAR(enc), end,
                             KW_ATTLIST)) {
       state->handler = attlist0;
       return XML_ROLE_ATTLIST_NONE;
     }
-    if (XmlNameMatchesAscii(enc,
-                            ptr + 2 * MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + 2 * MIN_BYTES_PER_CHAR(enc), end,
                             KW_ELEMENT)) {
       state->handler = element0;
       return XML_ROLE_ELEMENT_NONE;
     }
-    if (XmlNameMatchesAscii(enc,
-                            ptr + 2 * MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + 2 * MIN_BYTES_PER_CHAR(enc), end,
                             KW_NOTATION)) {
       state->handler = notation0;
       return XML_ROLE_NOTATION_NONE;
@@ -419,12 +370,8 @@
 #ifdef XML_DTD
 
 static int PTRCALL
-externalSubset0(PROLOG_STATE *state,
-                int tok,
-                const char *ptr,
-                const char *end,
-                const ENCODING *enc)
-{
+externalSubset0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+                const ENCODING *enc) {
   state->handler = externalSubset1;
   if (tok == XML_TOK_XML_DECL)
     return XML_ROLE_TEXT_DECL;
@@ -432,12 +379,8 @@
 }
 
 static int PTRCALL
-externalSubset1(PROLOG_STATE *state,
-                int tok,
-                const char *ptr,
-                const char *end,
-                const ENCODING *enc)
-{
+externalSubset1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+                const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_COND_SECT_OPEN:
     state->handler = condSect0;
@@ -464,12 +407,11 @@
 #endif /* XML_DTD */
 
 static int PTRCALL
-entity0(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+entity0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -484,12 +426,11 @@
 }
 
 static int PTRCALL
-entity1(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+entity1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -501,12 +442,8 @@
 }
 
 static int PTRCALL
-entity2(PROLOG_STATE *state,
-        int tok,
-        const char *ptr,
-        const char *end,
-        const ENCODING *enc)
-{
+entity2(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -529,12 +466,11 @@
 }
 
 static int PTRCALL
-entity3(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+entity3(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -546,12 +482,11 @@
 }
 
 static int PTRCALL
-entity4(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+entity4(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -563,12 +498,8 @@
 }
 
 static int PTRCALL
-entity5(PROLOG_STATE *state,
-        int tok,
-        const char *ptr,
-        const char *end,
-        const ENCODING *enc)
-{
+entity5(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -586,12 +517,11 @@
 }
 
 static int PTRCALL
-entity6(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+entity6(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -604,12 +534,8 @@
 }
 
 static int PTRCALL
-entity7(PROLOG_STATE *state,
-        int tok,
-        const char *ptr,
-        const char *end,
-        const ENCODING *enc)
-{
+entity7(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -632,12 +558,11 @@
 }
 
 static int PTRCALL
-entity8(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+entity8(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -649,12 +574,11 @@
 }
 
 static int PTRCALL
-entity9(PROLOG_STATE *state,
-        int tok,
-        const char *UNUSED_P(ptr),
-        const char *UNUSED_P(end),
-        const ENCODING *UNUSED_P(enc))
-{
+entity9(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+        const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -666,12 +590,11 @@
 }
 
 static int PTRCALL
-entity10(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+entity10(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ENTITY_NONE;
@@ -683,12 +606,11 @@
 }
 
 static int PTRCALL
-notation0(PROLOG_STATE *state,
-          int tok,
-          const char *UNUSED_P(ptr),
-          const char *UNUSED_P(end),
-          const ENCODING *UNUSED_P(enc))
-{
+notation0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NOTATION_NONE;
@@ -700,12 +622,8 @@
 }
 
 static int PTRCALL
-notation1(PROLOG_STATE *state,
-          int tok,
-          const char *ptr,
-          const char *end,
-          const ENCODING *enc)
-{
+notation1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NOTATION_NONE;
@@ -724,12 +642,11 @@
 }
 
 static int PTRCALL
-notation2(PROLOG_STATE *state,
-          int tok,
-          const char *UNUSED_P(ptr),
-          const char *UNUSED_P(end),
-          const ENCODING *UNUSED_P(enc))
-{
+notation2(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NOTATION_NONE;
@@ -741,12 +658,11 @@
 }
 
 static int PTRCALL
-notation3(PROLOG_STATE *state,
-          int tok,
-          const char *UNUSED_P(ptr),
-          const char *UNUSED_P(end),
-          const ENCODING *UNUSED_P(enc))
-{
+notation3(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NOTATION_NONE;
@@ -759,12 +675,11 @@
 }
 
 static int PTRCALL
-notation4(PROLOG_STATE *state,
-          int tok,
-          const char *UNUSED_P(ptr),
-          const char *UNUSED_P(end),
-          const ENCODING *UNUSED_P(enc))
-{
+notation4(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NOTATION_NONE;
@@ -780,12 +695,11 @@
 }
 
 static int PTRCALL
-attlist0(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -798,12 +712,11 @@
 }
 
 static int PTRCALL
-attlist1(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -819,34 +732,23 @@
 }
 
 static int PTRCALL
-attlist2(PROLOG_STATE *state,
-         int tok,
-         const char *ptr,
-         const char *end,
-         const ENCODING *enc)
-{
+attlist2(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
-  case XML_TOK_NAME:
-    {
-      static const char * const types[] = {
-        KW_CDATA,
-        KW_ID,
-        KW_IDREF,
-        KW_IDREFS,
-        KW_ENTITY,
-        KW_ENTITIES,
-        KW_NMTOKEN,
-        KW_NMTOKENS,
-      };
-      int i;
-      for (i = 0; i < (int)(sizeof(types)/sizeof(types[0])); i++)
-        if (XmlNameMatchesAscii(enc, ptr, end, types[i])) {
-          state->handler = attlist8;
-          return XML_ROLE_ATTRIBUTE_TYPE_CDATA + i;
-        }
-    }
+  case XML_TOK_NAME: {
+    static const char *const types[] = {
+        KW_CDATA,  KW_ID,       KW_IDREF,   KW_IDREFS,
+        KW_ENTITY, KW_ENTITIES, KW_NMTOKEN, KW_NMTOKENS,
+    };
+    int i;
+    for (i = 0; i < (int)(sizeof(types) / sizeof(types[0])); i++)
+      if (XmlNameMatchesAscii(enc, ptr, end, types[i])) {
+        state->handler = attlist8;
+        return XML_ROLE_ATTRIBUTE_TYPE_CDATA + i;
+      }
+  }
     if (XmlNameMatchesAscii(enc, ptr, end, KW_NOTATION)) {
       state->handler = attlist5;
       return XML_ROLE_ATTLIST_NONE;
@@ -860,12 +762,11 @@
 }
 
 static int PTRCALL
-attlist3(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist3(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -879,12 +780,11 @@
 }
 
 static int PTRCALL
-attlist4(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist4(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -899,12 +799,11 @@
 }
 
 static int PTRCALL
-attlist5(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist5(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -916,12 +815,11 @@
 }
 
 static int PTRCALL
-attlist6(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist6(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -933,12 +831,11 @@
 }
 
 static int PTRCALL
-attlist7(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist7(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -954,33 +851,23 @@
 
 /* default value */
 static int PTRCALL
-attlist8(PROLOG_STATE *state,
-         int tok,
-         const char *ptr,
-         const char *end,
-         const ENCODING *enc)
-{
+attlist8(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
   case XML_TOK_POUND_NAME:
-    if (XmlNameMatchesAscii(enc,
-                            ptr + MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + MIN_BYTES_PER_CHAR(enc), end,
                             KW_IMPLIED)) {
       state->handler = attlist1;
       return XML_ROLE_IMPLIED_ATTRIBUTE_VALUE;
     }
-    if (XmlNameMatchesAscii(enc,
-                            ptr + MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + MIN_BYTES_PER_CHAR(enc), end,
                             KW_REQUIRED)) {
       state->handler = attlist1;
       return XML_ROLE_REQUIRED_ATTRIBUTE_VALUE;
     }
-    if (XmlNameMatchesAscii(enc,
-                            ptr + MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + MIN_BYTES_PER_CHAR(enc), end,
                             KW_FIXED)) {
       state->handler = attlist9;
       return XML_ROLE_ATTLIST_NONE;
@@ -994,12 +881,11 @@
 }
 
 static int PTRCALL
-attlist9(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+attlist9(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ATTLIST_NONE;
@@ -1011,12 +897,11 @@
 }
 
 static int PTRCALL
-element0(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+element0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
@@ -1029,12 +914,8 @@
 }
 
 static int PTRCALL
-element1(PROLOG_STATE *state,
-         int tok,
-         const char *ptr,
-         const char *end,
-         const ENCODING *enc)
-{
+element1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
@@ -1059,19 +940,13 @@
 }
 
 static int PTRCALL
-element2(PROLOG_STATE *state,
-         int tok,
-         const char *ptr,
-         const char *end,
-         const ENCODING *enc)
-{
+element2(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
   case XML_TOK_POUND_NAME:
-    if (XmlNameMatchesAscii(enc,
-                            ptr + MIN_BYTES_PER_CHAR(enc),
-                            end,
+    if (XmlNameMatchesAscii(enc, ptr + MIN_BYTES_PER_CHAR(enc), end,
                             KW_PCDATA)) {
       state->handler = element3;
       return XML_ROLE_CONTENT_PCDATA;
@@ -1099,12 +974,11 @@
 }
 
 static int PTRCALL
-element3(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+element3(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
@@ -1124,12 +998,11 @@
 }
 
 static int PTRCALL
-element4(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+element4(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
@@ -1142,12 +1015,11 @@
 }
 
 static int PTRCALL
-element5(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+element5(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
@@ -1163,12 +1035,11 @@
 }
 
 static int PTRCALL
-element6(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+element6(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
@@ -1193,12 +1064,11 @@
 }
 
 static int PTRCALL
-element7(PROLOG_STATE *state,
-         int tok,
-         const char *UNUSED_P(ptr),
-         const char *UNUSED_P(end),
-         const ENCODING *UNUSED_P(enc))
-{
+element7(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+         const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_ELEMENT_NONE;
@@ -1243,12 +1113,8 @@
 #ifdef XML_DTD
 
 static int PTRCALL
-condSect0(PROLOG_STATE *state,
-          int tok,
-          const char *ptr,
-          const char *end,
-          const ENCODING *enc)
-{
+condSect0(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NONE;
@@ -1267,12 +1133,11 @@
 }
 
 static int PTRCALL
-condSect1(PROLOG_STATE *state,
-          int tok,
-          const char *UNUSED_P(ptr),
-          const char *UNUSED_P(end),
-          const ENCODING *UNUSED_P(enc))
-{
+condSect1(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NONE;
@@ -1285,12 +1150,11 @@
 }
 
 static int PTRCALL
-condSect2(PROLOG_STATE *state,
-          int tok,
-          const char *UNUSED_P(ptr),
-          const char *UNUSED_P(end),
-          const ENCODING *UNUSED_P(enc))
-{
+condSect2(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return XML_ROLE_NONE;
@@ -1304,12 +1168,11 @@
 #endif /* XML_DTD */
 
 static int PTRCALL
-declClose(PROLOG_STATE *state,
-          int tok,
-          const char *UNUSED_P(ptr),
-          const char *UNUSED_P(end),
-          const ENCODING *UNUSED_P(enc))
-{
+declClose(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+          const ENCODING *enc) {
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   switch (tok) {
   case XML_TOK_PROLOG_S:
     return state->role_none;
@@ -1341,21 +1204,21 @@
  * LCOV_EXCL_START
  */
 static int PTRCALL
-error(PROLOG_STATE *UNUSED_P(state),
-      int UNUSED_P(tok),
-      const char *UNUSED_P(ptr),
-      const char *UNUSED_P(end),
-      const ENCODING *UNUSED_P(enc))
-{
+error(PROLOG_STATE *state, int tok, const char *ptr, const char *end,
+      const ENCODING *enc) {
+  UNUSED_P(state);
+  UNUSED_P(tok);
+  UNUSED_P(ptr);
+  UNUSED_P(end);
+  UNUSED_P(enc);
   return XML_ROLE_NONE;
 }
 /* LCOV_EXCL_STOP */
 
 static int FASTCALL
-common(PROLOG_STATE *state, int tok)
-{
+common(PROLOG_STATE *state, int tok) {
 #ifdef XML_DTD
-  if (!state->documentEntity && tok == XML_TOK_PARAM_ENTITY_REF)
+  if (! state->documentEntity && tok == XML_TOK_PARAM_ENTITY_REF)
     return XML_ROLE_INNER_PARAM_ENTITY_REF;
 #endif
   state->handler = error;
@@ -1363,8 +1226,7 @@
 }
 
 void
-XmlPrologStateInit(PROLOG_STATE *state)
-{
+XmlPrologStateInit(PROLOG_STATE *state) {
   state->handler = prolog0;
 #ifdef XML_DTD
   state->documentEntity = 1;
@@ -1376,8 +1238,7 @@
 #ifdef XML_DTD
 
 void
-XmlPrologStateInitExternalEntity(PROLOG_STATE *state)
-{
+XmlPrologStateInitExternalEntity(PROLOG_STATE *state) {
   state->handler = externalSubset0;
   state->documentEntity = 0;
   state->includeLevel = 0;
diff --git a/third_party/expat/files/lib/xmlrole.h b/third_party/expat/files/lib/xmlrole.h
index e5f048e..036aba64 100644
--- a/third_party/expat/files/lib/xmlrole.h
+++ b/third_party/expat/files/lib/xmlrole.h
@@ -36,7 +36,7 @@
 #ifdef __VMS
 /*      0        1         2         3      0        1         2         3
         1234567890123456789012345678901     1234567890123456789012345678901 */
-#define XmlPrologStateInitExternalEntity    XmlPrologStateInitExternalEnt
+#  define XmlPrologStateInitExternalEntity XmlPrologStateInitExternalEnt
 #endif
 
 #include "xmltok.h"
@@ -113,11 +113,8 @@
 };
 
 typedef struct prolog_state {
-  int (PTRCALL *handler) (struct prolog_state *state,
-                          int tok,
-                          const char *ptr,
-                          const char *end,
-                          const ENCODING *enc);
+  int(PTRCALL *handler)(struct prolog_state *state, int tok, const char *ptr,
+                        const char *end, const ENCODING *enc);
   unsigned level;
   int role_none;
 #ifdef XML_DTD
@@ -132,8 +129,8 @@
 void XmlPrologStateInitExternalEntity(PROLOG_STATE *);
 #endif /* XML_DTD */
 
-#define XmlTokenRole(state, tok, ptr, end, enc) \
- (((state)->handler)(state, tok, ptr, end, enc))
+#define XmlTokenRole(state, tok, ptr, end, enc)                                \
+  (((state)->handler)(state, tok, ptr, end, enc))
 
 #ifdef __cplusplus
 }
diff --git a/third_party/expat/files/lib/xmltok.c b/third_party/expat/files/lib/xmltok.c
index 6b415d8..11e9d1c 100644
--- a/third_party/expat/files/lib/xmltok.c
+++ b/third_party/expat/files/lib/xmltok.c
@@ -31,24 +31,23 @@
 */
 
 #include <stddef.h>
-#include <string.h>  /* memcpy */
+#include <string.h> /* memcpy */
 
 #if defined(_MSC_VER) && (_MSC_VER <= 1700)
-  /* for vs2012/11.0/1700 and earlier Visual Studio compilers */
-# define bool   int
-# define false  0
-# define true   1
+/* for vs2012/11.0/1700 and earlier Visual Studio compilers */
+#  define bool int
+#  define false 0
+#  define true 1
 #else
-# include <stdbool.h>
+#  include <stdbool.h>
 #endif
 
-
 #ifdef _WIN32
-#include "winconfig.h"
+#  include "winconfig.h"
 #else
-#ifdef HAVE_EXPAT_CONFIG_H
-#include <expat_config.h>
-#endif
+#  ifdef HAVE_EXPAT_CONFIG_H
+#    include <expat_config.h>
+#  endif
 #endif /* ndef _WIN32 */
 
 #include "expat_external.h"
@@ -57,58 +56,49 @@
 #include "nametab.h"
 
 #ifdef XML_DTD
-#define IGNORE_SECTION_TOK_VTABLE , PREFIX(ignoreSectionTok)
+#  define IGNORE_SECTION_TOK_VTABLE , PREFIX(ignoreSectionTok)
 #else
-#define IGNORE_SECTION_TOK_VTABLE /* as nothing */
+#  define IGNORE_SECTION_TOK_VTABLE /* as nothing */
 #endif
 
-#define VTABLE1 \
-  { PREFIX(prologTok), PREFIX(contentTok), \
-    PREFIX(cdataSectionTok) IGNORE_SECTION_TOK_VTABLE }, \
-  { PREFIX(attributeValueTok), PREFIX(entityValueTok) }, \
-  PREFIX(nameMatchesAscii), \
-  PREFIX(nameLength), \
-  PREFIX(skipS), \
-  PREFIX(getAtts), \
-  PREFIX(charRefNumber), \
-  PREFIX(predefinedEntityName), \
-  PREFIX(updatePosition), \
-  PREFIX(isPublicId)
+#define VTABLE1                                                                \
+  {PREFIX(prologTok), PREFIX(contentTok),                                      \
+   PREFIX(cdataSectionTok) IGNORE_SECTION_TOK_VTABLE},                         \
+      {PREFIX(attributeValueTok), PREFIX(entityValueTok)},                     \
+      PREFIX(nameMatchesAscii), PREFIX(nameLength), PREFIX(skipS),             \
+      PREFIX(getAtts), PREFIX(charRefNumber), PREFIX(predefinedEntityName),    \
+      PREFIX(updatePosition), PREFIX(isPublicId)
 
 #define VTABLE VTABLE1, PREFIX(toUtf8), PREFIX(toUtf16)
 
-#define UCS2_GET_NAMING(pages, hi, lo) \
-   (namingBitmap[(pages[hi] << 3) + ((lo) >> 5)] & (1u << ((lo) & 0x1F)))
+#define UCS2_GET_NAMING(pages, hi, lo)                                         \
+  (namingBitmap[(pages[hi] << 3) + ((lo) >> 5)] & (1u << ((lo)&0x1F)))
 
 /* A 2 byte UTF-8 representation splits the characters 11 bits between
    the bottom 5 and 6 bits of the bytes.  We need 8 bits to index into
    pages, 3 bits to add to that index and 5 bits to generate the mask.
 */
-#define UTF8_GET_NAMING2(pages, byte) \
-    (namingBitmap[((pages)[(((byte)[0]) >> 2) & 7] << 3) \
-                      + ((((byte)[0]) & 3) << 1) \
-                      + ((((byte)[1]) >> 5) & 1)] \
-         & (1u << (((byte)[1]) & 0x1F)))
+#define UTF8_GET_NAMING2(pages, byte)                                          \
+  (namingBitmap[((pages)[(((byte)[0]) >> 2) & 7] << 3)                         \
+                + ((((byte)[0]) & 3) << 1) + ((((byte)[1]) >> 5) & 1)]         \
+   & (1u << (((byte)[1]) & 0x1F)))
 
 /* A 3 byte UTF-8 representation splits the characters 16 bits between
    the bottom 4, 6 and 6 bits of the bytes.  We need 8 bits to index
    into pages, 3 bits to add to that index and 5 bits to generate the
    mask.
 */
-#define UTF8_GET_NAMING3(pages, byte) \
-  (namingBitmap[((pages)[((((byte)[0]) & 0xF) << 4) \
-                             + ((((byte)[1]) >> 2) & 0xF)] \
-                       << 3) \
-                      + ((((byte)[1]) & 3) << 1) \
-                      + ((((byte)[2]) >> 5) & 1)] \
-         & (1u << (((byte)[2]) & 0x1F)))
+#define UTF8_GET_NAMING3(pages, byte)                                          \
+  (namingBitmap                                                                \
+       [((pages)[((((byte)[0]) & 0xF) << 4) + ((((byte)[1]) >> 2) & 0xF)]      \
+         << 3)                                                                 \
+        + ((((byte)[1]) & 3) << 1) + ((((byte)[2]) >> 5) & 1)]                 \
+   & (1u << (((byte)[2]) & 0x1F)))
 
-#define UTF8_GET_NAMING(pages, p, n) \
-  ((n) == 2 \
-  ? UTF8_GET_NAMING2(pages, (const unsigned char *)(p)) \
-  : ((n) == 3 \
-     ? UTF8_GET_NAMING3(pages, (const unsigned char *)(p)) \
-     : 0))
+#define UTF8_GET_NAMING(pages, p, n)                                           \
+  ((n) == 2                                                                    \
+       ? UTF8_GET_NAMING2(pages, (const unsigned char *)(p))                   \
+       : ((n) == 3 ? UTF8_GET_NAMING3(pages, (const unsigned char *)(p)) : 0))
 
 /* Detection of invalid UTF-8 sequences is based on Table 3.1B
    of Unicode 3.2: http://www.unicode.org/unicode/reports/tr28/
@@ -120,88 +110,76 @@
      (A & 0xC0) == 0xC0  means A > 0xBF
 */
 
-#define UTF8_INVALID2(p) \
+#define UTF8_INVALID2(p)                                                       \
   ((*p) < 0xC2 || ((p)[1] & 0x80) == 0 || ((p)[1] & 0xC0) == 0xC0)
 
-#define UTF8_INVALID3(p) \
-  (((p)[2] & 0x80) == 0 \
-  || \
-  ((*p) == 0xEF && (p)[1] == 0xBF \
-    ? \
-    (p)[2] > 0xBD \
-    : \
-    ((p)[2] & 0xC0) == 0xC0) \
-  || \
-  ((*p) == 0xE0 \
-    ? \
-    (p)[1] < 0xA0 || ((p)[1] & 0xC0) == 0xC0 \
-    : \
-    ((p)[1] & 0x80) == 0 \
-    || \
-    ((*p) == 0xED ? (p)[1] > 0x9F : ((p)[1] & 0xC0) == 0xC0)))
+#define UTF8_INVALID3(p)                                                       \
+  (((p)[2] & 0x80) == 0                                                        \
+   || ((*p) == 0xEF && (p)[1] == 0xBF ? (p)[2] > 0xBD                          \
+                                      : ((p)[2] & 0xC0) == 0xC0)               \
+   || ((*p) == 0xE0                                                            \
+           ? (p)[1] < 0xA0 || ((p)[1] & 0xC0) == 0xC0                          \
+           : ((p)[1] & 0x80) == 0                                              \
+                 || ((*p) == 0xED ? (p)[1] > 0x9F : ((p)[1] & 0xC0) == 0xC0)))
 
-#define UTF8_INVALID4(p) \
-  (((p)[3] & 0x80) == 0 || ((p)[3] & 0xC0) == 0xC0 \
-  || \
-  ((p)[2] & 0x80) == 0 || ((p)[2] & 0xC0) == 0xC0 \
-  || \
-  ((*p) == 0xF0 \
-    ? \
-    (p)[1] < 0x90 || ((p)[1] & 0xC0) == 0xC0 \
-    : \
-    ((p)[1] & 0x80) == 0 \
-    || \
-    ((*p) == 0xF4 ? (p)[1] > 0x8F : ((p)[1] & 0xC0) == 0xC0)))
+#define UTF8_INVALID4(p)                                                       \
+  (((p)[3] & 0x80) == 0 || ((p)[3] & 0xC0) == 0xC0 || ((p)[2] & 0x80) == 0     \
+   || ((p)[2] & 0xC0) == 0xC0                                                  \
+   || ((*p) == 0xF0                                                            \
+           ? (p)[1] < 0x90 || ((p)[1] & 0xC0) == 0xC0                          \
+           : ((p)[1] & 0x80) == 0                                              \
+                 || ((*p) == 0xF4 ? (p)[1] > 0x8F : ((p)[1] & 0xC0) == 0xC0)))
 
 static int PTRFASTCALL
-isNever(const ENCODING *UNUSED_P(enc), const char *UNUSED_P(p))
-{
+isNever(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
+  UNUSED_P(p);
   return 0;
 }
 
 static int PTRFASTCALL
-utf8_isName2(const ENCODING *UNUSED_P(enc), const char *p)
-{
+utf8_isName2(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return UTF8_GET_NAMING2(namePages, (const unsigned char *)p);
 }
 
 static int PTRFASTCALL
-utf8_isName3(const ENCODING *UNUSED_P(enc), const char *p)
-{
+utf8_isName3(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return UTF8_GET_NAMING3(namePages, (const unsigned char *)p);
 }
 
 #define utf8_isName4 isNever
 
 static int PTRFASTCALL
-utf8_isNmstrt2(const ENCODING *UNUSED_P(enc), const char *p)
-{
+utf8_isNmstrt2(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return UTF8_GET_NAMING2(nmstrtPages, (const unsigned char *)p);
 }
 
 static int PTRFASTCALL
-utf8_isNmstrt3(const ENCODING *UNUSED_P(enc), const char *p)
-{
+utf8_isNmstrt3(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return UTF8_GET_NAMING3(nmstrtPages, (const unsigned char *)p);
 }
 
 #define utf8_isNmstrt4 isNever
 
 static int PTRFASTCALL
-utf8_isInvalid2(const ENCODING *UNUSED_P(enc), const char *p)
-{
+utf8_isInvalid2(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return UTF8_INVALID2((const unsigned char *)p);
 }
 
 static int PTRFASTCALL
-utf8_isInvalid3(const ENCODING *UNUSED_P(enc), const char *p)
-{
+utf8_isInvalid3(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return UTF8_INVALID3((const unsigned char *)p);
 }
 
 static int PTRFASTCALL
-utf8_isInvalid4(const ENCODING *UNUSED_P(enc), const char *p)
-{
+utf8_isInvalid4(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return UTF8_INVALID4((const unsigned char *)p);
 }
 
@@ -209,61 +187,44 @@
   ENCODING enc;
   unsigned char type[256];
 #ifdef XML_MIN_SIZE
-  int (PTRFASTCALL *byteType)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isNameMin)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isNmstrtMin)(const ENCODING *, const char *);
-  int (PTRFASTCALL *byteToAscii)(const ENCODING *, const char *);
-  int (PTRCALL *charMatches)(const ENCODING *, const char *, int);
+  int(PTRFASTCALL *byteType)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isNameMin)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isNmstrtMin)(const ENCODING *, const char *);
+  int(PTRFASTCALL *byteToAscii)(const ENCODING *, const char *);
+  int(PTRCALL *charMatches)(const ENCODING *, const char *, int);
 #endif /* XML_MIN_SIZE */
-  int (PTRFASTCALL *isName2)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isName3)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isName4)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isNmstrt2)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isNmstrt3)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isNmstrt4)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isInvalid2)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isInvalid3)(const ENCODING *, const char *);
-  int (PTRFASTCALL *isInvalid4)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isName2)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isName3)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isName4)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isNmstrt2)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isNmstrt3)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isNmstrt4)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isInvalid2)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isInvalid3)(const ENCODING *, const char *);
+  int(PTRFASTCALL *isInvalid4)(const ENCODING *, const char *);
 };
 
-#define AS_NORMAL_ENCODING(enc)   ((const struct normal_encoding *) (enc))
+#define AS_NORMAL_ENCODING(enc) ((const struct normal_encoding *)(enc))
 
 #ifdef XML_MIN_SIZE
 
-#define STANDARD_VTABLE(E) \
- E ## byteType, \
- E ## isNameMin, \
- E ## isNmstrtMin, \
- E ## byteToAscii, \
- E ## charMatches,
+#  define STANDARD_VTABLE(E)                                                   \
+    E##byteType, E##isNameMin, E##isNmstrtMin, E##byteToAscii, E##charMatches,
 
 #else
 
-#define STANDARD_VTABLE(E) /* as nothing */
+#  define STANDARD_VTABLE(E) /* as nothing */
 
 #endif
 
-#define NORMAL_VTABLE(E) \
- E ## isName2, \
- E ## isName3, \
- E ## isName4, \
- E ## isNmstrt2, \
- E ## isNmstrt3, \
- E ## isNmstrt4, \
- E ## isInvalid2, \
- E ## isInvalid3, \
- E ## isInvalid4
+#define NORMAL_VTABLE(E)                                                       \
+  E##isName2, E##isName3, E##isName4, E##isNmstrt2, E##isNmstrt3,              \
+      E##isNmstrt4, E##isInvalid2, E##isInvalid3, E##isInvalid4
 
-#define NULL_VTABLE \
- /* isName2 */ NULL, \
- /* isName3 */ NULL, \
- /* isName4 */ NULL, \
- /* isNmstrt2 */ NULL, \
- /* isNmstrt3 */ NULL, \
- /* isNmstrt4 */ NULL, \
- /* isInvalid2 */ NULL, \
- /* isInvalid3 */ NULL, \
- /* isInvalid4 */ NULL
+#define NULL_VTABLE                                                            \
+  /* isName2 */ NULL, /* isName3 */ NULL, /* isName4 */ NULL,                  \
+      /* isNmstrt2 */ NULL, /* isNmstrt3 */ NULL, /* isNmstrt4 */ NULL,        \
+      /* isInvalid2 */ NULL, /* isInvalid3 */ NULL, /* isInvalid4 */ NULL
 
 static int FASTCALL checkCharRefNumber(int);
 
@@ -271,75 +232,70 @@
 #include "ascii.h"
 
 #ifdef XML_MIN_SIZE
-#define sb_isNameMin isNever
-#define sb_isNmstrtMin isNever
+#  define sb_isNameMin isNever
+#  define sb_isNmstrtMin isNever
 #endif
 
 #ifdef XML_MIN_SIZE
-#define MINBPC(enc) ((enc)->minBytesPerChar)
+#  define MINBPC(enc) ((enc)->minBytesPerChar)
 #else
 /* minimum bytes per character */
-#define MINBPC(enc) 1
+#  define MINBPC(enc) 1
 #endif
 
-#define SB_BYTE_TYPE(enc, p) \
+#define SB_BYTE_TYPE(enc, p)                                                   \
   (((struct normal_encoding *)(enc))->type[(unsigned char)*(p)])
 
 #ifdef XML_MIN_SIZE
 static int PTRFASTCALL
-sb_byteType(const ENCODING *enc, const char *p)
-{
+sb_byteType(const ENCODING *enc, const char *p) {
   return SB_BYTE_TYPE(enc, p);
 }
-#define BYTE_TYPE(enc, p) \
- (AS_NORMAL_ENCODING(enc)->byteType(enc, p))
+#  define BYTE_TYPE(enc, p) (AS_NORMAL_ENCODING(enc)->byteType(enc, p))
 #else
-#define BYTE_TYPE(enc, p) SB_BYTE_TYPE(enc, p)
+#  define BYTE_TYPE(enc, p) SB_BYTE_TYPE(enc, p)
 #endif
 
 #ifdef XML_MIN_SIZE
-#define BYTE_TO_ASCII(enc, p) \
- (AS_NORMAL_ENCODING(enc)->byteToAscii(enc, p))
+#  define BYTE_TO_ASCII(enc, p) (AS_NORMAL_ENCODING(enc)->byteToAscii(enc, p))
 static int PTRFASTCALL
-sb_byteToAscii(const ENCODING *enc, const char *p)
-{
+sb_byteToAscii(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
   return *p;
 }
 #else
-#define BYTE_TO_ASCII(enc, p) (*(p))
+#  define BYTE_TO_ASCII(enc, p) (*(p))
 #endif
 
-#define IS_NAME_CHAR(enc, p, n) \
- (AS_NORMAL_ENCODING(enc)->isName ## n(enc, p))
-#define IS_NMSTRT_CHAR(enc, p, n) \
- (AS_NORMAL_ENCODING(enc)->isNmstrt ## n(enc, p))
-#define IS_INVALID_CHAR(enc, p, n) \
- (AS_NORMAL_ENCODING(enc)->isInvalid ## n(enc, p))
+#define IS_NAME_CHAR(enc, p, n) (AS_NORMAL_ENCODING(enc)->isName##n(enc, p))
+#define IS_NMSTRT_CHAR(enc, p, n) (AS_NORMAL_ENCODING(enc)->isNmstrt##n(enc, p))
+#define IS_INVALID_CHAR(enc, p, n)                                             \
+  (AS_NORMAL_ENCODING(enc)->isInvalid##n(enc, p))
 
 #ifdef XML_MIN_SIZE
-#define IS_NAME_CHAR_MINBPC(enc, p) \
- (AS_NORMAL_ENCODING(enc)->isNameMin(enc, p))
-#define IS_NMSTRT_CHAR_MINBPC(enc, p) \
- (AS_NORMAL_ENCODING(enc)->isNmstrtMin(enc, p))
+#  define IS_NAME_CHAR_MINBPC(enc, p)                                          \
+    (AS_NORMAL_ENCODING(enc)->isNameMin(enc, p))
+#  define IS_NMSTRT_CHAR_MINBPC(enc, p)                                        \
+    (AS_NORMAL_ENCODING(enc)->isNmstrtMin(enc, p))
 #else
-#define IS_NAME_CHAR_MINBPC(enc, p) (0)
-#define IS_NMSTRT_CHAR_MINBPC(enc, p) (0)
+#  define IS_NAME_CHAR_MINBPC(enc, p) (0)
+#  define IS_NMSTRT_CHAR_MINBPC(enc, p) (0)
 #endif
 
 #ifdef XML_MIN_SIZE
-#define CHAR_MATCHES(enc, p, c) \
- (AS_NORMAL_ENCODING(enc)->charMatches(enc, p, c))
+#  define CHAR_MATCHES(enc, p, c)                                              \
+    (AS_NORMAL_ENCODING(enc)->charMatches(enc, p, c))
 static int PTRCALL
-sb_charMatches(const ENCODING *enc, const char *p, int c)
-{
+sb_charMatches(const ENCODING *enc, const char *p, int c) {
+  UNUSED_P(enc);
   return *p == c;
 }
 #else
 /* c is an ASCII character */
-#define CHAR_MATCHES(enc, p, c) (*(p) == c)
+#  define CHAR_MATCHES(enc, p, c) (*(p) == c)
 #endif
 
-#define PREFIX(ident) normal_ ## ident
+#define PREFIX(ident) normal_##ident
 #define XML_TOK_IMPL_C
 #include "xmltok_impl.c"
 #undef XML_TOK_IMPL_C
@@ -354,42 +310,46 @@
 #undef IS_NMSTRT_CHAR_MINBPC
 #undef IS_INVALID_CHAR
 
-enum {  /* UTF8_cvalN is value of masked first byte of N byte sequence */
-  UTF8_cval1 = 0x00,
-  UTF8_cval2 = 0xc0,
-  UTF8_cval3 = 0xe0,
-  UTF8_cval4 = 0xf0
+enum { /* UTF8_cvalN is value of masked first byte of N byte sequence */
+       UTF8_cval1 = 0x00,
+       UTF8_cval2 = 0xc0,
+       UTF8_cval3 = 0xe0,
+       UTF8_cval4 = 0xf0
 };
 
 void
-_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef)
-{
-  const char * fromLim = *fromLimRef;
+_INTERNAL_trim_to_complete_utf8_characters(const char *from,
+                                           const char **fromLimRef) {
+  const char *fromLim = *fromLimRef;
   size_t walked = 0;
   for (; fromLim > from; fromLim--, walked++) {
     const unsigned char prev = (unsigned char)fromLim[-1];
-    if ((prev & 0xf8u) == 0xf0u) { /* 4-byte character, lead by 0b11110xxx byte */
+    if ((prev & 0xf8u)
+        == 0xf0u) { /* 4-byte character, lead by 0b11110xxx byte */
       if (walked + 1 >= 4) {
         fromLim += 4 - 1;
         break;
       } else {
         walked = 0;
       }
-    } else if ((prev & 0xf0u) == 0xe0u) { /* 3-byte character, lead by 0b1110xxxx byte */
+    } else if ((prev & 0xf0u)
+               == 0xe0u) { /* 3-byte character, lead by 0b1110xxxx byte */
       if (walked + 1 >= 3) {
         fromLim += 3 - 1;
         break;
       } else {
         walked = 0;
       }
-    } else if ((prev & 0xe0u) == 0xc0u) { /* 2-byte character, lead by 0b110xxxxx byte */
+    } else if ((prev & 0xe0u)
+               == 0xc0u) { /* 2-byte character, lead by 0b110xxxxx byte */
       if (walked + 1 >= 2) {
         fromLim += 2 - 1;
         break;
       } else {
         walked = 0;
       }
-    } else if ((prev & 0x80u) == 0x00u) { /* 1-byte character, matching 0b0xxxxxxx */
+    } else if ((prev & 0x80u)
+               == 0x00u) { /* 1-byte character, matching 0b0xxxxxxx */
       break;
     }
   }
@@ -397,16 +357,15 @@
 }
 
 static enum XML_Convert_Result PTRCALL
-utf8_toUtf8(const ENCODING *UNUSED_P(enc),
-            const char **fromP, const char *fromLim,
-            char **toP, const char *toLim)
-{
+utf8_toUtf8(const ENCODING *enc, const char **fromP, const char *fromLim,
+            char **toP, const char *toLim) {
   bool input_incomplete = false;
   bool output_exhausted = false;
 
   /* Avoid copying partial characters (due to limited space). */
   const ptrdiff_t bytesAvailable = fromLim - *fromP;
   const ptrdiff_t bytesStorable = toLim - *toP;
+  UNUSED_P(enc);
   if (bytesAvailable > bytesStorable) {
     fromLim = *fromP + bytesStorable;
     output_exhausted = true;
@@ -414,7 +373,7 @@
 
   /* Avoid copying partial characters (from incomplete input). */
   {
-    const char * const fromLimBefore = fromLim;
+    const char *const fromLimBefore = fromLim;
     _INTERNAL_trim_to_complete_utf8_characters(*fromP, &fromLim);
     if (fromLim < fromLimBefore) {
       input_incomplete = true;
@@ -428,7 +387,7 @@
     *toP += bytesToCopy;
   }
 
-  if (output_exhausted)  /* needs to go first */
+  if (output_exhausted) /* needs to go first */
     return XML_CONVERT_OUTPUT_EXHAUSTED;
   else if (input_incomplete)
     return XML_CONVERT_INPUT_INCOMPLETE;
@@ -437,10 +396,8 @@
 }
 
 static enum XML_Convert_Result PTRCALL
-utf8_toUtf16(const ENCODING *enc,
-             const char **fromP, const char *fromLim,
-             unsigned short **toP, const unsigned short *toLim)
-{
+utf8_toUtf16(const ENCODING *enc, const char **fromP, const char *fromLim,
+             unsigned short **toP, const unsigned short *toLim) {
   enum XML_Convert_Result res = XML_CONVERT_COMPLETED;
   unsigned short *to = *toP;
   const char *from = *fromP;
@@ -459,30 +416,28 @@
         res = XML_CONVERT_INPUT_INCOMPLETE;
         goto after;
       }
-      *to++ = (unsigned short)(((from[0] & 0xf) << 12)
-                               | ((from[1] & 0x3f) << 6) | (from[2] & 0x3f));
+      *to++ = (unsigned short)(((from[0] & 0xf) << 12) | ((from[1] & 0x3f) << 6)
+                               | (from[2] & 0x3f));
       from += 3;
       break;
-    case BT_LEAD4:
-      {
-        unsigned long n;
-        if (toLim - to < 2) {
-          res = XML_CONVERT_OUTPUT_EXHAUSTED;
-          goto after;
-        }
-        if (fromLim - from < 4) {
-          res = XML_CONVERT_INPUT_INCOMPLETE;
-          goto after;
-        }
-        n = ((from[0] & 0x7) << 18) | ((from[1] & 0x3f) << 12)
-            | ((from[2] & 0x3f) << 6) | (from[3] & 0x3f);
-        n -= 0x10000;
-        to[0] = (unsigned short)((n >> 10) | 0xD800);
-        to[1] = (unsigned short)((n & 0x3FF) | 0xDC00);
-        to += 2;
-        from += 4;
+    case BT_LEAD4: {
+      unsigned long n;
+      if (toLim - to < 2) {
+        res = XML_CONVERT_OUTPUT_EXHAUSTED;
+        goto after;
       }
-      break;
+      if (fromLim - from < 4) {
+        res = XML_CONVERT_INPUT_INCOMPLETE;
+        goto after;
+      }
+      n = ((from[0] & 0x7) << 18) | ((from[1] & 0x3f) << 12)
+          | ((from[2] & 0x3f) << 6) | (from[3] & 0x3f);
+      n -= 0x10000;
+      to[0] = (unsigned short)((n >> 10) | 0xD800);
+      to[1] = (unsigned short)((n & 0x3FF) | 0xDC00);
+      to += 2;
+      from += 4;
+    } break;
     default:
       *to++ = *from++;
       break;
@@ -497,56 +452,51 @@
 }
 
 #ifdef XML_NS
-static const struct normal_encoding utf8_encoding_ns = {
-  { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 },
-  {
-#include "asciitab.h"
-#include "utf8tab.h"
-  },
-  STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)
-};
+static const struct normal_encoding utf8_encoding_ns
+    = {{VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0},
+       {
+#  include "asciitab.h"
+#  include "utf8tab.h"
+       },
+       STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)};
 #endif
 
-static const struct normal_encoding utf8_encoding = {
-  { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 },
-  {
+static const struct normal_encoding utf8_encoding
+    = {{VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0},
+       {
 #define BT_COLON BT_NMSTRT
 #include "asciitab.h"
 #undef BT_COLON
 #include "utf8tab.h"
-  },
-  STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)
-};
+       },
+       STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)};
 
 #ifdef XML_NS
 
-static const struct normal_encoding internal_utf8_encoding_ns = {
-  { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 },
-  {
-#include "iasciitab.h"
-#include "utf8tab.h"
-  },
-  STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)
-};
+static const struct normal_encoding internal_utf8_encoding_ns
+    = {{VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0},
+       {
+#  include "iasciitab.h"
+#  include "utf8tab.h"
+       },
+       STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)};
 
 #endif
 
-static const struct normal_encoding internal_utf8_encoding = {
-  { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 },
-  {
+static const struct normal_encoding internal_utf8_encoding
+    = {{VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0},
+       {
 #define BT_COLON BT_NMSTRT
 #include "iasciitab.h"
 #undef BT_COLON
 #include "utf8tab.h"
-  },
-  STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)
-};
+       },
+       STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_)};
 
 static enum XML_Convert_Result PTRCALL
-latin1_toUtf8(const ENCODING *UNUSED_P(enc),
-              const char **fromP, const char *fromLim,
-              char **toP, const char *toLim)
-{
+latin1_toUtf8(const ENCODING *enc, const char **fromP, const char *fromLim,
+              char **toP, const char *toLim) {
+  UNUSED_P(enc);
   for (;;) {
     unsigned char c;
     if (*fromP == fromLim)
@@ -558,8 +508,7 @@
       *(*toP)++ = (char)((c >> 6) | UTF8_cval2);
       *(*toP)++ = (char)((c & 0x3f) | 0x80);
       (*fromP)++;
-    }
-    else {
+    } else {
       if (*toP == toLim)
         return XML_CONVERT_OUTPUT_EXHAUSTED;
       *(*toP)++ = *(*fromP)++;
@@ -568,10 +517,9 @@
 }
 
 static enum XML_Convert_Result PTRCALL
-latin1_toUtf16(const ENCODING *UNUSED_P(enc),
-               const char **fromP, const char *fromLim,
-               unsigned short **toP, const unsigned short *toLim)
-{
+latin1_toUtf16(const ENCODING *enc, const char **fromP, const char *fromLim,
+               unsigned short **toP, const unsigned short *toLim) {
+  UNUSED_P(enc);
   while (*fromP < fromLim && *toP < toLim)
     *(*toP)++ = (unsigned char)*(*fromP)++;
 
@@ -583,33 +531,30 @@
 
 #ifdef XML_NS
 
-static const struct normal_encoding latin1_encoding_ns = {
-  { VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0 },
-  {
-#include "asciitab.h"
-#include "latin1tab.h"
-  },
-  STANDARD_VTABLE(sb_) NULL_VTABLE
-};
+static const struct normal_encoding latin1_encoding_ns
+    = {{VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0},
+       {
+#  include "asciitab.h"
+#  include "latin1tab.h"
+       },
+       STANDARD_VTABLE(sb_) NULL_VTABLE};
 
 #endif
 
-static const struct normal_encoding latin1_encoding = {
-  { VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0 },
-  {
+static const struct normal_encoding latin1_encoding
+    = {{VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0},
+       {
 #define BT_COLON BT_NMSTRT
 #include "asciitab.h"
 #undef BT_COLON
 #include "latin1tab.h"
-  },
-  STANDARD_VTABLE(sb_) NULL_VTABLE
-};
+       },
+       STANDARD_VTABLE(sb_) NULL_VTABLE};
 
 static enum XML_Convert_Result PTRCALL
-ascii_toUtf8(const ENCODING *UNUSED_P(enc),
-             const char **fromP, const char *fromLim,
-             char **toP, const char *toLim)
-{
+ascii_toUtf8(const ENCODING *enc, const char **fromP, const char *fromLim,
+             char **toP, const char *toLim) {
+  UNUSED_P(enc);
   while (*fromP < fromLim && *toP < toLim)
     *(*toP)++ = *(*fromP)++;
 
@@ -621,40 +566,45 @@
 
 #ifdef XML_NS
 
-static const struct normal_encoding ascii_encoding_ns = {
-  { VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0 },
-  {
-#include "asciitab.h"
-/* BT_NONXML == 0 */
-  },
-  STANDARD_VTABLE(sb_) NULL_VTABLE
-};
+static const struct normal_encoding ascii_encoding_ns
+    = {{VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0},
+       {
+#  include "asciitab.h"
+           /* BT_NONXML == 0 */
+       },
+       STANDARD_VTABLE(sb_) NULL_VTABLE};
 
 #endif
 
-static const struct normal_encoding ascii_encoding = {
-  { VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0 },
-  {
+static const struct normal_encoding ascii_encoding
+    = {{VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0},
+       {
 #define BT_COLON BT_NMSTRT
 #include "asciitab.h"
 #undef BT_COLON
-/* BT_NONXML == 0 */
-  },
-  STANDARD_VTABLE(sb_) NULL_VTABLE
-};
+           /* BT_NONXML == 0 */
+       },
+       STANDARD_VTABLE(sb_) NULL_VTABLE};
 
 static int PTRFASTCALL
-unicode_byte_type(char hi, char lo)
-{
+unicode_byte_type(char hi, char lo) {
   switch ((unsigned char)hi) {
-  case 0xD8: case 0xD9: case 0xDA: case 0xDB:
+  /* 0xD800–0xDBFF first 16-bit code unit or high surrogate (W1) */
+  case 0xD8:
+  case 0xD9:
+  case 0xDA:
+  case 0xDB:
     return BT_LEAD4;
-  case 0xDC: case 0xDD: case 0xDE: case 0xDF:
+  /* 0xDC00–0xDFFF second 16-bit code unit or low surrogate (W2) */
+  case 0xDC:
+  case 0xDD:
+  case 0xDE:
+  case 0xDF:
     return BT_TRAIL;
   case 0xFF:
     switch ((unsigned char)lo) {
-    case 0xFF:
-    case 0xFE:
+    case 0xFF: /* noncharacter-FFFF */
+    case 0xFE: /* noncharacter-FFFE */
       return BT_NONXML;
     }
     break;
@@ -662,102 +612,105 @@
   return BT_NONASCII;
 }
 
-#define DEFINE_UTF16_TO_UTF8(E) \
-static enum XML_Convert_Result  PTRCALL \
-E ## toUtf8(const ENCODING *UNUSED_P(enc), \
-            const char **fromP, const char *fromLim, \
-            char **toP, const char *toLim) \
-{ \
-  const char *from = *fromP; \
-  fromLim = from + (((fromLim - from) >> 1) << 1);  /* shrink to even */ \
-  for (; from < fromLim; from += 2) { \
-    int plane; \
-    unsigned char lo2; \
-    unsigned char lo = GET_LO(from); \
-    unsigned char hi = GET_HI(from); \
-    switch (hi) { \
-    case 0: \
-      if (lo < 0x80) { \
-        if (*toP == toLim) { \
-          *fromP = from; \
-          return XML_CONVERT_OUTPUT_EXHAUSTED; \
-        } \
-        *(*toP)++ = lo; \
-        break; \
-      } \
-      /* fall through */ \
-    case 0x1: case 0x2: case 0x3: \
-    case 0x4: case 0x5: case 0x6: case 0x7: \
-      if (toLim -  *toP < 2) { \
-        *fromP = from; \
-        return XML_CONVERT_OUTPUT_EXHAUSTED; \
-      } \
-      *(*toP)++ = ((lo >> 6) | (hi << 2) |  UTF8_cval2); \
-      *(*toP)++ = ((lo & 0x3f) | 0x80); \
-      break; \
-    default: \
-      if (toLim -  *toP < 3)  { \
-        *fromP = from; \
-        return XML_CONVERT_OUTPUT_EXHAUSTED; \
-      } \
-      /* 16 bits divided 4, 6, 6 amongst 3 bytes */ \
-      *(*toP)++ = ((hi >> 4) | UTF8_cval3); \
-      *(*toP)++ = (((hi & 0xf) << 2) | (lo >> 6) | 0x80); \
-      *(*toP)++ = ((lo & 0x3f) | 0x80); \
-      break; \
-    case 0xD8: case 0xD9: case 0xDA: case 0xDB: \
-      if (toLim -  *toP < 4) { \
-        *fromP = from; \
-        return XML_CONVERT_OUTPUT_EXHAUSTED; \
-      } \
-      if (fromLim - from < 4) { \
-        *fromP = from; \
-        return XML_CONVERT_INPUT_INCOMPLETE; \
-      } \
-      plane = (((hi & 0x3) << 2) | ((lo >> 6) & 0x3)) + 1; \
-      *(*toP)++ = ((plane >> 2) | UTF8_cval4); \
-      *(*toP)++ = (((lo >> 2) & 0xF) | ((plane & 0x3) << 4) | 0x80); \
-      from += 2; \
-      lo2 = GET_LO(from); \
-      *(*toP)++ = (((lo & 0x3) << 4) \
-                   | ((GET_HI(from) & 0x3) << 2) \
-                   | (lo2 >> 6) \
-                   | 0x80); \
-      *(*toP)++ = ((lo2 & 0x3f) | 0x80); \
-      break; \
-    } \
-  } \
-  *fromP = from; \
-  if (from < fromLim) \
-    return XML_CONVERT_INPUT_INCOMPLETE; \
-  else \
-    return XML_CONVERT_COMPLETED; \
-}
+#define DEFINE_UTF16_TO_UTF8(E)                                                \
+  static enum XML_Convert_Result PTRCALL E##toUtf8(                            \
+      const ENCODING *enc, const char **fromP, const char *fromLim,            \
+      char **toP, const char *toLim) {                                         \
+    const char *from = *fromP;                                                 \
+    UNUSED_P(enc);                                                             \
+    fromLim = from + (((fromLim - from) >> 1) << 1); /* shrink to even */      \
+    for (; from < fromLim; from += 2) {                                        \
+      int plane;                                                               \
+      unsigned char lo2;                                                       \
+      unsigned char lo = GET_LO(from);                                         \
+      unsigned char hi = GET_HI(from);                                         \
+      switch (hi) {                                                            \
+      case 0:                                                                  \
+        if (lo < 0x80) {                                                       \
+          if (*toP == toLim) {                                                 \
+            *fromP = from;                                                     \
+            return XML_CONVERT_OUTPUT_EXHAUSTED;                               \
+          }                                                                    \
+          *(*toP)++ = lo;                                                      \
+          break;                                                               \
+        }                                                                      \
+        /* fall through */                                                     \
+      case 0x1:                                                                \
+      case 0x2:                                                                \
+      case 0x3:                                                                \
+      case 0x4:                                                                \
+      case 0x5:                                                                \
+      case 0x6:                                                                \
+      case 0x7:                                                                \
+        if (toLim - *toP < 2) {                                                \
+          *fromP = from;                                                       \
+          return XML_CONVERT_OUTPUT_EXHAUSTED;                                 \
+        }                                                                      \
+        *(*toP)++ = ((lo >> 6) | (hi << 2) | UTF8_cval2);                      \
+        *(*toP)++ = ((lo & 0x3f) | 0x80);                                      \
+        break;                                                                 \
+      default:                                                                 \
+        if (toLim - *toP < 3) {                                                \
+          *fromP = from;                                                       \
+          return XML_CONVERT_OUTPUT_EXHAUSTED;                                 \
+        }                                                                      \
+        /* 16 bits divided 4, 6, 6 amongst 3 bytes */                          \
+        *(*toP)++ = ((hi >> 4) | UTF8_cval3);                                  \
+        *(*toP)++ = (((hi & 0xf) << 2) | (lo >> 6) | 0x80);                    \
+        *(*toP)++ = ((lo & 0x3f) | 0x80);                                      \
+        break;                                                                 \
+      case 0xD8:                                                               \
+      case 0xD9:                                                               \
+      case 0xDA:                                                               \
+      case 0xDB:                                                               \
+        if (toLim - *toP < 4) {                                                \
+          *fromP = from;                                                       \
+          return XML_CONVERT_OUTPUT_EXHAUSTED;                                 \
+        }                                                                      \
+        if (fromLim - from < 4) {                                              \
+          *fromP = from;                                                       \
+          return XML_CONVERT_INPUT_INCOMPLETE;                                 \
+        }                                                                      \
+        plane = (((hi & 0x3) << 2) | ((lo >> 6) & 0x3)) + 1;                   \
+        *(*toP)++ = (char)((plane >> 2) | UTF8_cval4);                         \
+        *(*toP)++ = (((lo >> 2) & 0xF) | ((plane & 0x3) << 4) | 0x80);         \
+        from += 2;                                                             \
+        lo2 = GET_LO(from);                                                    \
+        *(*toP)++ = (((lo & 0x3) << 4) | ((GET_HI(from) & 0x3) << 2)           \
+                     | (lo2 >> 6) | 0x80);                                     \
+        *(*toP)++ = ((lo2 & 0x3f) | 0x80);                                     \
+        break;                                                                 \
+      }                                                                        \
+    }                                                                          \
+    *fromP = from;                                                             \
+    if (from < fromLim)                                                        \
+      return XML_CONVERT_INPUT_INCOMPLETE;                                     \
+    else                                                                       \
+      return XML_CONVERT_COMPLETED;                                            \
+  }
 
-#define DEFINE_UTF16_TO_UTF16(E) \
-static enum XML_Convert_Result  PTRCALL \
-E ## toUtf16(const ENCODING *UNUSED_P(enc), \
-             const char **fromP, const char *fromLim, \
-             unsigned short **toP, const unsigned short *toLim) \
-{ \
-  enum XML_Convert_Result res = XML_CONVERT_COMPLETED; \
-  fromLim = *fromP + (((fromLim - *fromP) >> 1) << 1);  /* shrink to even */ \
-  /* Avoid copying first half only of surrogate */ \
-  if (fromLim - *fromP > ((toLim - *toP) << 1) \
-      && (GET_HI(fromLim - 2) & 0xF8) == 0xD8) { \
-    fromLim -= 2; \
-    res = XML_CONVERT_INPUT_INCOMPLETE; \
-  } \
-  for (; *fromP < fromLim && *toP < toLim; *fromP += 2) \
-    *(*toP)++ = (GET_HI(*fromP) << 8) | GET_LO(*fromP); \
-  if ((*toP == toLim) && (*fromP < fromLim)) \
-    return XML_CONVERT_OUTPUT_EXHAUSTED; \
-  else \
-    return res; \
-}
+#define DEFINE_UTF16_TO_UTF16(E)                                               \
+  static enum XML_Convert_Result PTRCALL E##toUtf16(                           \
+      const ENCODING *enc, const char **fromP, const char *fromLim,            \
+      unsigned short **toP, const unsigned short *toLim) {                     \
+    enum XML_Convert_Result res = XML_CONVERT_COMPLETED;                       \
+    UNUSED_P(enc);                                                             \
+    fromLim = *fromP + (((fromLim - *fromP) >> 1) << 1); /* shrink to even */  \
+    /* Avoid copying first half only of surrogate */                           \
+    if (fromLim - *fromP > ((toLim - *toP) << 1)                               \
+        && (GET_HI(fromLim - 2) & 0xF8) == 0xD8) {                             \
+      fromLim -= 2;                                                            \
+      res = XML_CONVERT_INPUT_INCOMPLETE;                                      \
+    }                                                                          \
+    for (; *fromP < fromLim && *toP < toLim; *fromP += 2)                      \
+      *(*toP)++ = (GET_HI(*fromP) << 8) | GET_LO(*fromP);                      \
+    if ((*toP == toLim) && (*fromP < fromLim))                                 \
+      return XML_CONVERT_OUTPUT_EXHAUSTED;                                     \
+    else                                                                       \
+      return res;                                                              \
+  }
 
-#define SET2(ptr, ch) \
-  (((ptr)[0] = ((ch) & 0xff)), ((ptr)[1] = ((ch) >> 8)))
+#define SET2(ptr, ch) (((ptr)[0] = ((ch)&0xff)), ((ptr)[1] = ((ch) >> 8)))
 #define GET_LO(ptr) ((unsigned char)(ptr)[0])
 #define GET_HI(ptr) ((unsigned char)(ptr)[1])
 
@@ -768,8 +721,7 @@
 #undef GET_LO
 #undef GET_HI
 
-#define SET2(ptr, ch) \
-  (((ptr)[0] = ((ch) >> 8)), ((ptr)[1] = ((ch) & 0xFF)))
+#define SET2(ptr, ch) (((ptr)[0] = ((ch) >> 8)), ((ptr)[1] = ((ch)&0xFF)))
 #define GET_LO(ptr) ((unsigned char)(ptr)[1])
 #define GET_HI(ptr) ((unsigned char)(ptr)[0])
 
@@ -780,292 +732,279 @@
 #undef GET_LO
 #undef GET_HI
 
-#define LITTLE2_BYTE_TYPE(enc, p) \
- ((p)[1] == 0 \
-  ? ((struct normal_encoding *)(enc))->type[(unsigned char)*(p)] \
-  : unicode_byte_type((p)[1], (p)[0]))
-#define LITTLE2_BYTE_TO_ASCII(enc, p) ((p)[1] == 0 ? (p)[0] : -1)
-#define LITTLE2_CHAR_MATCHES(enc, p, c) ((p)[1] == 0 && (p)[0] == c)
-#define LITTLE2_IS_NAME_CHAR_MINBPC(enc, p) \
+#define LITTLE2_BYTE_TYPE(enc, p)                                              \
+  ((p)[1] == 0 ? ((struct normal_encoding *)(enc))->type[(unsigned char)*(p)]  \
+               : unicode_byte_type((p)[1], (p)[0]))
+#define LITTLE2_BYTE_TO_ASCII(p) ((p)[1] == 0 ? (p)[0] : -1)
+#define LITTLE2_CHAR_MATCHES(p, c) ((p)[1] == 0 && (p)[0] == c)
+#define LITTLE2_IS_NAME_CHAR_MINBPC(p)                                         \
   UCS2_GET_NAMING(namePages, (unsigned char)p[1], (unsigned char)p[0])
-#define LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p) \
+#define LITTLE2_IS_NMSTRT_CHAR_MINBPC(p)                                       \
   UCS2_GET_NAMING(nmstrtPages, (unsigned char)p[1], (unsigned char)p[0])
 
 #ifdef XML_MIN_SIZE
 
 static int PTRFASTCALL
-little2_byteType(const ENCODING *enc, const char *p)
-{
+little2_byteType(const ENCODING *enc, const char *p) {
   return LITTLE2_BYTE_TYPE(enc, p);
 }
 
 static int PTRFASTCALL
-little2_byteToAscii(const ENCODING *enc, const char *p)
-{
-  return LITTLE2_BYTE_TO_ASCII(enc, p);
+little2_byteToAscii(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
+  return LITTLE2_BYTE_TO_ASCII(p);
 }
 
 static int PTRCALL
-little2_charMatches(const ENCODING *enc, const char *p, int c)
-{
-  return LITTLE2_CHAR_MATCHES(enc, p, c);
+little2_charMatches(const ENCODING *enc, const char *p, int c) {
+  UNUSED_P(enc);
+  return LITTLE2_CHAR_MATCHES(p, c);
 }
 
 static int PTRFASTCALL
-little2_isNameMin(const ENCODING *enc, const char *p)
-{
-  return LITTLE2_IS_NAME_CHAR_MINBPC(enc, p);
+little2_isNameMin(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
+  return LITTLE2_IS_NAME_CHAR_MINBPC(p);
 }
 
 static int PTRFASTCALL
-little2_isNmstrtMin(const ENCODING *enc, const char *p)
-{
-  return LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p);
+little2_isNmstrtMin(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
+  return LITTLE2_IS_NMSTRT_CHAR_MINBPC(p);
 }
 
-#undef VTABLE
-#define VTABLE VTABLE1, little2_toUtf8, little2_toUtf16
+#  undef VTABLE
+#  define VTABLE VTABLE1, little2_toUtf8, little2_toUtf16
 
 #else /* not XML_MIN_SIZE */
 
-#undef PREFIX
-#define PREFIX(ident) little2_ ## ident
-#define MINBPC(enc) 2
+#  undef PREFIX
+#  define PREFIX(ident) little2_##ident
+#  define MINBPC(enc) 2
 /* CHAR_MATCHES is guaranteed to have MINBPC bytes available. */
-#define BYTE_TYPE(enc, p) LITTLE2_BYTE_TYPE(enc, p)
-#define BYTE_TO_ASCII(enc, p) LITTLE2_BYTE_TO_ASCII(enc, p)
-#define CHAR_MATCHES(enc, p, c) LITTLE2_CHAR_MATCHES(enc, p, c)
-#define IS_NAME_CHAR(enc, p, n) 0
-#define IS_NAME_CHAR_MINBPC(enc, p) LITTLE2_IS_NAME_CHAR_MINBPC(enc, p)
-#define IS_NMSTRT_CHAR(enc, p, n) (0)
-#define IS_NMSTRT_CHAR_MINBPC(enc, p) LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p)
+#  define BYTE_TYPE(enc, p) LITTLE2_BYTE_TYPE(enc, p)
+#  define BYTE_TO_ASCII(enc, p) LITTLE2_BYTE_TO_ASCII(p)
+#  define CHAR_MATCHES(enc, p, c) LITTLE2_CHAR_MATCHES(p, c)
+#  define IS_NAME_CHAR(enc, p, n) 0
+#  define IS_NAME_CHAR_MINBPC(enc, p) LITTLE2_IS_NAME_CHAR_MINBPC(p)
+#  define IS_NMSTRT_CHAR(enc, p, n) (0)
+#  define IS_NMSTRT_CHAR_MINBPC(enc, p) LITTLE2_IS_NMSTRT_CHAR_MINBPC(p)
 
-#define XML_TOK_IMPL_C
-#include "xmltok_impl.c"
-#undef XML_TOK_IMPL_C
+#  define XML_TOK_IMPL_C
+#  include "xmltok_impl.c"
+#  undef XML_TOK_IMPL_C
 
-#undef MINBPC
-#undef BYTE_TYPE
-#undef BYTE_TO_ASCII
-#undef CHAR_MATCHES
-#undef IS_NAME_CHAR
-#undef IS_NAME_CHAR_MINBPC
-#undef IS_NMSTRT_CHAR
-#undef IS_NMSTRT_CHAR_MINBPC
-#undef IS_INVALID_CHAR
+#  undef MINBPC
+#  undef BYTE_TYPE
+#  undef BYTE_TO_ASCII
+#  undef CHAR_MATCHES
+#  undef IS_NAME_CHAR
+#  undef IS_NAME_CHAR_MINBPC
+#  undef IS_NMSTRT_CHAR
+#  undef IS_NMSTRT_CHAR_MINBPC
+#  undef IS_INVALID_CHAR
 
 #endif /* not XML_MIN_SIZE */
 
 #ifdef XML_NS
 
-static const struct normal_encoding little2_encoding_ns = {
-  { VTABLE, 2, 0,
-#if BYTEORDER == 1234
-    1
-#else
-    0
-#endif
-  },
-  {
-#include "asciitab.h"
-#include "latin1tab.h"
-  },
-  STANDARD_VTABLE(little2_) NULL_VTABLE
-};
+static const struct normal_encoding little2_encoding_ns
+    = {{VTABLE, 2, 0,
+#  if BYTEORDER == 1234
+        1
+#  else
+        0
+#  endif
+       },
+       {
+#  include "asciitab.h"
+#  include "latin1tab.h"
+       },
+       STANDARD_VTABLE(little2_) NULL_VTABLE};
 
 #endif
 
-static const struct normal_encoding little2_encoding = {
-  { VTABLE, 2, 0,
+static const struct normal_encoding little2_encoding
+    = {{VTABLE, 2, 0,
 #if BYTEORDER == 1234
-    1
+        1
 #else
-    0
+        0
 #endif
-  },
-  {
+       },
+       {
 #define BT_COLON BT_NMSTRT
 #include "asciitab.h"
 #undef BT_COLON
 #include "latin1tab.h"
-  },
-  STANDARD_VTABLE(little2_) NULL_VTABLE
-};
+       },
+       STANDARD_VTABLE(little2_) NULL_VTABLE};
 
 #if BYTEORDER != 4321
 
-#ifdef XML_NS
+#  ifdef XML_NS
 
-static const struct normal_encoding internal_little2_encoding_ns = {
-  { VTABLE, 2, 0, 1 },
-  {
-#include "iasciitab.h"
-#include "latin1tab.h"
-  },
-  STANDARD_VTABLE(little2_) NULL_VTABLE
-};
+static const struct normal_encoding internal_little2_encoding_ns
+    = {{VTABLE, 2, 0, 1},
+       {
+#    include "iasciitab.h"
+#    include "latin1tab.h"
+       },
+       STANDARD_VTABLE(little2_) NULL_VTABLE};
+
+#  endif
+
+static const struct normal_encoding internal_little2_encoding
+    = {{VTABLE, 2, 0, 1},
+       {
+#  define BT_COLON BT_NMSTRT
+#  include "iasciitab.h"
+#  undef BT_COLON
+#  include "latin1tab.h"
+       },
+       STANDARD_VTABLE(little2_) NULL_VTABLE};
 
 #endif
 
-static const struct normal_encoding internal_little2_encoding = {
-  { VTABLE, 2, 0, 1 },
-  {
-#define BT_COLON BT_NMSTRT
-#include "iasciitab.h"
-#undef BT_COLON
-#include "latin1tab.h"
-  },
-  STANDARD_VTABLE(little2_) NULL_VTABLE
-};
-
-#endif
-
-
-#define BIG2_BYTE_TYPE(enc, p) \
- ((p)[0] == 0 \
-  ? ((struct normal_encoding *)(enc))->type[(unsigned char)(p)[1]] \
-  : unicode_byte_type((p)[0], (p)[1]))
-#define BIG2_BYTE_TO_ASCII(enc, p) ((p)[0] == 0 ? (p)[1] : -1)
-#define BIG2_CHAR_MATCHES(enc, p, c) ((p)[0] == 0 && (p)[1] == c)
-#define BIG2_IS_NAME_CHAR_MINBPC(enc, p) \
+#define BIG2_BYTE_TYPE(enc, p)                                                 \
+  ((p)[0] == 0                                                                 \
+       ? ((struct normal_encoding *)(enc))->type[(unsigned char)(p)[1]]        \
+       : unicode_byte_type((p)[0], (p)[1]))
+#define BIG2_BYTE_TO_ASCII(p) ((p)[0] == 0 ? (p)[1] : -1)
+#define BIG2_CHAR_MATCHES(p, c) ((p)[0] == 0 && (p)[1] == c)
+#define BIG2_IS_NAME_CHAR_MINBPC(p)                                            \
   UCS2_GET_NAMING(namePages, (unsigned char)p[0], (unsigned char)p[1])
-#define BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p) \
+#define BIG2_IS_NMSTRT_CHAR_MINBPC(p)                                          \
   UCS2_GET_NAMING(nmstrtPages, (unsigned char)p[0], (unsigned char)p[1])
 
 #ifdef XML_MIN_SIZE
 
 static int PTRFASTCALL
-big2_byteType(const ENCODING *enc, const char *p)
-{
+big2_byteType(const ENCODING *enc, const char *p) {
   return BIG2_BYTE_TYPE(enc, p);
 }
 
 static int PTRFASTCALL
-big2_byteToAscii(const ENCODING *enc, const char *p)
-{
-  return BIG2_BYTE_TO_ASCII(enc, p);
+big2_byteToAscii(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
+  return BIG2_BYTE_TO_ASCII(p);
 }
 
 static int PTRCALL
-big2_charMatches(const ENCODING *enc, const char *p, int c)
-{
-  return BIG2_CHAR_MATCHES(enc, p, c);
+big2_charMatches(const ENCODING *enc, const char *p, int c) {
+  UNUSED_P(enc);
+  return BIG2_CHAR_MATCHES(p, c);
 }
 
 static int PTRFASTCALL
-big2_isNameMin(const ENCODING *enc, const char *p)
-{
-  return BIG2_IS_NAME_CHAR_MINBPC(enc, p);
+big2_isNameMin(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
+  return BIG2_IS_NAME_CHAR_MINBPC(p);
 }
 
 static int PTRFASTCALL
-big2_isNmstrtMin(const ENCODING *enc, const char *p)
-{
-  return BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p);
+big2_isNmstrtMin(const ENCODING *enc, const char *p) {
+  UNUSED_P(enc);
+  return BIG2_IS_NMSTRT_CHAR_MINBPC(p);
 }
 
-#undef VTABLE
-#define VTABLE VTABLE1, big2_toUtf8, big2_toUtf16
+#  undef VTABLE
+#  define VTABLE VTABLE1, big2_toUtf8, big2_toUtf16
 
 #else /* not XML_MIN_SIZE */
 
-#undef PREFIX
-#define PREFIX(ident) big2_ ## ident
-#define MINBPC(enc) 2
+#  undef PREFIX
+#  define PREFIX(ident) big2_##ident
+#  define MINBPC(enc) 2
 /* CHAR_MATCHES is guaranteed to have MINBPC bytes available. */
-#define BYTE_TYPE(enc, p) BIG2_BYTE_TYPE(enc, p)
-#define BYTE_TO_ASCII(enc, p) BIG2_BYTE_TO_ASCII(enc, p)
-#define CHAR_MATCHES(enc, p, c) BIG2_CHAR_MATCHES(enc, p, c)
-#define IS_NAME_CHAR(enc, p, n) 0
-#define IS_NAME_CHAR_MINBPC(enc, p) BIG2_IS_NAME_CHAR_MINBPC(enc, p)
-#define IS_NMSTRT_CHAR(enc, p, n) (0)
-#define IS_NMSTRT_CHAR_MINBPC(enc, p) BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p)
+#  define BYTE_TYPE(enc, p) BIG2_BYTE_TYPE(enc, p)
+#  define BYTE_TO_ASCII(enc, p) BIG2_BYTE_TO_ASCII(p)
+#  define CHAR_MATCHES(enc, p, c) BIG2_CHAR_MATCHES(p, c)
+#  define IS_NAME_CHAR(enc, p, n) 0
+#  define IS_NAME_CHAR_MINBPC(enc, p) BIG2_IS_NAME_CHAR_MINBPC(p)
+#  define IS_NMSTRT_CHAR(enc, p, n) (0)
+#  define IS_NMSTRT_CHAR_MINBPC(enc, p) BIG2_IS_NMSTRT_CHAR_MINBPC(p)
 
-#define XML_TOK_IMPL_C
-#include "xmltok_impl.c"
-#undef XML_TOK_IMPL_C
+#  define XML_TOK_IMPL_C
+#  include "xmltok_impl.c"
+#  undef XML_TOK_IMPL_C
 
-#undef MINBPC
-#undef BYTE_TYPE
-#undef BYTE_TO_ASCII
-#undef CHAR_MATCHES
-#undef IS_NAME_CHAR
-#undef IS_NAME_CHAR_MINBPC
-#undef IS_NMSTRT_CHAR
-#undef IS_NMSTRT_CHAR_MINBPC
-#undef IS_INVALID_CHAR
+#  undef MINBPC
+#  undef BYTE_TYPE
+#  undef BYTE_TO_ASCII
+#  undef CHAR_MATCHES
+#  undef IS_NAME_CHAR
+#  undef IS_NAME_CHAR_MINBPC
+#  undef IS_NMSTRT_CHAR
+#  undef IS_NMSTRT_CHAR_MINBPC
+#  undef IS_INVALID_CHAR
 
 #endif /* not XML_MIN_SIZE */
 
 #ifdef XML_NS
 
-static const struct normal_encoding big2_encoding_ns = {
-  { VTABLE, 2, 0,
-#if BYTEORDER == 4321
-  1
-#else
-  0
-#endif
-  },
-  {
-#include "asciitab.h"
-#include "latin1tab.h"
-  },
-  STANDARD_VTABLE(big2_) NULL_VTABLE
-};
+static const struct normal_encoding big2_encoding_ns
+    = {{VTABLE, 2, 0,
+#  if BYTEORDER == 4321
+        1
+#  else
+        0
+#  endif
+       },
+       {
+#  include "asciitab.h"
+#  include "latin1tab.h"
+       },
+       STANDARD_VTABLE(big2_) NULL_VTABLE};
 
 #endif
 
-static const struct normal_encoding big2_encoding = {
-  { VTABLE, 2, 0,
+static const struct normal_encoding big2_encoding
+    = {{VTABLE, 2, 0,
 #if BYTEORDER == 4321
-  1
+        1
 #else
-  0
+        0
 #endif
-  },
-  {
+       },
+       {
 #define BT_COLON BT_NMSTRT
 #include "asciitab.h"
 #undef BT_COLON
 #include "latin1tab.h"
-  },
-  STANDARD_VTABLE(big2_) NULL_VTABLE
-};
+       },
+       STANDARD_VTABLE(big2_) NULL_VTABLE};
 
 #if BYTEORDER != 1234
 
-#ifdef XML_NS
+#  ifdef XML_NS
 
-static const struct normal_encoding internal_big2_encoding_ns = {
-  { VTABLE, 2, 0, 1 },
-  {
-#include "iasciitab.h"
-#include "latin1tab.h"
-  },
-  STANDARD_VTABLE(big2_) NULL_VTABLE
-};
+static const struct normal_encoding internal_big2_encoding_ns
+    = {{VTABLE, 2, 0, 1},
+       {
+#    include "iasciitab.h"
+#    include "latin1tab.h"
+       },
+       STANDARD_VTABLE(big2_) NULL_VTABLE};
 
-#endif
+#  endif
 
-static const struct normal_encoding internal_big2_encoding = {
-  { VTABLE, 2, 0, 1 },
-  {
-#define BT_COLON BT_NMSTRT
-#include "iasciitab.h"
-#undef BT_COLON
-#include "latin1tab.h"
-  },
-  STANDARD_VTABLE(big2_) NULL_VTABLE
-};
+static const struct normal_encoding internal_big2_encoding
+    = {{VTABLE, 2, 0, 1},
+       {
+#  define BT_COLON BT_NMSTRT
+#  include "iasciitab.h"
+#  undef BT_COLON
+#  include "latin1tab.h"
+       },
+       STANDARD_VTABLE(big2_) NULL_VTABLE};
 
 #endif
 
 #undef PREFIX
 
 static int FASTCALL
-streqci(const char *s1, const char *s2)
-{
+streqci(const char *s1, const char *s2) {
   for (;;) {
     char c1 = *s1++;
     char c2 = *s2++;
@@ -1079,22 +1018,21 @@
       c2 += ASCII_A - ASCII_a; /* LCOV_EXCL_LINE */
     if (c1 != c2)
       return 0;
-    if (!c1)
+    if (! c1)
       break;
   }
   return 1;
 }
 
 static void PTRCALL
-initUpdatePosition(const ENCODING *UNUSED_P(enc), const char *ptr,
-                   const char *end, POSITION *pos)
-{
+initUpdatePosition(const ENCODING *enc, const char *ptr, const char *end,
+                   POSITION *pos) {
+  UNUSED_P(enc);
   normal_updatePosition(&utf8_encoding.enc, ptr, end, pos);
 }
 
 static int
-toAscii(const ENCODING *enc, const char *ptr, const char *end)
-{
+toAscii(const ENCODING *enc, const char *ptr, const char *end) {
   char buf[1];
   char *p = buf;
   XmlUtf8Convert(enc, &ptr, end, &p, p + 1);
@@ -1105,8 +1043,7 @@
 }
 
 static int FASTCALL
-isSpace(int c)
-{
+isSpace(int c) {
   switch (c) {
   case 0x20:
   case 0xD:
@@ -1121,21 +1058,16 @@
    followed by name=val.
 */
 static int
-parsePseudoAttribute(const ENCODING *enc,
-                     const char *ptr,
-                     const char *end,
-                     const char **namePtr,
-                     const char **nameEndPtr,
-                     const char **valPtr,
-                     const char **nextTokPtr)
-{
+parsePseudoAttribute(const ENCODING *enc, const char *ptr, const char *end,
+                     const char **namePtr, const char **nameEndPtr,
+                     const char **valPtr, const char **nextTokPtr) {
   int c;
   char open;
   if (ptr == end) {
     *namePtr = NULL;
     return 1;
   }
-  if (!isSpace(toAscii(enc, ptr, end))) {
+  if (! isSpace(toAscii(enc, ptr, end))) {
     *nextTokPtr = ptr;
     return 0;
   }
@@ -1191,12 +1123,9 @@
     c = toAscii(enc, ptr, end);
     if (c == open)
       break;
-    if (!(ASCII_a <= c && c <= ASCII_z)
-        && !(ASCII_A <= c && c <= ASCII_Z)
-        && !(ASCII_0 <= c && c <= ASCII_9)
-        && c != ASCII_PERIOD
-        && c != ASCII_MINUS
-        && c != ASCII_UNDERSCORE) {
+    if (! (ASCII_a <= c && c <= ASCII_z) && ! (ASCII_A <= c && c <= ASCII_Z)
+        && ! (ASCII_0 <= c && c <= ASCII_9) && c != ASCII_PERIOD
+        && c != ASCII_MINUS && c != ASCII_UNDERSCORE) {
       *nextTokPtr = ptr;
       return 0;
     }
@@ -1205,68 +1134,52 @@
   return 1;
 }
 
-static const char KW_version[] = {
-  ASCII_v, ASCII_e, ASCII_r, ASCII_s, ASCII_i, ASCII_o, ASCII_n, '\0'
-};
+static const char KW_version[]
+    = {ASCII_v, ASCII_e, ASCII_r, ASCII_s, ASCII_i, ASCII_o, ASCII_n, '\0'};
 
-static const char KW_encoding[] = {
-  ASCII_e, ASCII_n, ASCII_c, ASCII_o, ASCII_d, ASCII_i, ASCII_n, ASCII_g, '\0'
-};
+static const char KW_encoding[] = {ASCII_e, ASCII_n, ASCII_c, ASCII_o, ASCII_d,
+                                   ASCII_i, ASCII_n, ASCII_g, '\0'};
 
-static const char KW_standalone[] = {
-  ASCII_s, ASCII_t, ASCII_a, ASCII_n, ASCII_d, ASCII_a, ASCII_l, ASCII_o,
-  ASCII_n, ASCII_e, '\0'
-};
+static const char KW_standalone[]
+    = {ASCII_s, ASCII_t, ASCII_a, ASCII_n, ASCII_d, ASCII_a,
+       ASCII_l, ASCII_o, ASCII_n, ASCII_e, '\0'};
 
-static const char KW_yes[] = {
-  ASCII_y, ASCII_e, ASCII_s,  '\0'
-};
+static const char KW_yes[] = {ASCII_y, ASCII_e, ASCII_s, '\0'};
 
-static const char KW_no[] = {
-  ASCII_n, ASCII_o,  '\0'
-};
+static const char KW_no[] = {ASCII_n, ASCII_o, '\0'};
 
 static int
-doParseXmlDecl(const ENCODING *(*encodingFinder)(const ENCODING *,
-                                                 const char *,
+doParseXmlDecl(const ENCODING *(*encodingFinder)(const ENCODING *, const char *,
                                                  const char *),
-               int isGeneralTextEntity,
-               const ENCODING *enc,
-               const char *ptr,
-               const char *end,
-               const char **badPtr,
-               const char **versionPtr,
-               const char **versionEndPtr,
-               const char **encodingName,
-               const ENCODING **encoding,
-               int *standalone)
-{
+               int isGeneralTextEntity, const ENCODING *enc, const char *ptr,
+               const char *end, const char **badPtr, const char **versionPtr,
+               const char **versionEndPtr, const char **encodingName,
+               const ENCODING **encoding, int *standalone) {
   const char *val = NULL;
   const char *name = NULL;
   const char *nameEnd = NULL;
   ptr += 5 * enc->minBytesPerChar;
   end -= 2 * enc->minBytesPerChar;
-  if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)
-      || !name) {
+  if (! parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)
+      || ! name) {
     *badPtr = ptr;
     return 0;
   }
-  if (!XmlNameMatchesAscii(enc, name, nameEnd, KW_version)) {
-    if (!isGeneralTextEntity) {
+  if (! XmlNameMatchesAscii(enc, name, nameEnd, KW_version)) {
+    if (! isGeneralTextEntity) {
       *badPtr = name;
       return 0;
     }
-  }
-  else {
+  } else {
     if (versionPtr)
       *versionPtr = val;
     if (versionEndPtr)
       *versionEndPtr = ptr;
-    if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) {
+    if (! parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) {
       *badPtr = ptr;
       return 0;
     }
-    if (!name) {
+    if (! name) {
       if (isGeneralTextEntity) {
         /* a TextDecl must have an EncodingDecl */
         *badPtr = ptr;
@@ -1277,7 +1190,7 @@
   }
   if (XmlNameMatchesAscii(enc, name, nameEnd, KW_encoding)) {
     int c = toAscii(enc, val, end);
-    if (!(ASCII_a <= c && c <= ASCII_z) && !(ASCII_A <= c && c <= ASCII_Z)) {
+    if (! (ASCII_a <= c && c <= ASCII_z) && ! (ASCII_A <= c && c <= ASCII_Z)) {
       *badPtr = val;
       return 0;
     }
@@ -1285,14 +1198,14 @@
       *encodingName = val;
     if (encoding)
       *encoding = encodingFinder(enc, val, ptr - enc->minBytesPerChar);
-    if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) {
+    if (! parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) {
       *badPtr = ptr;
       return 0;
     }
-    if (!name)
+    if (! name)
       return 1;
   }
-  if (!XmlNameMatchesAscii(enc, name, nameEnd, KW_standalone)
+  if (! XmlNameMatchesAscii(enc, name, nameEnd, KW_standalone)
       || isGeneralTextEntity) {
     *badPtr = name;
     return 0;
@@ -1300,12 +1213,10 @@
   if (XmlNameMatchesAscii(enc, val, ptr - enc->minBytesPerChar, KW_yes)) {
     if (standalone)
       *standalone = 1;
-  }
-  else if (XmlNameMatchesAscii(enc, val, ptr - enc->minBytesPerChar, KW_no)) {
+  } else if (XmlNameMatchesAscii(enc, val, ptr - enc->minBytesPerChar, KW_no)) {
     if (standalone)
       *standalone = 0;
-  }
-  else {
+  } else {
     *badPtr = val;
     return 0;
   }
@@ -1319,11 +1230,16 @@
 }
 
 static int FASTCALL
-checkCharRefNumber(int result)
-{
+checkCharRefNumber(int result) {
   switch (result >> 8) {
-  case 0xD8: case 0xD9: case 0xDA: case 0xDB:
-  case 0xDC: case 0xDD: case 0xDE: case 0xDF:
+  case 0xD8:
+  case 0xD9:
+  case 0xDA:
+  case 0xDB:
+  case 0xDC:
+  case 0xDD:
+  case 0xDE:
+  case 0xDF:
     return -1;
   case 0:
     if (latin1_encoding.type[result] == BT_NONXML)
@@ -1338,8 +1254,7 @@
 }
 
 int FASTCALL
-XmlUtf8Encode(int c, char *buf)
-{
+XmlUtf8Encode(int c, char *buf) {
   enum {
     /* minN is minimum legal resulting value for N byte sequence */
     min2 = 0x80,
@@ -1375,8 +1290,7 @@
 }
 
 int FASTCALL
-XmlUtf16Encode(int charNum, unsigned short *buf)
-{
+XmlUtf16Encode(int charNum, unsigned short *buf) {
   if (charNum < 0)
     return 0;
   if (charNum < 0x10000) {
@@ -1400,17 +1314,15 @@
   char utf8[256][4];
 };
 
-#define AS_UNKNOWN_ENCODING(enc)  ((const struct unknown_encoding *) (enc))
+#define AS_UNKNOWN_ENCODING(enc) ((const struct unknown_encoding *)(enc))
 
 int
-XmlSizeOfUnknownEncoding(void)
-{
+XmlSizeOfUnknownEncoding(void) {
   return sizeof(struct unknown_encoding);
 }
 
 static int PTRFASTCALL
-unknown_isName(const ENCODING *enc, const char *p)
-{
+unknown_isName(const ENCODING *enc, const char *p) {
   const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc);
   int c = uenc->convert(uenc->userData, p);
   if (c & ~0xFFFF)
@@ -1419,8 +1331,7 @@
 }
 
 static int PTRFASTCALL
-unknown_isNmstrt(const ENCODING *enc, const char *p)
-{
+unknown_isNmstrt(const ENCODING *enc, const char *p) {
   const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc);
   int c = uenc->convert(uenc->userData, p);
   if (c & ~0xFFFF)
@@ -1429,18 +1340,15 @@
 }
 
 static int PTRFASTCALL
-unknown_isInvalid(const ENCODING *enc, const char *p)
-{
+unknown_isInvalid(const ENCODING *enc, const char *p) {
   const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc);
   int c = uenc->convert(uenc->userData, p);
   return (c & ~0xFFFF) || checkCharRefNumber(c) < 0;
 }
 
 static enum XML_Convert_Result PTRCALL
-unknown_toUtf8(const ENCODING *enc,
-               const char **fromP, const char *fromLim,
-               char **toP, const char *toLim)
-{
+unknown_toUtf8(const ENCODING *enc, const char **fromP, const char *fromLim,
+               char **toP, const char *toLim) {
   const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc);
   char buf[XML_UTF8_ENCODE_MAX];
   for (;;) {
@@ -1458,8 +1366,7 @@
       utf8 = buf;
       *fromP += (AS_NORMAL_ENCODING(enc)->type[(unsigned char)**fromP]
                  - (BT_LEAD2 - 2));
-    }
-    else {
+    } else {
       if (n > toLim - *toP)
         return XML_CONVERT_OUTPUT_EXHAUSTED;
       (*fromP)++;
@@ -1470,20 +1377,16 @@
 }
 
 static enum XML_Convert_Result PTRCALL
-unknown_toUtf16(const ENCODING *enc,
-                const char **fromP, const char *fromLim,
-                unsigned short **toP, const unsigned short *toLim)
-{
+unknown_toUtf16(const ENCODING *enc, const char **fromP, const char *fromLim,
+                unsigned short **toP, const unsigned short *toLim) {
   const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc);
   while (*fromP < fromLim && *toP < toLim) {
     unsigned short c = uenc->utf16[(unsigned char)**fromP];
     if (c == 0) {
-      c = (unsigned short)
-          uenc->convert(uenc->userData, *fromP);
+      c = (unsigned short)uenc->convert(uenc->userData, *fromP);
       *fromP += (AS_NORMAL_ENCODING(enc)->type[(unsigned char)**fromP]
                  - (BT_LEAD2 - 2));
-    }
-    else
+    } else
       (*fromP)++;
     *(*toP)++ = c;
   }
@@ -1495,19 +1398,14 @@
 }
 
 ENCODING *
-XmlInitUnknownEncoding(void *mem,
-                       int *table,
-                       CONVERTER convert,
-                       void *userData)
-{
+XmlInitUnknownEncoding(void *mem, int *table, CONVERTER convert,
+                       void *userData) {
   int i;
   struct unknown_encoding *e = (struct unknown_encoding *)mem;
-  for (i = 0; i < (int)sizeof(struct normal_encoding); i++)
-    ((char *)mem)[i] = ((char *)&latin1_encoding)[i];
+  memcpy(mem, &latin1_encoding, sizeof(struct normal_encoding));
   for (i = 0; i < 128; i++)
     if (latin1_encoding.type[i] != BT_OTHER
-        && latin1_encoding.type[i] != BT_NONXML
-        && table[i] != i)
+        && latin1_encoding.type[i] != BT_NONXML && table[i] != i)
       return 0;
   for (i = 0; i < 256; i++) {
     int c = table[i];
@@ -1517,35 +1415,30 @@
       e->utf16[i] = 0xFFFF;
       e->utf8[i][0] = 1;
       e->utf8[i][1] = 0;
-    }
-    else if (c < 0) {
+    } else if (c < 0) {
       if (c < -4)
         return 0;
       /* Multi-byte sequences need a converter function */
-      if (!convert)
+      if (! convert)
         return 0;
       e->normal.type[i] = (unsigned char)(BT_LEAD2 - (c + 2));
       e->utf8[i][0] = 0;
       e->utf16[i] = 0;
-    }
-    else if (c < 0x80) {
+    } else if (c < 0x80) {
       if (latin1_encoding.type[c] != BT_OTHER
-          && latin1_encoding.type[c] != BT_NONXML
-          && c != i)
+          && latin1_encoding.type[c] != BT_NONXML && c != i)
         return 0;
       e->normal.type[i] = latin1_encoding.type[c];
       e->utf8[i][0] = 1;
       e->utf8[i][1] = (char)c;
       e->utf16[i] = (unsigned short)(c == 0 ? 0xFFFF : c);
-    }
-    else if (checkCharRefNumber(c) < 0) {
+    } else if (checkCharRefNumber(c) < 0) {
       e->normal.type[i] = BT_NONXML;
       /* This shouldn't really get used. */
       e->utf16[i] = 0xFFFF;
       e->utf8[i][0] = 1;
       e->utf8[i][1] = 0;
-    }
-    else {
+    } else {
       if (c > 0xFFFF)
         return 0;
       if (UCS2_GET_NAMING(nmstrtPages, c >> 8, c & 0xff))
@@ -1590,44 +1483,32 @@
   NO_ENC
 };
 
-static const char KW_ISO_8859_1[] = {
-  ASCII_I, ASCII_S, ASCII_O, ASCII_MINUS, ASCII_8, ASCII_8, ASCII_5, ASCII_9,
-  ASCII_MINUS, ASCII_1, '\0'
-};
-static const char KW_US_ASCII[] = {
-  ASCII_U, ASCII_S, ASCII_MINUS, ASCII_A, ASCII_S, ASCII_C, ASCII_I, ASCII_I,
-  '\0'
-};
-static const char KW_UTF_8[] =  {
-  ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_8, '\0'
-};
-static const char KW_UTF_16[] = {
-  ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, '\0'
-};
-static const char KW_UTF_16BE[] = {
-  ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, ASCII_B, ASCII_E,
-  '\0'
-};
-static const char KW_UTF_16LE[] = {
-  ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, ASCII_L, ASCII_E,
-  '\0'
-};
+static const char KW_ISO_8859_1[]
+    = {ASCII_I, ASCII_S, ASCII_O,     ASCII_MINUS, ASCII_8, ASCII_8,
+       ASCII_5, ASCII_9, ASCII_MINUS, ASCII_1,     '\0'};
+static const char KW_US_ASCII[]
+    = {ASCII_U, ASCII_S, ASCII_MINUS, ASCII_A, ASCII_S,
+       ASCII_C, ASCII_I, ASCII_I,     '\0'};
+static const char KW_UTF_8[]
+    = {ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_8, '\0'};
+static const char KW_UTF_16[]
+    = {ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, '\0'};
+static const char KW_UTF_16BE[]
+    = {ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1,
+       ASCII_6, ASCII_B, ASCII_E, '\0'};
+static const char KW_UTF_16LE[]
+    = {ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1,
+       ASCII_6, ASCII_L, ASCII_E, '\0'};
 
 static int FASTCALL
-getEncodingIndex(const char *name)
-{
-  static const char * const encodingNames[] = {
-    KW_ISO_8859_1,
-    KW_US_ASCII,
-    KW_UTF_8,
-    KW_UTF_16,
-    KW_UTF_16BE,
-    KW_UTF_16LE,
+getEncodingIndex(const char *name) {
+  static const char *const encodingNames[] = {
+      KW_ISO_8859_1, KW_US_ASCII, KW_UTF_8, KW_UTF_16, KW_UTF_16BE, KW_UTF_16LE,
   };
   int i;
   if (name == NULL)
     return NO_ENC;
-  for (i = 0; i < (int)(sizeof(encodingNames)/sizeof(encodingNames[0])); i++)
+  for (i = 0; i < (int)(sizeof(encodingNames) / sizeof(encodingNames[0])); i++)
     if (streqci(name, encodingNames[i]))
       return i;
   return UNKNOWN_ENC;
@@ -1647,15 +1528,9 @@
    XML_PROLOG_STATE otherwise.
 */
 
-
 static int
-initScan(const ENCODING * const *encodingTable,
-         const INIT_ENCODING *enc,
-         int state,
-         const char *ptr,
-         const char *end,
-         const char **nextTokPtr)
-{
+initScan(const ENCODING *const *encodingTable, const INIT_ENCODING *enc,
+         int state, const char *ptr, const char *end, const char **nextTokPtr) {
   const ENCODING **encPtr;
 
   if (ptr >= end)
@@ -1680,20 +1555,17 @@
     case 0xFE:
     case 0xFF:
     case 0xEF: /* possibly first byte of UTF-8 BOM */
-      if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC
-          && state == XML_CONTENT_STATE)
+      if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC && state == XML_CONTENT_STATE)
         break;
       /* fall through */
     case 0x00:
     case 0x3C:
       return XML_TOK_PARTIAL;
     }
-  }
-  else {
+  } else {
     switch (((unsigned char)ptr[0] << 8) | (unsigned char)ptr[1]) {
     case 0xFEFF:
-      if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC
-          && state == XML_CONTENT_STATE)
+      if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC && state == XML_CONTENT_STATE)
         break;
       *nextTokPtr = ptr + 2;
       *encPtr = encodingTable[UTF_16BE_ENC];
@@ -1707,8 +1579,7 @@
       *encPtr = encodingTable[UTF_16LE_ENC];
       return XmlTok(*encPtr, state, ptr, end, nextTokPtr);
     case 0xFFFE:
-      if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC
-          && state == XML_CONTENT_STATE)
+      if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC && state == XML_CONTENT_STATE)
         break;
       *nextTokPtr = ptr + 2;
       *encPtr = encodingTable[UTF_16LE_ENC];
@@ -1723,8 +1594,8 @@
       */
       if (state == XML_CONTENT_STATE) {
         int e = INIT_ENC_INDEX(enc);
-        if (e == ISO_8859_1_ENC || e == UTF_16BE_ENC
-            || e == UTF_16LE_ENC || e == UTF_16_ENC)
+        if (e == ISO_8859_1_ENC || e == UTF_16BE_ENC || e == UTF_16LE_ENC
+            || e == UTF_16_ENC)
           break;
       }
       if (ptr + 2 == end)
@@ -1747,8 +1618,7 @@
           break;
         *encPtr = encodingTable[UTF_16BE_ENC];
         return XmlTok(*encPtr, state, ptr, end, nextTokPtr);
-      }
-      else if (ptr[1] == '\0') {
+      } else if (ptr[1] == '\0') {
         /* We could recover here in the case:
             - parsing an external entity
             - second byte is 0
@@ -1770,7 +1640,6 @@
   return XmlTok(*encPtr, state, ptr, end, nextTokPtr);
 }
 
-
 #define NS(x) x
 #define ns(x) x
 #define XML_TOK_NS_C
@@ -1781,22 +1650,19 @@
 
 #ifdef XML_NS
 
-#define NS(x) x ## NS
-#define ns(x) x ## _ns
+#  define NS(x) x##NS
+#  define ns(x) x##_ns
 
-#define XML_TOK_NS_C
-#include "xmltok_ns.c"
-#undef XML_TOK_NS_C
+#  define XML_TOK_NS_C
+#  include "xmltok_ns.c"
+#  undef XML_TOK_NS_C
 
-#undef NS
-#undef ns
+#  undef NS
+#  undef ns
 
 ENCODING *
-XmlInitUnknownEncodingNS(void *mem,
-                         int *table,
-                         CONVERTER convert,
-                         void *userData)
-{
+XmlInitUnknownEncodingNS(void *mem, int *table, CONVERTER convert,
+                         void *userData) {
   ENCODING *enc = XmlInitUnknownEncoding(mem, table, convert, userData);
   if (enc)
     ((struct normal_encoding *)enc)->type[ASCII_COLON] = BT_COLON;
diff --git a/third_party/expat/files/lib/xmltok.h b/third_party/expat/files/lib/xmltok.h
index 50926f3..2adbf530 100644
--- a/third_party/expat/files/lib/xmltok.h
+++ b/third_party/expat/files/lib/xmltok.h
@@ -38,16 +38,18 @@
 #endif
 
 /* The following token may be returned by XmlContentTok */
-#define XML_TOK_TRAILING_RSQB -5 /* ] or ]] at the end of the scan; might be
-                                    start of illegal ]]> sequence */
+#define XML_TOK_TRAILING_RSQB                                                  \
+  -5 /* ] or ]] at the end of the scan; might be                               \
+        start of illegal ]]> sequence */
 /* The following tokens may be returned by both XmlPrologTok and
    XmlContentTok.
 */
-#define XML_TOK_NONE -4          /* The string to be scanned is empty */
-#define XML_TOK_TRAILING_CR -3   /* A CR at the end of the scan;
-                                    might be part of CRLF sequence */
-#define XML_TOK_PARTIAL_CHAR -2  /* only part of a multibyte sequence */
-#define XML_TOK_PARTIAL -1       /* only part of a token */
+#define XML_TOK_NONE -4 /* The string to be scanned is empty */
+#define XML_TOK_TRAILING_CR                                                    \
+  -3                            /* A CR at the end of the scan;                \
+                                   might be part of CRLF sequence */
+#define XML_TOK_PARTIAL_CHAR -2 /* only part of a multibyte sequence */
+#define XML_TOK_PARTIAL -1      /* only part of a token */
 #define XML_TOK_INVALID 0
 
 /* The following tokens are returned by XmlContentTok; some are also
@@ -62,24 +64,24 @@
 #define XML_TOK_DATA_NEWLINE 7
 #define XML_TOK_CDATA_SECT_OPEN 8
 #define XML_TOK_ENTITY_REF 9
-#define XML_TOK_CHAR_REF 10               /* numeric character reference */
+#define XML_TOK_CHAR_REF 10 /* numeric character reference */
 
 /* The following tokens may be returned by both XmlPrologTok and
    XmlContentTok.
 */
-#define XML_TOK_PI 11                     /* processing instruction */
-#define XML_TOK_XML_DECL 12               /* XML decl or text decl */
+#define XML_TOK_PI 11       /* processing instruction */
+#define XML_TOK_XML_DECL 12 /* XML decl or text decl */
 #define XML_TOK_COMMENT 13
-#define XML_TOK_BOM 14                    /* Byte order mark */
+#define XML_TOK_BOM 14 /* Byte order mark */
 
 /* The following tokens are returned only by XmlPrologTok */
 #define XML_TOK_PROLOG_S 15
-#define XML_TOK_DECL_OPEN 16              /* <!foo */
-#define XML_TOK_DECL_CLOSE 17             /* > */
+#define XML_TOK_DECL_OPEN 16  /* <!foo */
+#define XML_TOK_DECL_CLOSE 17 /* > */
 #define XML_TOK_NAME 18
 #define XML_TOK_NMTOKEN 19
-#define XML_TOK_POUND_NAME 20             /* #name */
-#define XML_TOK_OR 21                     /* | */
+#define XML_TOK_POUND_NAME 20 /* #name */
+#define XML_TOK_OR 21         /* | */
 #define XML_TOK_PERCENT 22
 #define XML_TOK_OPEN_PAREN 23
 #define XML_TOK_CLOSE_PAREN 24
@@ -90,14 +92,14 @@
 #define XML_TOK_INSTANCE_START 29
 
 /* The following occur only in element type declarations */
-#define XML_TOK_NAME_QUESTION 30          /* name? */
-#define XML_TOK_NAME_ASTERISK 31          /* name* */
-#define XML_TOK_NAME_PLUS 32              /* name+ */
-#define XML_TOK_COND_SECT_OPEN 33         /* <![ */
-#define XML_TOK_COND_SECT_CLOSE 34        /* ]]> */
-#define XML_TOK_CLOSE_PAREN_QUESTION 35   /* )? */
-#define XML_TOK_CLOSE_PAREN_ASTERISK 36   /* )* */
-#define XML_TOK_CLOSE_PAREN_PLUS 37       /* )+ */
+#define XML_TOK_NAME_QUESTION 30        /* name? */
+#define XML_TOK_NAME_ASTERISK 31        /* name* */
+#define XML_TOK_NAME_PLUS 32            /* name+ */
+#define XML_TOK_COND_SECT_OPEN 33       /* <![ */
+#define XML_TOK_COND_SECT_CLOSE 34      /* ]]> */
+#define XML_TOK_CLOSE_PAREN_QUESTION 35 /* )? */
+#define XML_TOK_CLOSE_PAREN_ASTERISK 36 /* )* */
+#define XML_TOK_CLOSE_PAREN_PLUS 37     /* )+ */
 #define XML_TOK_COMMA 38
 
 /* The following token is returned only by XmlAttributeValueTok */
@@ -112,20 +114,20 @@
 #define XML_TOK_PREFIXED_NAME 41
 
 #ifdef XML_DTD
-#define XML_TOK_IGNORE_SECT 42
+#  define XML_TOK_IGNORE_SECT 42
 #endif /* XML_DTD */
 
 #ifdef XML_DTD
-#define XML_N_STATES 4
+#  define XML_N_STATES 4
 #else /* not XML_DTD */
-#define XML_N_STATES 3
+#  define XML_N_STATES 3
 #endif /* not XML_DTD */
 
 #define XML_PROLOG_STATE 0
 #define XML_CONTENT_STATE 1
 #define XML_CDATA_SECTION_STATE 2
 #ifdef XML_DTD
-#define XML_IGNORE_SECTION_STATE 3
+#  define XML_IGNORE_SECTION_STATE 3
 #endif /* XML_DTD */
 
 #define XML_N_LITERAL_TYPES 2
@@ -153,52 +155,41 @@
 struct encoding;
 typedef struct encoding ENCODING;
 
-typedef int (PTRCALL *SCANNER)(const ENCODING *,
-                               const char *,
-                               const char *,
-                               const char **);
+typedef int(PTRCALL *SCANNER)(const ENCODING *, const char *, const char *,
+                              const char **);
 
 enum XML_Convert_Result {
   XML_CONVERT_COMPLETED = 0,
   XML_CONVERT_INPUT_INCOMPLETE = 1,
-  XML_CONVERT_OUTPUT_EXHAUSTED = 2  /* and therefore potentially input remaining as well */
+  XML_CONVERT_OUTPUT_EXHAUSTED
+  = 2 /* and therefore potentially input remaining as well */
 };
 
 struct encoding {
   SCANNER scanners[XML_N_STATES];
   SCANNER literalScanners[XML_N_LITERAL_TYPES];
-  int (PTRCALL *nameMatchesAscii)(const ENCODING *,
-                                  const char *,
-                                  const char *,
-                                  const char *);
-  int (PTRFASTCALL *nameLength)(const ENCODING *, const char *);
+  int(PTRCALL *nameMatchesAscii)(const ENCODING *, const char *, const char *,
+                                 const char *);
+  int(PTRFASTCALL *nameLength)(const ENCODING *, const char *);
   const char *(PTRFASTCALL *skipS)(const ENCODING *, const char *);
-  int (PTRCALL *getAtts)(const ENCODING *enc,
-                         const char *ptr,
-                         int attsMax,
-                         ATTRIBUTE *atts);
-  int (PTRFASTCALL *charRefNumber)(const ENCODING *enc, const char *ptr);
-  int (PTRCALL *predefinedEntityName)(const ENCODING *,
-                                      const char *,
-                                      const char *);
-  void (PTRCALL *updatePosition)(const ENCODING *,
-                                 const char *ptr,
-                                 const char *end,
-                                 POSITION *);
-  int (PTRCALL *isPublicId)(const ENCODING *enc,
-                            const char *ptr,
-                            const char *end,
-                            const char **badPtr);
-  enum XML_Convert_Result (PTRCALL *utf8Convert)(const ENCODING *enc,
-                              const char **fromP,
-                              const char *fromLim,
-                              char **toP,
-                              const char *toLim);
-  enum XML_Convert_Result (PTRCALL *utf16Convert)(const ENCODING *enc,
-                               const char **fromP,
-                               const char *fromLim,
-                               unsigned short **toP,
-                               const unsigned short *toLim);
+  int(PTRCALL *getAtts)(const ENCODING *enc, const char *ptr, int attsMax,
+                        ATTRIBUTE *atts);
+  int(PTRFASTCALL *charRefNumber)(const ENCODING *enc, const char *ptr);
+  int(PTRCALL *predefinedEntityName)(const ENCODING *, const char *,
+                                     const char *);
+  void(PTRCALL *updatePosition)(const ENCODING *, const char *ptr,
+                                const char *end, POSITION *);
+  int(PTRCALL *isPublicId)(const ENCODING *enc, const char *ptr,
+                           const char *end, const char **badPtr);
+  enum XML_Convert_Result(PTRCALL *utf8Convert)(const ENCODING *enc,
+                                                const char **fromP,
+                                                const char *fromLim, char **toP,
+                                                const char *toLim);
+  enum XML_Convert_Result(PTRCALL *utf16Convert)(const ENCODING *enc,
+                                                 const char **fromP,
+                                                 const char *fromLim,
+                                                 unsigned short **toP,
+                                                 const unsigned short *toLim);
   int minBytesPerChar;
   char isUtf8;
   char isUtf16;
@@ -225,66 +216,62 @@
    the prolog outside literals, comments and processing instructions.
 */
 
-
-#define XmlTok(enc, state, ptr, end, nextTokPtr) \
+#define XmlTok(enc, state, ptr, end, nextTokPtr)                               \
   (((enc)->scanners[state])(enc, ptr, end, nextTokPtr))
 
-#define XmlPrologTok(enc, ptr, end, nextTokPtr) \
-   XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr)
+#define XmlPrologTok(enc, ptr, end, nextTokPtr)                                \
+  XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr)
 
-#define XmlContentTok(enc, ptr, end, nextTokPtr) \
-   XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr)
+#define XmlContentTok(enc, ptr, end, nextTokPtr)                               \
+  XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr)
 
-#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr) \
-   XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr)
+#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr)                          \
+  XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr)
 
 #ifdef XML_DTD
 
-#define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr) \
-   XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr)
+#  define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr)                       \
+    XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr)
 
 #endif /* XML_DTD */
 
 /* This is used for performing a 2nd-level tokenization on the content
    of a literal that has already been returned by XmlTok.
 */
-#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr) \
+#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr)                  \
   (((enc)->literalScanners[literalType])(enc, ptr, end, nextTokPtr))
 
-#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr) \
-   XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr)
+#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr)                        \
+  XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr)
 
-#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \
-   XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr)
+#define XmlEntityValueTok(enc, ptr, end, nextTokPtr)                           \
+  XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr)
 
-#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \
+#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2)                             \
   (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2))
 
-#define XmlNameLength(enc, ptr) \
-  (((enc)->nameLength)(enc, ptr))
+#define XmlNameLength(enc, ptr) (((enc)->nameLength)(enc, ptr))
 
-#define XmlSkipS(enc, ptr) \
-  (((enc)->skipS)(enc, ptr))
+#define XmlSkipS(enc, ptr) (((enc)->skipS)(enc, ptr))
 
-#define XmlGetAttributes(enc, ptr, attsMax, atts) \
+#define XmlGetAttributes(enc, ptr, attsMax, atts)                              \
   (((enc)->getAtts)(enc, ptr, attsMax, atts))
 
-#define XmlCharRefNumber(enc, ptr) \
-  (((enc)->charRefNumber)(enc, ptr))
+#define XmlCharRefNumber(enc, ptr) (((enc)->charRefNumber)(enc, ptr))
 
-#define XmlPredefinedEntityName(enc, ptr, end) \
+#define XmlPredefinedEntityName(enc, ptr, end)                                 \
   (((enc)->predefinedEntityName)(enc, ptr, end))
 
-#define XmlUpdatePosition(enc, ptr, end, pos) \
+#define XmlUpdatePosition(enc, ptr, end, pos)                                  \
   (((enc)->updatePosition)(enc, ptr, end, pos))
 
-#define XmlIsPublicId(enc, ptr, end, badPtr) \
+#define XmlIsPublicId(enc, ptr, end, badPtr)                                   \
   (((enc)->isPublicId)(enc, ptr, end, badPtr))
 
-#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim) \
+#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim)                        \
   (((enc)->utf8Convert)(enc, fromP, fromLim, toP, toLim))
 
-#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim) \
+#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim)                       \
   (((enc)->utf16Convert)(enc, fromP, fromLim, toP, toLim))
 
 typedef struct {
@@ -292,16 +279,11 @@
   const ENCODING **encPtr;
 } INIT_ENCODING;
 
-int XmlParseXmlDecl(int isGeneralTextEntity,
-                    const ENCODING *enc,
-                    const char *ptr,
-                    const char *end,
-                    const char **badPtr,
-                    const char **versionPtr,
-                    const char **versionEndPtr,
+int XmlParseXmlDecl(int isGeneralTextEntity, const ENCODING *enc,
+                    const char *ptr, const char *end, const char **badPtr,
+                    const char **versionPtr, const char **versionEndPtr,
                     const char **encodingNamePtr,
-                    const ENCODING **namedEncodingPtr,
-                    int *standalonePtr);
+                    const ENCODING **namedEncodingPtr, int *standalonePtr);
 
 int XmlInitEncoding(INIT_ENCODING *, const ENCODING **, const char *name);
 const ENCODING *XmlGetUtf8InternalEncoding(void);
@@ -310,34 +292,22 @@
 int FASTCALL XmlUtf16Encode(int charNumber, unsigned short *buf);
 int XmlSizeOfUnknownEncoding(void);
 
+typedef int(XMLCALL *CONVERTER)(void *userData, const char *p);
 
-typedef int (XMLCALL *CONVERTER) (void *userData, const char *p);
+ENCODING *XmlInitUnknownEncoding(void *mem, int *table, CONVERTER convert,
+                                 void *userData);
 
-ENCODING *
-XmlInitUnknownEncoding(void *mem,
-                       int *table,
-                       CONVERTER convert,
-                       void *userData);
-
-int XmlParseXmlDeclNS(int isGeneralTextEntity,
-                      const ENCODING *enc,
-                      const char *ptr,
-                      const char *end,
-                      const char **badPtr,
-                      const char **versionPtr,
-                      const char **versionEndPtr,
+int XmlParseXmlDeclNS(int isGeneralTextEntity, const ENCODING *enc,
+                      const char *ptr, const char *end, const char **badPtr,
+                      const char **versionPtr, const char **versionEndPtr,
                       const char **encodingNamePtr,
-                      const ENCODING **namedEncodingPtr,
-                      int *standalonePtr);
+                      const ENCODING **namedEncodingPtr, int *standalonePtr);
 
 int XmlInitEncodingNS(INIT_ENCODING *, const ENCODING **, const char *name);
 const ENCODING *XmlGetUtf8InternalEncodingNS(void);
 const ENCODING *XmlGetUtf16InternalEncodingNS(void);
-ENCODING *
-XmlInitUnknownEncodingNS(void *mem,
-                         int *table,
-                         CONVERTER convert,
-                         void *userData);
+ENCODING *XmlInitUnknownEncodingNS(void *mem, int *table, CONVERTER convert,
+                                   void *userData);
 #ifdef __cplusplus
 }
 #endif
diff --git a/third_party/expat/files/lib/xmltok_impl.c b/third_party/expat/files/lib/xmltok_impl.c
index 4d9ae7d..c209221 100644
--- a/third_party/expat/files/lib/xmltok_impl.c
+++ b/third_party/expat/files/lib/xmltok_impl.c
@@ -32,130 +32,124 @@
 
 #ifdef XML_TOK_IMPL_C
 
-#ifndef IS_INVALID_CHAR
-#define IS_INVALID_CHAR(enc, ptr, n) (0)
-#endif
+#  ifndef IS_INVALID_CHAR
+#    define IS_INVALID_CHAR(enc, ptr, n) (0)
+#  endif
 
-#define INVALID_LEAD_CASE(n, ptr, nextTokPtr) \
-    case BT_LEAD ## n: \
-      if (end - ptr < n) \
-        return XML_TOK_PARTIAL_CHAR; \
-      if (IS_INVALID_CHAR(enc, ptr, n)) { \
-        *(nextTokPtr) = (ptr); \
-        return XML_TOK_INVALID; \
-      } \
-      ptr += n; \
-      break;
+#  define INVALID_LEAD_CASE(n, ptr, nextTokPtr)                                \
+  case BT_LEAD##n:                                                             \
+    if (end - ptr < n)                                                         \
+      return XML_TOK_PARTIAL_CHAR;                                             \
+    if (IS_INVALID_CHAR(enc, ptr, n)) {                                        \
+      *(nextTokPtr) = (ptr);                                                   \
+      return XML_TOK_INVALID;                                                  \
+    }                                                                          \
+    ptr += n;                                                                  \
+    break;
 
-#define INVALID_CASES(ptr, nextTokPtr) \
-  INVALID_LEAD_CASE(2, ptr, nextTokPtr) \
-  INVALID_LEAD_CASE(3, ptr, nextTokPtr) \
-  INVALID_LEAD_CASE(4, ptr, nextTokPtr) \
-  case BT_NONXML: \
-  case BT_MALFORM: \
-  case BT_TRAIL: \
-    *(nextTokPtr) = (ptr); \
+#  define INVALID_CASES(ptr, nextTokPtr)                                       \
+    INVALID_LEAD_CASE(2, ptr, nextTokPtr)                                      \
+    INVALID_LEAD_CASE(3, ptr, nextTokPtr)                                      \
+    INVALID_LEAD_CASE(4, ptr, nextTokPtr)                                      \
+  case BT_NONXML:                                                              \
+  case BT_MALFORM:                                                             \
+  case BT_TRAIL:                                                               \
+    *(nextTokPtr) = (ptr);                                                     \
     return XML_TOK_INVALID;
 
-#define CHECK_NAME_CASE(n, enc, ptr, end, nextTokPtr) \
-   case BT_LEAD ## n: \
-     if (end - ptr < n) \
-       return XML_TOK_PARTIAL_CHAR; \
-     if (!IS_NAME_CHAR(enc, ptr, n)) { \
-       *nextTokPtr = ptr; \
-       return XML_TOK_INVALID; \
-     } \
-     ptr += n; \
-     break;
+#  define CHECK_NAME_CASE(n, enc, ptr, end, nextTokPtr)                        \
+  case BT_LEAD##n:                                                             \
+    if (end - ptr < n)                                                         \
+      return XML_TOK_PARTIAL_CHAR;                                             \
+    if (! IS_NAME_CHAR(enc, ptr, n)) {                                         \
+      *nextTokPtr = ptr;                                                       \
+      return XML_TOK_INVALID;                                                  \
+    }                                                                          \
+    ptr += n;                                                                  \
+    break;
 
-#define CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) \
-  case BT_NONASCII: \
-    if (!IS_NAME_CHAR_MINBPC(enc, ptr)) { \
-      *nextTokPtr = ptr; \
-      return XML_TOK_INVALID; \
-    } \
-    /* fall through */ \
-  case BT_NMSTRT: \
-  case BT_HEX: \
-  case BT_DIGIT: \
-  case BT_NAME: \
-  case BT_MINUS: \
-    ptr += MINBPC(enc); \
-    break; \
-  CHECK_NAME_CASE(2, enc, ptr, end, nextTokPtr) \
-  CHECK_NAME_CASE(3, enc, ptr, end, nextTokPtr) \
-  CHECK_NAME_CASE(4, enc, ptr, end, nextTokPtr)
+#  define CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)                          \
+  case BT_NONASCII:                                                            \
+    if (! IS_NAME_CHAR_MINBPC(enc, ptr)) {                                     \
+      *nextTokPtr = ptr;                                                       \
+      return XML_TOK_INVALID;                                                  \
+    }                                                                          \
+    /* fall through */                                                         \
+  case BT_NMSTRT:                                                              \
+  case BT_HEX:                                                                 \
+  case BT_DIGIT:                                                               \
+  case BT_NAME:                                                                \
+  case BT_MINUS:                                                               \
+    ptr += MINBPC(enc);                                                        \
+    break;                                                                     \
+    CHECK_NAME_CASE(2, enc, ptr, end, nextTokPtr)                              \
+    CHECK_NAME_CASE(3, enc, ptr, end, nextTokPtr)                              \
+    CHECK_NAME_CASE(4, enc, ptr, end, nextTokPtr)
 
-#define CHECK_NMSTRT_CASE(n, enc, ptr, end, nextTokPtr) \
-   case BT_LEAD ## n: \
-     if (end - ptr < n) \
-       return XML_TOK_PARTIAL_CHAR; \
-     if (!IS_NMSTRT_CHAR(enc, ptr, n)) { \
-       *nextTokPtr = ptr; \
-       return XML_TOK_INVALID; \
-     } \
-     ptr += n; \
-     break;
+#  define CHECK_NMSTRT_CASE(n, enc, ptr, end, nextTokPtr)                      \
+  case BT_LEAD##n:                                                             \
+    if (end - ptr < n)                                                         \
+      return XML_TOK_PARTIAL_CHAR;                                             \
+    if (! IS_NMSTRT_CHAR(enc, ptr, n)) {                                       \
+      *nextTokPtr = ptr;                                                       \
+      return XML_TOK_INVALID;                                                  \
+    }                                                                          \
+    ptr += n;                                                                  \
+    break;
 
-#define CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) \
-  case BT_NONASCII: \
-    if (!IS_NMSTRT_CHAR_MINBPC(enc, ptr)) { \
-      *nextTokPtr = ptr; \
-      return XML_TOK_INVALID; \
-    } \
-    /* fall through */ \
-  case BT_NMSTRT: \
-  case BT_HEX: \
-    ptr += MINBPC(enc); \
-    break; \
-  CHECK_NMSTRT_CASE(2, enc, ptr, end, nextTokPtr) \
-  CHECK_NMSTRT_CASE(3, enc, ptr, end, nextTokPtr) \
-  CHECK_NMSTRT_CASE(4, enc, ptr, end, nextTokPtr)
+#  define CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)                        \
+  case BT_NONASCII:                                                            \
+    if (! IS_NMSTRT_CHAR_MINBPC(enc, ptr)) {                                   \
+      *nextTokPtr = ptr;                                                       \
+      return XML_TOK_INVALID;                                                  \
+    }                                                                          \
+    /* fall through */                                                         \
+  case BT_NMSTRT:                                                              \
+  case BT_HEX:                                                                 \
+    ptr += MINBPC(enc);                                                        \
+    break;                                                                     \
+    CHECK_NMSTRT_CASE(2, enc, ptr, end, nextTokPtr)                            \
+    CHECK_NMSTRT_CASE(3, enc, ptr, end, nextTokPtr)                            \
+    CHECK_NMSTRT_CASE(4, enc, ptr, end, nextTokPtr)
 
-#ifndef PREFIX
-#define PREFIX(ident) ident
-#endif
+#  ifndef PREFIX
+#    define PREFIX(ident) ident
+#  endif
 
+#  define HAS_CHARS(enc, ptr, end, count) (end - ptr >= count * MINBPC(enc))
 
-#define HAS_CHARS(enc, ptr, end, count) \
-    (end - ptr >= count * MINBPC(enc))
+#  define HAS_CHAR(enc, ptr, end) HAS_CHARS(enc, ptr, end, 1)
 
-#define HAS_CHAR(enc, ptr, end) \
-    HAS_CHARS(enc, ptr, end, 1)
-
-#define REQUIRE_CHARS(enc, ptr, end, count) \
-    { \
-      if (! HAS_CHARS(enc, ptr, end, count)) { \
-        return XML_TOK_PARTIAL; \
-      } \
+#  define REQUIRE_CHARS(enc, ptr, end, count)                                  \
+    {                                                                          \
+      if (! HAS_CHARS(enc, ptr, end, count)) {                                 \
+        return XML_TOK_PARTIAL;                                                \
+      }                                                                        \
     }
 
-#define REQUIRE_CHAR(enc, ptr, end) \
-    REQUIRE_CHARS(enc, ptr, end, 1)
-
+#  define REQUIRE_CHAR(enc, ptr, end) REQUIRE_CHARS(enc, ptr, end, 1)
 
 /* ptr points to character following "<!-" */
 
 static int PTRCALL
-PREFIX(scanComment)(const ENCODING *enc, const char *ptr,
-                    const char *end, const char **nextTokPtr)
-{
+PREFIX(scanComment)(const ENCODING *enc, const char *ptr, const char *end,
+                    const char **nextTokPtr) {
   if (HAS_CHAR(enc, ptr, end)) {
-    if (!CHAR_MATCHES(enc, ptr, ASCII_MINUS)) {
+    if (! CHAR_MATCHES(enc, ptr, ASCII_MINUS)) {
       *nextTokPtr = ptr;
       return XML_TOK_INVALID;
     }
     ptr += MINBPC(enc);
     while (HAS_CHAR(enc, ptr, end)) {
       switch (BYTE_TYPE(enc, ptr)) {
-      INVALID_CASES(ptr, nextTokPtr)
+        INVALID_CASES(ptr, nextTokPtr)
       case BT_MINUS:
         ptr += MINBPC(enc);
         REQUIRE_CHAR(enc, ptr, end);
         if (CHAR_MATCHES(enc, ptr, ASCII_MINUS)) {
           ptr += MINBPC(enc);
           REQUIRE_CHAR(enc, ptr, end);
-          if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) {
+          if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) {
             *nextTokPtr = ptr;
             return XML_TOK_INVALID;
           }
@@ -175,9 +169,8 @@
 /* ptr points to character following "<!" */
 
 static int PTRCALL
-PREFIX(scanDecl)(const ENCODING *enc, const char *ptr,
-                 const char *end, const char **nextTokPtr)
-{
+PREFIX(scanDecl)(const ENCODING *enc, const char *ptr, const char *end,
+                 const char **nextTokPtr) {
   REQUIRE_CHAR(enc, ptr, end);
   switch (BYTE_TYPE(enc, ptr)) {
   case BT_MINUS:
@@ -199,12 +192,17 @@
       REQUIRE_CHARS(enc, ptr, end, 2);
       /* don't allow <!ENTITY% foo "whatever"> */
       switch (BYTE_TYPE(enc, ptr + MINBPC(enc))) {
-      case BT_S: case BT_CR: case BT_LF: case BT_PERCNT:
+      case BT_S:
+      case BT_CR:
+      case BT_LF:
+      case BT_PERCNT:
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
       /* fall through */
-    case BT_S: case BT_CR: case BT_LF:
+    case BT_S:
+    case BT_CR:
+    case BT_LF:
       *nextTokPtr = ptr;
       return XML_TOK_DECL_OPEN;
     case BT_NMSTRT:
@@ -220,12 +218,12 @@
 }
 
 static int PTRCALL
-PREFIX(checkPiTarget)(const ENCODING *UNUSED_P(enc), const char *ptr,
-                      const char *end, int *tokPtr)
-{
+PREFIX(checkPiTarget)(const ENCODING *enc, const char *ptr, const char *end,
+                      int *tokPtr) {
   int upper = 0;
+  UNUSED_P(enc);
   *tokPtr = XML_TOK_PI;
-  if (end - ptr != MINBPC(enc)*3)
+  if (end - ptr != MINBPC(enc) * 3)
     return 1;
   switch (BYTE_TO_ASCII(enc, ptr)) {
   case ASCII_x:
@@ -265,30 +263,31 @@
 /* ptr points to character following "<?" */
 
 static int PTRCALL
-PREFIX(scanPi)(const ENCODING *enc, const char *ptr,
-               const char *end, const char **nextTokPtr)
-{
+PREFIX(scanPi)(const ENCODING *enc, const char *ptr, const char *end,
+               const char **nextTokPtr) {
   int tok;
   const char *target = ptr;
   REQUIRE_CHAR(enc, ptr, end);
   switch (BYTE_TYPE(enc, ptr)) {
-  CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+    CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
   default:
     *nextTokPtr = ptr;
     return XML_TOK_INVALID;
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-    case BT_S: case BT_CR: case BT_LF:
-      if (!PREFIX(checkPiTarget)(enc, target, ptr, &tok)) {
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+    case BT_S:
+    case BT_CR:
+    case BT_LF:
+      if (! PREFIX(checkPiTarget)(enc, target, ptr, &tok)) {
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
       ptr += MINBPC(enc);
       while (HAS_CHAR(enc, ptr, end)) {
         switch (BYTE_TYPE(enc, ptr)) {
-        INVALID_CASES(ptr, nextTokPtr)
+          INVALID_CASES(ptr, nextTokPtr)
         case BT_QUEST:
           ptr += MINBPC(enc);
           REQUIRE_CHAR(enc, ptr, end);
@@ -304,7 +303,7 @@
       }
       return XML_TOK_PARTIAL;
     case BT_QUEST:
-      if (!PREFIX(checkPiTarget)(enc, target, ptr, &tok)) {
+      if (! PREFIX(checkPiTarget)(enc, target, ptr, &tok)) {
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
@@ -324,16 +323,16 @@
 }
 
 static int PTRCALL
-PREFIX(scanCdataSection)(const ENCODING *UNUSED_P(enc), const char *ptr,
-                         const char *end, const char **nextTokPtr)
-{
-  static const char CDATA_LSQB[] = { ASCII_C, ASCII_D, ASCII_A,
-                                     ASCII_T, ASCII_A, ASCII_LSQB };
+PREFIX(scanCdataSection)(const ENCODING *enc, const char *ptr, const char *end,
+                         const char **nextTokPtr) {
+  static const char CDATA_LSQB[]
+      = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, ASCII_LSQB};
   int i;
+  UNUSED_P(enc);
   /* CDATA[ */
   REQUIRE_CHARS(enc, ptr, end, 6);
   for (i = 0; i < 6; i++, ptr += MINBPC(enc)) {
-    if (!CHAR_MATCHES(enc, ptr, CDATA_LSQB[i])) {
+    if (! CHAR_MATCHES(enc, ptr, CDATA_LSQB[i])) {
       *nextTokPtr = ptr;
       return XML_TOK_INVALID;
     }
@@ -343,9 +342,8 @@
 }
 
 static int PTRCALL
-PREFIX(cdataSectionTok)(const ENCODING *enc, const char *ptr,
-                        const char *end, const char **nextTokPtr)
-{
+PREFIX(cdataSectionTok)(const ENCODING *enc, const char *ptr, const char *end,
+                        const char **nextTokPtr) {
   if (ptr >= end)
     return XML_TOK_NONE;
   if (MINBPC(enc) > 1) {
@@ -361,11 +359,11 @@
   case BT_RSQB:
     ptr += MINBPC(enc);
     REQUIRE_CHAR(enc, ptr, end);
-    if (!CHAR_MATCHES(enc, ptr, ASCII_RSQB))
+    if (! CHAR_MATCHES(enc, ptr, ASCII_RSQB))
       break;
     ptr += MINBPC(enc);
     REQUIRE_CHAR(enc, ptr, end);
-    if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) {
+    if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) {
       ptr -= MINBPC(enc);
       break;
     }
@@ -381,23 +379,25 @@
   case BT_LF:
     *nextTokPtr = ptr + MINBPC(enc);
     return XML_TOK_DATA_NEWLINE;
-  INVALID_CASES(ptr, nextTokPtr)
+    INVALID_CASES(ptr, nextTokPtr)
   default:
     ptr += MINBPC(enc);
     break;
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-#define LEAD_CASE(n) \
-    case BT_LEAD ## n: \
-      if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \
-        *nextTokPtr = ptr; \
-        return XML_TOK_DATA_CHARS; \
-      } \
-      ptr += n; \
-      break;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) {                       \
+      *nextTokPtr = ptr;                                                       \
+      return XML_TOK_DATA_CHARS;                                               \
+    }                                                                          \
+    ptr += n;                                                                  \
+    break;
+      LEAD_CASE(2)
+      LEAD_CASE(3)
+      LEAD_CASE(4)
+#  undef LEAD_CASE
     case BT_NONXML:
     case BT_MALFORM:
     case BT_TRAIL:
@@ -418,23 +418,26 @@
 /* ptr points to character following "</" */
 
 static int PTRCALL
-PREFIX(scanEndTag)(const ENCODING *enc, const char *ptr,
-                   const char *end, const char **nextTokPtr)
-{
+PREFIX(scanEndTag)(const ENCODING *enc, const char *ptr, const char *end,
+                   const char **nextTokPtr) {
   REQUIRE_CHAR(enc, ptr, end);
   switch (BYTE_TYPE(enc, ptr)) {
-  CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+    CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
   default:
     *nextTokPtr = ptr;
     return XML_TOK_INVALID;
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-    case BT_S: case BT_CR: case BT_LF:
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+    case BT_S:
+    case BT_CR:
+    case BT_LF:
       for (ptr += MINBPC(enc); HAS_CHAR(enc, ptr, end); ptr += MINBPC(enc)) {
         switch (BYTE_TYPE(enc, ptr)) {
-        case BT_S: case BT_CR: case BT_LF:
+        case BT_S:
+        case BT_CR:
+        case BT_LF:
           break;
         case BT_GT:
           *nextTokPtr = ptr + MINBPC(enc);
@@ -445,13 +448,13 @@
         }
       }
       return XML_TOK_PARTIAL;
-#ifdef XML_NS
+#  ifdef XML_NS
     case BT_COLON:
       /* no need to check qname syntax here,
          since end-tag must match exactly */
       ptr += MINBPC(enc);
       break;
-#endif
+#  endif
     case BT_GT:
       *nextTokPtr = ptr + MINBPC(enc);
       return XML_TOK_END_TAG;
@@ -466,9 +469,8 @@
 /* ptr points to character following "&#X" */
 
 static int PTRCALL
-PREFIX(scanHexCharRef)(const ENCODING *enc, const char *ptr,
-                       const char *end, const char **nextTokPtr)
-{
+PREFIX(scanHexCharRef)(const ENCODING *enc, const char *ptr, const char *end,
+                       const char **nextTokPtr) {
   if (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
     case BT_DIGIT:
@@ -498,9 +500,8 @@
 /* ptr points to character following "&#" */
 
 static int PTRCALL
-PREFIX(scanCharRef)(const ENCODING *enc, const char *ptr,
-                    const char *end, const char **nextTokPtr)
-{
+PREFIX(scanCharRef)(const ENCODING *enc, const char *ptr, const char *end,
+                    const char **nextTokPtr) {
   if (HAS_CHAR(enc, ptr, end)) {
     if (CHAR_MATCHES(enc, ptr, ASCII_x))
       return PREFIX(scanHexCharRef)(enc, ptr + MINBPC(enc), end, nextTokPtr);
@@ -531,11 +532,10 @@
 
 static int PTRCALL
 PREFIX(scanRef)(const ENCODING *enc, const char *ptr, const char *end,
-                const char **nextTokPtr)
-{
+                const char **nextTokPtr) {
   REQUIRE_CHAR(enc, ptr, end);
   switch (BYTE_TYPE(enc, ptr)) {
-  CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+    CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
   case BT_NUM:
     return PREFIX(scanCharRef)(enc, ptr + MINBPC(enc), end, nextTokPtr);
   default:
@@ -544,7 +544,7 @@
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
     case BT_SEMI:
       *nextTokPtr = ptr + MINBPC(enc);
       return XML_TOK_ENTITY_REF;
@@ -560,15 +560,14 @@
 
 static int PTRCALL
 PREFIX(scanAtts)(const ENCODING *enc, const char *ptr, const char *end,
-                 const char **nextTokPtr)
-{
-#ifdef XML_NS
+                 const char **nextTokPtr) {
+#  ifdef XML_NS
   int hadColon = 0;
-#endif
+#  endif
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-#ifdef XML_NS
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+#  ifdef XML_NS
     case BT_COLON:
       if (hadColon) {
         *nextTokPtr = ptr;
@@ -578,14 +577,16 @@
       ptr += MINBPC(enc);
       REQUIRE_CHAR(enc, ptr, end);
       switch (BYTE_TYPE(enc, ptr)) {
-      CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+        CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
       default:
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
       break;
-#endif
-    case BT_S: case BT_CR: case BT_LF:
+#  endif
+    case BT_S:
+    case BT_CR:
+    case BT_LF:
       for (;;) {
         int t;
 
@@ -605,101 +606,101 @@
         }
       }
       /* fall through */
-    case BT_EQUALS:
-      {
-        int open;
-#ifdef XML_NS
-        hadColon = 0;
-#endif
-        for (;;) {
-          ptr += MINBPC(enc);
-          REQUIRE_CHAR(enc, ptr, end);
-          open = BYTE_TYPE(enc, ptr);
-          if (open == BT_QUOT || open == BT_APOS)
-            break;
-          switch (open) {
-          case BT_S:
-          case BT_LF:
-          case BT_CR:
-            break;
-          default:
-            *nextTokPtr = ptr;
-            return XML_TOK_INVALID;
-          }
-        }
-        ptr += MINBPC(enc);
-        /* in attribute value */
-        for (;;) {
-          int t;
-          REQUIRE_CHAR(enc, ptr, end);
-          t = BYTE_TYPE(enc, ptr);
-          if (t == open)
-            break;
-          switch (t) {
-          INVALID_CASES(ptr, nextTokPtr)
-          case BT_AMP:
-            {
-              int tok = PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, &ptr);
-              if (tok <= 0) {
-                if (tok == XML_TOK_INVALID)
-                  *nextTokPtr = ptr;
-                return tok;
-              }
-              break;
-            }
-          case BT_LT:
-            *nextTokPtr = ptr;
-            return XML_TOK_INVALID;
-          default:
-            ptr += MINBPC(enc);
-            break;
-          }
-        }
+    case BT_EQUALS: {
+      int open;
+#  ifdef XML_NS
+      hadColon = 0;
+#  endif
+      for (;;) {
         ptr += MINBPC(enc);
         REQUIRE_CHAR(enc, ptr, end);
-        switch (BYTE_TYPE(enc, ptr)) {
-        case BT_S:
-        case BT_CR:
-        case BT_LF:
+        open = BYTE_TYPE(enc, ptr);
+        if (open == BT_QUOT || open == BT_APOS)
           break;
-        case BT_SOL:
-          goto sol;
-        case BT_GT:
-          goto gt;
+        switch (open) {
+        case BT_S:
+        case BT_LF:
+        case BT_CR:
+          break;
         default:
           *nextTokPtr = ptr;
           return XML_TOK_INVALID;
         }
-        /* ptr points to closing quote */
-        for (;;) {
-          ptr += MINBPC(enc);
-          REQUIRE_CHAR(enc, ptr, end);
-          switch (BYTE_TYPE(enc, ptr)) {
-          CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
-          case BT_S: case BT_CR: case BT_LF:
-            continue;
-          case BT_GT:
-          gt:
-            *nextTokPtr = ptr + MINBPC(enc);
-            return XML_TOK_START_TAG_WITH_ATTS;
-          case BT_SOL:
-          sol:
-            ptr += MINBPC(enc);
-            REQUIRE_CHAR(enc, ptr, end);
-            if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) {
+      }
+      ptr += MINBPC(enc);
+      /* in attribute value */
+      for (;;) {
+        int t;
+        REQUIRE_CHAR(enc, ptr, end);
+        t = BYTE_TYPE(enc, ptr);
+        if (t == open)
+          break;
+        switch (t) {
+          INVALID_CASES(ptr, nextTokPtr)
+        case BT_AMP: {
+          int tok = PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, &ptr);
+          if (tok <= 0) {
+            if (tok == XML_TOK_INVALID)
               *nextTokPtr = ptr;
-              return XML_TOK_INVALID;
-            }
-            *nextTokPtr = ptr + MINBPC(enc);
-            return XML_TOK_EMPTY_ELEMENT_WITH_ATTS;
-          default:
-            *nextTokPtr = ptr;
-            return XML_TOK_INVALID;
+            return tok;
           }
           break;
         }
+        case BT_LT:
+          *nextTokPtr = ptr;
+          return XML_TOK_INVALID;
+        default:
+          ptr += MINBPC(enc);
+          break;
+        }
+      }
+      ptr += MINBPC(enc);
+      REQUIRE_CHAR(enc, ptr, end);
+      switch (BYTE_TYPE(enc, ptr)) {
+      case BT_S:
+      case BT_CR:
+      case BT_LF:
+        break;
+      case BT_SOL:
+        goto sol;
+      case BT_GT:
+        goto gt;
+      default:
+        *nextTokPtr = ptr;
+        return XML_TOK_INVALID;
+      }
+      /* ptr points to closing quote */
+      for (;;) {
+        ptr += MINBPC(enc);
+        REQUIRE_CHAR(enc, ptr, end);
+        switch (BYTE_TYPE(enc, ptr)) {
+          CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+        case BT_S:
+        case BT_CR:
+        case BT_LF:
+          continue;
+        case BT_GT:
+        gt:
+          *nextTokPtr = ptr + MINBPC(enc);
+          return XML_TOK_START_TAG_WITH_ATTS;
+        case BT_SOL:
+        sol:
+          ptr += MINBPC(enc);
+          REQUIRE_CHAR(enc, ptr, end);
+          if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) {
+            *nextTokPtr = ptr;
+            return XML_TOK_INVALID;
+          }
+          *nextTokPtr = ptr + MINBPC(enc);
+          return XML_TOK_EMPTY_ELEMENT_WITH_ATTS;
+        default:
+          *nextTokPtr = ptr;
+          return XML_TOK_INVALID;
+        }
         break;
       }
+      break;
+    }
     default:
       *nextTokPtr = ptr;
       return XML_TOK_INVALID;
@@ -712,14 +713,13 @@
 
 static int PTRCALL
 PREFIX(scanLt)(const ENCODING *enc, const char *ptr, const char *end,
-               const char **nextTokPtr)
-{
-#ifdef XML_NS
+               const char **nextTokPtr) {
+#  ifdef XML_NS
   int hadColon;
-#endif
+#  endif
   REQUIRE_CHAR(enc, ptr, end);
   switch (BYTE_TYPE(enc, ptr)) {
-  CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+    CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
   case BT_EXCL:
     ptr += MINBPC(enc);
     REQUIRE_CHAR(enc, ptr, end);
@@ -727,8 +727,7 @@
     case BT_MINUS:
       return PREFIX(scanComment)(enc, ptr + MINBPC(enc), end, nextTokPtr);
     case BT_LSQB:
-      return PREFIX(scanCdataSection)(enc, ptr + MINBPC(enc),
-                                      end, nextTokPtr);
+      return PREFIX(scanCdataSection)(enc, ptr + MINBPC(enc), end, nextTokPtr);
     }
     *nextTokPtr = ptr;
     return XML_TOK_INVALID;
@@ -740,14 +739,14 @@
     *nextTokPtr = ptr;
     return XML_TOK_INVALID;
   }
-#ifdef XML_NS
+#  ifdef XML_NS
   hadColon = 0;
-#endif
+#  endif
   /* we have a start-tag */
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-#ifdef XML_NS
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+#  ifdef XML_NS
     case BT_COLON:
       if (hadColon) {
         *nextTokPtr = ptr;
@@ -757,34 +756,37 @@
       ptr += MINBPC(enc);
       REQUIRE_CHAR(enc, ptr, end);
       switch (BYTE_TYPE(enc, ptr)) {
-      CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+        CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
       default:
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
       break;
-#endif
-    case BT_S: case BT_CR: case BT_LF:
-      {
-        ptr += MINBPC(enc);
-        while (HAS_CHAR(enc, ptr, end)) {
-          switch (BYTE_TYPE(enc, ptr)) {
+#  endif
+    case BT_S:
+    case BT_CR:
+    case BT_LF: {
+      ptr += MINBPC(enc);
+      while (HAS_CHAR(enc, ptr, end)) {
+        switch (BYTE_TYPE(enc, ptr)) {
           CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
-          case BT_GT:
-            goto gt;
-          case BT_SOL:
-            goto sol;
-          case BT_S: case BT_CR: case BT_LF:
-            ptr += MINBPC(enc);
-            continue;
-          default:
-            *nextTokPtr = ptr;
-            return XML_TOK_INVALID;
-          }
-          return PREFIX(scanAtts)(enc, ptr, end, nextTokPtr);
+        case BT_GT:
+          goto gt;
+        case BT_SOL:
+          goto sol;
+        case BT_S:
+        case BT_CR:
+        case BT_LF:
+          ptr += MINBPC(enc);
+          continue;
+        default:
+          *nextTokPtr = ptr;
+          return XML_TOK_INVALID;
         }
-        return XML_TOK_PARTIAL;
+        return PREFIX(scanAtts)(enc, ptr, end, nextTokPtr);
       }
+      return XML_TOK_PARTIAL;
+    }
     case BT_GT:
     gt:
       *nextTokPtr = ptr + MINBPC(enc);
@@ -793,7 +795,7 @@
     sol:
       ptr += MINBPC(enc);
       REQUIRE_CHAR(enc, ptr, end);
-      if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) {
+      if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) {
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
@@ -809,8 +811,7 @@
 
 static int PTRCALL
 PREFIX(contentTok)(const ENCODING *enc, const char *ptr, const char *end,
-                   const char **nextTokPtr)
-{
+                   const char **nextTokPtr) {
   if (ptr >= end)
     return XML_TOK_NONE;
   if (MINBPC(enc) > 1) {
@@ -842,48 +843,50 @@
     ptr += MINBPC(enc);
     if (! HAS_CHAR(enc, ptr, end))
       return XML_TOK_TRAILING_RSQB;
-    if (!CHAR_MATCHES(enc, ptr, ASCII_RSQB))
+    if (! CHAR_MATCHES(enc, ptr, ASCII_RSQB))
       break;
     ptr += MINBPC(enc);
     if (! HAS_CHAR(enc, ptr, end))
       return XML_TOK_TRAILING_RSQB;
-    if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) {
+    if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) {
       ptr -= MINBPC(enc);
       break;
     }
     *nextTokPtr = ptr;
     return XML_TOK_INVALID;
-  INVALID_CASES(ptr, nextTokPtr)
+    INVALID_CASES(ptr, nextTokPtr)
   default:
     ptr += MINBPC(enc);
     break;
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-#define LEAD_CASE(n) \
-    case BT_LEAD ## n: \
-      if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \
-        *nextTokPtr = ptr; \
-        return XML_TOK_DATA_CHARS; \
-      } \
-      ptr += n; \
-      break;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) {                       \
+      *nextTokPtr = ptr;                                                       \
+      return XML_TOK_DATA_CHARS;                                               \
+    }                                                                          \
+    ptr += n;                                                                  \
+    break;
+      LEAD_CASE(2)
+      LEAD_CASE(3)
+      LEAD_CASE(4)
+#  undef LEAD_CASE
     case BT_RSQB:
       if (HAS_CHARS(enc, ptr, end, 2)) {
-         if (!CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_RSQB)) {
-           ptr += MINBPC(enc);
-           break;
-         }
-         if (HAS_CHARS(enc, ptr, end, 3)) {
-           if (!CHAR_MATCHES(enc, ptr + 2*MINBPC(enc), ASCII_GT)) {
-             ptr += MINBPC(enc);
-             break;
-           }
-           *nextTokPtr = ptr + 2*MINBPC(enc);
-           return XML_TOK_INVALID;
-         }
+        if (! CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_RSQB)) {
+          ptr += MINBPC(enc);
+          break;
+        }
+        if (HAS_CHARS(enc, ptr, end, 3)) {
+          if (! CHAR_MATCHES(enc, ptr + 2 * MINBPC(enc), ASCII_GT)) {
+            ptr += MINBPC(enc);
+            break;
+          }
+          *nextTokPtr = ptr + 2 * MINBPC(enc);
+          return XML_TOK_INVALID;
+        }
       }
       /* fall through */
     case BT_AMP:
@@ -908,12 +911,14 @@
 
 static int PTRCALL
 PREFIX(scanPercent)(const ENCODING *enc, const char *ptr, const char *end,
-                    const char **nextTokPtr)
-{
+                    const char **nextTokPtr) {
   REQUIRE_CHAR(enc, ptr, end);
   switch (BYTE_TYPE(enc, ptr)) {
-  CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
-  case BT_S: case BT_LF: case BT_CR: case BT_PERCNT:
+    CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+  case BT_S:
+  case BT_LF:
+  case BT_CR:
+  case BT_PERCNT:
     *nextTokPtr = ptr;
     return XML_TOK_PERCENT;
   default:
@@ -922,7 +927,7 @@
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
     case BT_SEMI:
       *nextTokPtr = ptr + MINBPC(enc);
       return XML_TOK_PARAM_ENTITY_REF;
@@ -936,20 +941,24 @@
 
 static int PTRCALL
 PREFIX(scanPoundName)(const ENCODING *enc, const char *ptr, const char *end,
-                      const char **nextTokPtr)
-{
+                      const char **nextTokPtr) {
   REQUIRE_CHAR(enc, ptr, end);
   switch (BYTE_TYPE(enc, ptr)) {
-  CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
+    CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr)
   default:
     *nextTokPtr = ptr;
     return XML_TOK_INVALID;
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-    case BT_CR: case BT_LF: case BT_S:
-    case BT_RPAR: case BT_GT: case BT_PERCNT: case BT_VERBAR:
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+    case BT_CR:
+    case BT_LF:
+    case BT_S:
+    case BT_RPAR:
+    case BT_GT:
+    case BT_PERCNT:
+    case BT_VERBAR:
       *nextTokPtr = ptr;
       return XML_TOK_POUND_NAME;
     default:
@@ -961,14 +970,12 @@
 }
 
 static int PTRCALL
-PREFIX(scanLit)(int open, const ENCODING *enc,
-                const char *ptr, const char *end,
-                const char **nextTokPtr)
-{
+PREFIX(scanLit)(int open, const ENCODING *enc, const char *ptr, const char *end,
+                const char **nextTokPtr) {
   while (HAS_CHAR(enc, ptr, end)) {
     int t = BYTE_TYPE(enc, ptr);
     switch (t) {
-    INVALID_CASES(ptr, nextTokPtr)
+      INVALID_CASES(ptr, nextTokPtr)
     case BT_QUOT:
     case BT_APOS:
       ptr += MINBPC(enc);
@@ -978,8 +985,12 @@
         return -XML_TOK_LITERAL;
       *nextTokPtr = ptr;
       switch (BYTE_TYPE(enc, ptr)) {
-      case BT_S: case BT_CR: case BT_LF:
-      case BT_GT: case BT_PERCNT: case BT_LSQB:
+      case BT_S:
+      case BT_CR:
+      case BT_LF:
+      case BT_GT:
+      case BT_PERCNT:
+      case BT_LSQB:
         return XML_TOK_LITERAL;
       default:
         return XML_TOK_INVALID;
@@ -994,8 +1005,7 @@
 
 static int PTRCALL
 PREFIX(prologTok)(const ENCODING *enc, const char *ptr, const char *end,
-                  const char **nextTokPtr)
-{
+                  const char **nextTokPtr) {
   int tok;
   if (ptr >= end)
     return XML_TOK_NONE;
@@ -1013,27 +1023,26 @@
     return PREFIX(scanLit)(BT_QUOT, enc, ptr + MINBPC(enc), end, nextTokPtr);
   case BT_APOS:
     return PREFIX(scanLit)(BT_APOS, enc, ptr + MINBPC(enc), end, nextTokPtr);
-  case BT_LT:
-    {
-      ptr += MINBPC(enc);
-      REQUIRE_CHAR(enc, ptr, end);
-      switch (BYTE_TYPE(enc, ptr)) {
-      case BT_EXCL:
-        return PREFIX(scanDecl)(enc, ptr + MINBPC(enc), end, nextTokPtr);
-      case BT_QUEST:
-        return PREFIX(scanPi)(enc, ptr + MINBPC(enc), end, nextTokPtr);
-      case BT_NMSTRT:
-      case BT_HEX:
-      case BT_NONASCII:
-      case BT_LEAD2:
-      case BT_LEAD3:
-      case BT_LEAD4:
-        *nextTokPtr = ptr - MINBPC(enc);
-        return XML_TOK_INSTANCE_START;
-      }
-      *nextTokPtr = ptr;
-      return XML_TOK_INVALID;
+  case BT_LT: {
+    ptr += MINBPC(enc);
+    REQUIRE_CHAR(enc, ptr, end);
+    switch (BYTE_TYPE(enc, ptr)) {
+    case BT_EXCL:
+      return PREFIX(scanDecl)(enc, ptr + MINBPC(enc), end, nextTokPtr);
+    case BT_QUEST:
+      return PREFIX(scanPi)(enc, ptr + MINBPC(enc), end, nextTokPtr);
+    case BT_NMSTRT:
+    case BT_HEX:
+    case BT_NONASCII:
+    case BT_LEAD2:
+    case BT_LEAD3:
+    case BT_LEAD4:
+      *nextTokPtr = ptr - MINBPC(enc);
+      return XML_TOK_INSTANCE_START;
     }
+    *nextTokPtr = ptr;
+    return XML_TOK_INVALID;
+  }
   case BT_CR:
     if (ptr + MINBPC(enc) == end) {
       *nextTokPtr = end;
@@ -1041,13 +1050,15 @@
       return -XML_TOK_PROLOG_S;
     }
     /* fall through */
-  case BT_S: case BT_LF:
+  case BT_S:
+  case BT_LF:
     for (;;) {
       ptr += MINBPC(enc);
       if (! HAS_CHAR(enc, ptr, end))
         break;
       switch (BYTE_TYPE(enc, ptr)) {
-      case BT_S: case BT_LF:
+      case BT_S:
+      case BT_LF:
         break;
       case BT_CR:
         /* don't split CR/LF pair */
@@ -1076,7 +1087,7 @@
     if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) {
       REQUIRE_CHARS(enc, ptr, end, 2);
       if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_GT)) {
-        *nextTokPtr = ptr + 2*MINBPC(enc);
+        *nextTokPtr = ptr + 2 * MINBPC(enc);
         return XML_TOK_COND_SECT_CLOSE;
       }
     }
@@ -1099,8 +1110,12 @@
     case BT_PLUS:
       *nextTokPtr = ptr + MINBPC(enc);
       return XML_TOK_CLOSE_PAREN_PLUS;
-    case BT_CR: case BT_LF: case BT_S:
-    case BT_GT: case BT_COMMA: case BT_VERBAR:
+    case BT_CR:
+    case BT_LF:
+    case BT_S:
+    case BT_GT:
+    case BT_COMMA:
+    case BT_VERBAR:
     case BT_RPAR:
       *nextTokPtr = ptr;
       return XML_TOK_CLOSE_PAREN;
@@ -1115,24 +1130,26 @@
     return XML_TOK_DECL_CLOSE;
   case BT_NUM:
     return PREFIX(scanPoundName)(enc, ptr + MINBPC(enc), end, nextTokPtr);
-#define LEAD_CASE(n) \
-  case BT_LEAD ## n: \
-    if (end - ptr < n) \
-      return XML_TOK_PARTIAL_CHAR; \
-    if (IS_NMSTRT_CHAR(enc, ptr, n)) { \
-      ptr += n; \
-      tok = XML_TOK_NAME; \
-      break; \
-    } \
-    if (IS_NAME_CHAR(enc, ptr, n)) { \
-      ptr += n; \
-      tok = XML_TOK_NMTOKEN; \
-      break; \
-    } \
-    *nextTokPtr = ptr; \
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    if (end - ptr < n)                                                         \
+      return XML_TOK_PARTIAL_CHAR;                                             \
+    if (IS_NMSTRT_CHAR(enc, ptr, n)) {                                         \
+      ptr += n;                                                                \
+      tok = XML_TOK_NAME;                                                      \
+      break;                                                                   \
+    }                                                                          \
+    if (IS_NAME_CHAR(enc, ptr, n)) {                                           \
+      ptr += n;                                                                \
+      tok = XML_TOK_NMTOKEN;                                                   \
+      break;                                                                   \
+    }                                                                          \
+    *nextTokPtr = ptr;                                                         \
     return XML_TOK_INVALID;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+    LEAD_CASE(2)
+    LEAD_CASE(3)
+    LEAD_CASE(4)
+#  undef LEAD_CASE
   case BT_NMSTRT:
   case BT_HEX:
     tok = XML_TOK_NAME;
@@ -1141,9 +1158,9 @@
   case BT_DIGIT:
   case BT_NAME:
   case BT_MINUS:
-#ifdef XML_NS
+#  ifdef XML_NS
   case BT_COLON:
-#endif
+#  endif
     tok = XML_TOK_NMTOKEN;
     ptr += MINBPC(enc);
     break;
@@ -1165,13 +1182,19 @@
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
-    case BT_GT: case BT_RPAR: case BT_COMMA:
-    case BT_VERBAR: case BT_LSQB: case BT_PERCNT:
-    case BT_S: case BT_CR: case BT_LF:
+      CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+    case BT_GT:
+    case BT_RPAR:
+    case BT_COMMA:
+    case BT_VERBAR:
+    case BT_LSQB:
+    case BT_PERCNT:
+    case BT_S:
+    case BT_CR:
+    case BT_LF:
       *nextTokPtr = ptr;
       return tok;
-#ifdef XML_NS
+#  ifdef XML_NS
     case BT_COLON:
       ptr += MINBPC(enc);
       switch (tok) {
@@ -1179,7 +1202,7 @@
         REQUIRE_CHAR(enc, ptr, end);
         tok = XML_TOK_PREFIXED_NAME;
         switch (BYTE_TYPE(enc, ptr)) {
-        CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
+          CHECK_NAME_CASES(enc, ptr, end, nextTokPtr)
         default:
           tok = XML_TOK_NMTOKEN;
           break;
@@ -1190,23 +1213,23 @@
         break;
       }
       break;
-#endif
+#  endif
     case BT_PLUS:
-      if (tok == XML_TOK_NMTOKEN)  {
+      if (tok == XML_TOK_NMTOKEN) {
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
       *nextTokPtr = ptr + MINBPC(enc);
       return XML_TOK_NAME_PLUS;
     case BT_AST:
-      if (tok == XML_TOK_NMTOKEN)  {
+      if (tok == XML_TOK_NMTOKEN) {
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
       *nextTokPtr = ptr + MINBPC(enc);
       return XML_TOK_NAME_ASTERISK;
     case BT_QUEST:
-      if (tok == XML_TOK_NMTOKEN)  {
+      if (tok == XML_TOK_NMTOKEN) {
         *nextTokPtr = ptr;
         return XML_TOK_INVALID;
       }
@@ -1221,9 +1244,8 @@
 }
 
 static int PTRCALL
-PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr,
-                          const char *end, const char **nextTokPtr)
-{
+PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr, const char *end,
+                          const char **nextTokPtr) {
   const char *start;
   if (ptr >= end)
     return XML_TOK_NONE;
@@ -1238,10 +1260,14 @@
   start = ptr;
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-#define LEAD_CASE(n) \
-    case BT_LEAD ## n: ptr += n; break;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    ptr += n;                                                                  \
+    break;
+      LEAD_CASE(2)
+      LEAD_CASE(3)
+      LEAD_CASE(4)
+#  undef LEAD_CASE
     case BT_AMP:
       if (ptr == start)
         return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr);
@@ -1287,9 +1313,8 @@
 }
 
 static int PTRCALL
-PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr,
-                       const char *end, const char **nextTokPtr)
-{
+PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr, const char *end,
+                       const char **nextTokPtr) {
   const char *start;
   if (ptr >= end)
     return XML_TOK_NONE;
@@ -1304,10 +1329,14 @@
   start = ptr;
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-#define LEAD_CASE(n) \
-    case BT_LEAD ## n: ptr += n; break;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    ptr += n;                                                                  \
+    break;
+      LEAD_CASE(2)
+      LEAD_CASE(3)
+      LEAD_CASE(4)
+#  undef LEAD_CASE
     case BT_AMP:
       if (ptr == start)
         return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr);
@@ -1315,8 +1344,7 @@
       return XML_TOK_DATA_CHARS;
     case BT_PERCNT:
       if (ptr == start) {
-        int tok =  PREFIX(scanPercent)(enc, ptr + MINBPC(enc),
-                                       end, nextTokPtr);
+        int tok = PREFIX(scanPercent)(enc, ptr + MINBPC(enc), end, nextTokPtr);
         return (tok == XML_TOK_PERCENT) ? XML_TOK_INVALID : tok;
       }
       *nextTokPtr = ptr;
@@ -1349,12 +1377,11 @@
   return XML_TOK_DATA_CHARS;
 }
 
-#ifdef XML_DTD
+#  ifdef XML_DTD
 
 static int PTRCALL
-PREFIX(ignoreSectionTok)(const ENCODING *enc, const char *ptr,
-                         const char *end, const char **nextTokPtr)
-{
+PREFIX(ignoreSectionTok)(const ENCODING *enc, const char *ptr, const char *end,
+                         const char **nextTokPtr) {
   int level = 0;
   if (MINBPC(enc) > 1) {
     size_t n = end - ptr;
@@ -1365,7 +1392,7 @@
   }
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-    INVALID_CASES(ptr, nextTokPtr)
+      INVALID_CASES(ptr, nextTokPtr)
     case BT_LT:
       ptr += MINBPC(enc);
       REQUIRE_CHAR(enc, ptr, end);
@@ -1402,12 +1429,11 @@
   return XML_TOK_PARTIAL;
 }
 
-#endif /* XML_DTD */
+#  endif /* XML_DTD */
 
 static int PTRCALL
 PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end,
-                   const char **badPtr)
-{
+                   const char **badPtr) {
   ptr += MINBPC(enc);
   end -= MINBPC(enc);
   for (; HAS_CHAR(enc, ptr, end); ptr += MINBPC(enc)) {
@@ -1430,9 +1456,9 @@
     case BT_AST:
     case BT_PERCNT:
     case BT_NUM:
-#ifdef XML_NS
+#  ifdef XML_NS
     case BT_COLON:
-#endif
+#  endif
       break;
     case BT_S:
       if (CHAR_MATCHES(enc, ptr, ASCII_TAB)) {
@@ -1442,7 +1468,7 @@
       break;
     case BT_NAME:
     case BT_NMSTRT:
-      if (!(BYTE_TO_ASCII(enc, ptr) & ~0x7f))
+      if (! (BYTE_TO_ASCII(enc, ptr) & ~0x7f))
         break;
       /* fall through */
     default:
@@ -1466,9 +1492,8 @@
 */
 
 static int PTRCALL
-PREFIX(getAtts)(const ENCODING *enc, const char *ptr,
-                int attsMax, ATTRIBUTE *atts)
-{
+PREFIX(getAtts)(const ENCODING *enc, const char *ptr, int attsMax,
+                ATTRIBUTE *atts) {
   enum { other, inName, inValue } state = inName;
   int nAtts = 0;
   int open = 0; /* defined when state == inValue;
@@ -1476,32 +1501,35 @@
 
   for (ptr += MINBPC(enc);; ptr += MINBPC(enc)) {
     switch (BYTE_TYPE(enc, ptr)) {
-#define START_NAME \
-      if (state == other) { \
-        if (nAtts < attsMax) { \
-          atts[nAtts].name = ptr; \
-          atts[nAtts].normalized = 1; \
-        } \
-        state = inName; \
-      }
-#define LEAD_CASE(n) \
-    case BT_LEAD ## n: START_NAME ptr += (n - MINBPC(enc)); break;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+#  define START_NAME                                                           \
+    if (state == other) {                                                      \
+      if (nAtts < attsMax) {                                                   \
+        atts[nAtts].name = ptr;                                                \
+        atts[nAtts].normalized = 1;                                            \
+      }                                                                        \
+      state = inName;                                                          \
+    }
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    START_NAME ptr += (n - MINBPC(enc));                                       \
+    break;
+      LEAD_CASE(2)
+      LEAD_CASE(3)
+      LEAD_CASE(4)
+#  undef LEAD_CASE
     case BT_NONASCII:
     case BT_NMSTRT:
     case BT_HEX:
       START_NAME
       break;
-#undef START_NAME
+#  undef START_NAME
     case BT_QUOT:
       if (state != inValue) {
         if (nAtts < attsMax)
           atts[nAtts].valuePtr = ptr + MINBPC(enc);
         state = inValue;
         open = BT_QUOT;
-      }
-      else if (open == BT_QUOT) {
+      } else if (open == BT_QUOT) {
         state = other;
         if (nAtts < attsMax)
           atts[nAtts].valueEnd = ptr;
@@ -1514,8 +1542,7 @@
           atts[nAtts].valuePtr = ptr + MINBPC(enc);
         state = inValue;
         open = BT_APOS;
-      }
-      else if (open == BT_APOS) {
+      } else if (open == BT_APOS) {
         state = other;
         if (nAtts < attsMax)
           atts[nAtts].valueEnd = ptr;
@@ -1529,16 +1556,15 @@
     case BT_S:
       if (state == inName)
         state = other;
-      else if (state == inValue
-               && nAtts < attsMax
-               && atts[nAtts].normalized
+      else if (state == inValue && nAtts < attsMax && atts[nAtts].normalized
                && (ptr == atts[nAtts].valuePtr
                    || BYTE_TO_ASCII(enc, ptr) != ASCII_SPACE
                    || BYTE_TO_ASCII(enc, ptr + MINBPC(enc)) == ASCII_SPACE
                    || BYTE_TYPE(enc, ptr + MINBPC(enc)) == open))
         atts[nAtts].normalized = 0;
       break;
-    case BT_CR: case BT_LF:
+    case BT_CR:
+    case BT_LF:
       /* This case ensures that the first attribute name is counted
          Apart from that we could just change state on the quote. */
       if (state == inName)
@@ -1559,29 +1585,44 @@
 }
 
 static int PTRFASTCALL
-PREFIX(charRefNumber)(const ENCODING *UNUSED_P(enc), const char *ptr)
-{
+PREFIX(charRefNumber)(const ENCODING *enc, const char *ptr) {
   int result = 0;
   /* skip &# */
-  ptr += 2*MINBPC(enc);
+  UNUSED_P(enc);
+  ptr += 2 * MINBPC(enc);
   if (CHAR_MATCHES(enc, ptr, ASCII_x)) {
-    for (ptr += MINBPC(enc);
-         !CHAR_MATCHES(enc, ptr, ASCII_SEMI);
+    for (ptr += MINBPC(enc); ! CHAR_MATCHES(enc, ptr, ASCII_SEMI);
          ptr += MINBPC(enc)) {
       int c = BYTE_TO_ASCII(enc, ptr);
       switch (c) {
-      case ASCII_0: case ASCII_1: case ASCII_2: case ASCII_3: case ASCII_4:
-      case ASCII_5: case ASCII_6: case ASCII_7: case ASCII_8: case ASCII_9:
+      case ASCII_0:
+      case ASCII_1:
+      case ASCII_2:
+      case ASCII_3:
+      case ASCII_4:
+      case ASCII_5:
+      case ASCII_6:
+      case ASCII_7:
+      case ASCII_8:
+      case ASCII_9:
         result <<= 4;
         result |= (c - ASCII_0);
         break;
-      case ASCII_A: case ASCII_B: case ASCII_C:
-      case ASCII_D: case ASCII_E: case ASCII_F:
+      case ASCII_A:
+      case ASCII_B:
+      case ASCII_C:
+      case ASCII_D:
+      case ASCII_E:
+      case ASCII_F:
         result <<= 4;
         result += 10 + (c - ASCII_A);
         break;
-      case ASCII_a: case ASCII_b: case ASCII_c:
-      case ASCII_d: case ASCII_e: case ASCII_f:
+      case ASCII_a:
+      case ASCII_b:
+      case ASCII_c:
+      case ASCII_d:
+      case ASCII_e:
+      case ASCII_f:
         result <<= 4;
         result += 10 + (c - ASCII_a);
         break;
@@ -1589,9 +1630,8 @@
       if (result >= 0x110000)
         return -1;
     }
-  }
-  else {
-    for (; !CHAR_MATCHES(enc, ptr, ASCII_SEMI); ptr += MINBPC(enc)) {
+  } else {
+    for (; ! CHAR_MATCHES(enc, ptr, ASCII_SEMI); ptr += MINBPC(enc)) {
       int c = BYTE_TO_ASCII(enc, ptr);
       result *= 10;
       result += (c - ASCII_0);
@@ -1603,10 +1643,10 @@
 }
 
 static int PTRCALL
-PREFIX(predefinedEntityName)(const ENCODING *UNUSED_P(enc), const char *ptr,
-                             const char *end)
-{
-  switch ((end - ptr)/MINBPC(enc)) {
+PREFIX(predefinedEntityName)(const ENCODING *enc, const char *ptr,
+                             const char *end) {
+  UNUSED_P(enc);
+  switch ((end - ptr) / MINBPC(enc)) {
   case 2:
     if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_t)) {
       switch (BYTE_TO_ASCII(enc, ptr)) {
@@ -1657,9 +1697,9 @@
 }
 
 static int PTRCALL
-PREFIX(nameMatchesAscii)(const ENCODING *UNUSED_P(enc), const char *ptr1,
-                         const char *end1, const char *ptr2)
-{
+PREFIX(nameMatchesAscii)(const ENCODING *enc, const char *ptr1,
+                         const char *end1, const char *ptr2) {
+  UNUSED_P(enc);
   for (; *ptr2; ptr1 += MINBPC(enc), ptr2++) {
     if (end1 - ptr1 < MINBPC(enc)) {
       /* This line cannot be executed.  The incoming data has already
@@ -1669,27 +1709,30 @@
        */
       return 0; /* LCOV_EXCL_LINE */
     }
-    if (!CHAR_MATCHES(enc, ptr1, *ptr2))
+    if (! CHAR_MATCHES(enc, ptr1, *ptr2))
       return 0;
   }
   return ptr1 == end1;
 }
 
 static int PTRFASTCALL
-PREFIX(nameLength)(const ENCODING *enc, const char *ptr)
-{
+PREFIX(nameLength)(const ENCODING *enc, const char *ptr) {
   const char *start = ptr;
   for (;;) {
     switch (BYTE_TYPE(enc, ptr)) {
-#define LEAD_CASE(n) \
-    case BT_LEAD ## n: ptr += n; break;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    ptr += n;                                                                  \
+    break;
+      LEAD_CASE(2)
+      LEAD_CASE(3)
+      LEAD_CASE(4)
+#  undef LEAD_CASE
     case BT_NONASCII:
     case BT_NMSTRT:
-#ifdef XML_NS
+#  ifdef XML_NS
     case BT_COLON:
-#endif
+#  endif
     case BT_HEX:
     case BT_DIGIT:
     case BT_NAME:
@@ -1702,9 +1745,8 @@
   }
 }
 
-static const char * PTRFASTCALL
-PREFIX(skipS)(const ENCODING *enc, const char *ptr)
-{
+static const char *PTRFASTCALL
+PREFIX(skipS)(const ENCODING *enc, const char *ptr) {
   for (;;) {
     switch (BYTE_TYPE(enc, ptr)) {
     case BT_LF:
@@ -1719,19 +1761,18 @@
 }
 
 static void PTRCALL
-PREFIX(updatePosition)(const ENCODING *enc,
-                       const char *ptr,
-                       const char *end,
-                       POSITION *pos)
-{
+PREFIX(updatePosition)(const ENCODING *enc, const char *ptr, const char *end,
+                       POSITION *pos) {
   while (HAS_CHAR(enc, ptr, end)) {
     switch (BYTE_TYPE(enc, ptr)) {
-#define LEAD_CASE(n) \
-    case BT_LEAD ## n: \
-      ptr += n; \
-      break;
-    LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4)
-#undef LEAD_CASE
+#  define LEAD_CASE(n)                                                         \
+  case BT_LEAD##n:                                                             \
+    ptr += n;                                                                  \
+    break;
+      LEAD_CASE(2)
+      LEAD_CASE(3)
+      LEAD_CASE(4)
+#  undef LEAD_CASE
     case BT_LF:
       pos->columnNumber = (XML_Size)-1;
       pos->lineNumber++;
@@ -1752,12 +1793,12 @@
   }
 }
 
-#undef DO_LEAD_CASE
-#undef MULTIBYTE_CASES
-#undef INVALID_CASES
-#undef CHECK_NAME_CASE
-#undef CHECK_NAME_CASES
-#undef CHECK_NMSTRT_CASE
-#undef CHECK_NMSTRT_CASES
+#  undef DO_LEAD_CASE
+#  undef MULTIBYTE_CASES
+#  undef INVALID_CASES
+#  undef CHECK_NAME_CASE
+#  undef CHECK_NAME_CASES
+#  undef CHECK_NMSTRT_CASE
+#  undef CHECK_NMSTRT_CASES
 
 #endif /* XML_TOK_IMPL_C */
diff --git a/third_party/expat/files/lib/xmltok_impl.h b/third_party/expat/files/lib/xmltok_impl.h
index a6420f48..e925dbc 100644
--- a/third_party/expat/files/lib/xmltok_impl.h
+++ b/third_party/expat/files/lib/xmltok_impl.h
@@ -31,43 +31,43 @@
 */
 
 enum {
-  BT_NONXML,
-  BT_MALFORM,
-  BT_LT,
-  BT_AMP,
-  BT_RSQB,
-  BT_LEAD2,
-  BT_LEAD3,
-  BT_LEAD4,
-  BT_TRAIL,
-  BT_CR,
-  BT_LF,
-  BT_GT,
-  BT_QUOT,
-  BT_APOS,
-  BT_EQUALS,
-  BT_QUEST,
-  BT_EXCL,
-  BT_SOL,
-  BT_SEMI,
-  BT_NUM,
-  BT_LSQB,
-  BT_S,
-  BT_NMSTRT,
-  BT_COLON,
-  BT_HEX,
-  BT_DIGIT,
-  BT_NAME,
-  BT_MINUS,
-  BT_OTHER, /* known not to be a name or name start character */
+  BT_NONXML,   /* e.g. noncharacter-FFFF */
+  BT_MALFORM,  /* illegal, with regard to encoding */
+  BT_LT,       /* less than = "<" */
+  BT_AMP,      /* ampersand = "&" */
+  BT_RSQB,     /* right square bracket = "[" */
+  BT_LEAD2,    /* lead byte of a 2-byte UTF-8 character */
+  BT_LEAD3,    /* lead byte of a 3-byte UTF-8 character */
+  BT_LEAD4,    /* lead byte of a 4-byte UTF-8 character */
+  BT_TRAIL,    /* trailing unit, e.g. second 16-bit unit of a 4-byte char. */
+  BT_CR,       /* carriage return = "\r" */
+  BT_LF,       /* line feed = "\n" */
+  BT_GT,       /* greater than = ">" */
+  BT_QUOT,     /* quotation character = "\"" */
+  BT_APOS,     /* aposthrophe = "'" */
+  BT_EQUALS,   /* equal sign = "=" */
+  BT_QUEST,    /* question mark = "?" */
+  BT_EXCL,     /* exclamation mark = "!" */
+  BT_SOL,      /* solidus, slash = "/" */
+  BT_SEMI,     /* semicolon = ";" */
+  BT_NUM,      /* number sign = "#" */
+  BT_LSQB,     /* left square bracket = "[" */
+  BT_S,        /* white space, e.g. "\t", " "[, "\r"] */
+  BT_NMSTRT,   /* non-hex name start letter = "G".."Z" + "g".."z" + "_" */
+  BT_COLON,    /* colon = ":" */
+  BT_HEX,      /* hex letter = "A".."F" + "a".."f" */
+  BT_DIGIT,    /* digit = "0".."9" */
+  BT_NAME,     /* dot and middle dot = "." + chr(0xb7) */
+  BT_MINUS,    /* minus = "-" */
+  BT_OTHER,    /* known not to be a name or name start character */
   BT_NONASCII, /* might be a name or name start character */
-  BT_PERCNT,
-  BT_LPAR,
-  BT_RPAR,
-  BT_AST,
-  BT_PLUS,
-  BT_COMMA,
-  BT_VERBAR
+  BT_PERCNT,   /* percent sign = "%" */
+  BT_LPAR,     /* left parenthesis = "(" */
+  BT_RPAR,     /* right parenthesis = "(" */
+  BT_AST,      /* asterisk = "*" */
+  BT_PLUS,     /* plus sign = "+" */
+  BT_COMMA,    /* comma = "," */
+  BT_VERBAR    /* vertical bar = "|" */
 };
 
 #include <stddef.h>
diff --git a/third_party/expat/files/lib/xmltok_ns.c b/third_party/expat/files/lib/xmltok_ns.c
index 23d31e8e..919c74e9 100644
--- a/third_party/expat/files/lib/xmltok_ns.c
+++ b/third_party/expat/files/lib/xmltok_ns.c
@@ -33,56 +33,47 @@
 #ifdef XML_TOK_NS_C
 
 const ENCODING *
-NS(XmlGetUtf8InternalEncoding)(void)
-{
+NS(XmlGetUtf8InternalEncoding)(void) {
   return &ns(internal_utf8_encoding).enc;
 }
 
 const ENCODING *
-NS(XmlGetUtf16InternalEncoding)(void)
-{
-#if BYTEORDER == 1234
+NS(XmlGetUtf16InternalEncoding)(void) {
+#  if BYTEORDER == 1234
   return &ns(internal_little2_encoding).enc;
-#elif BYTEORDER == 4321
+#  elif BYTEORDER == 4321
   return &ns(internal_big2_encoding).enc;
-#else
+#  else
   const short n = 1;
-  return (*(const char *)&n
-          ? &ns(internal_little2_encoding).enc
-          : &ns(internal_big2_encoding).enc);
-#endif
+  return (*(const char *)&n ? &ns(internal_little2_encoding).enc
+                            : &ns(internal_big2_encoding).enc);
+#  endif
 }
 
-static const ENCODING * const NS(encodings)[] = {
-  &ns(latin1_encoding).enc,
-  &ns(ascii_encoding).enc,
-  &ns(utf8_encoding).enc,
-  &ns(big2_encoding).enc,
-  &ns(big2_encoding).enc,
-  &ns(little2_encoding).enc,
-  &ns(utf8_encoding).enc /* NO_ENC */
+static const ENCODING *const NS(encodings)[] = {
+    &ns(latin1_encoding).enc, &ns(ascii_encoding).enc,
+    &ns(utf8_encoding).enc,   &ns(big2_encoding).enc,
+    &ns(big2_encoding).enc,   &ns(little2_encoding).enc,
+    &ns(utf8_encoding).enc /* NO_ENC */
 };
 
 static int PTRCALL
 NS(initScanProlog)(const ENCODING *enc, const char *ptr, const char *end,
-                   const char **nextTokPtr)
-{
-  return initScan(NS(encodings), (const INIT_ENCODING *)enc,
-                  XML_PROLOG_STATE, ptr, end, nextTokPtr);
+                   const char **nextTokPtr) {
+  return initScan(NS(encodings), (const INIT_ENCODING *)enc, XML_PROLOG_STATE,
+                  ptr, end, nextTokPtr);
 }
 
 static int PTRCALL
 NS(initScanContent)(const ENCODING *enc, const char *ptr, const char *end,
-                    const char **nextTokPtr)
-{
-  return initScan(NS(encodings), (const INIT_ENCODING *)enc,
-                  XML_CONTENT_STATE, ptr, end, nextTokPtr);
+                    const char **nextTokPtr) {
+  return initScan(NS(encodings), (const INIT_ENCODING *)enc, XML_CONTENT_STATE,
+                  ptr, end, nextTokPtr);
 }
 
 int
 NS(XmlInitEncoding)(INIT_ENCODING *p, const ENCODING **encPtr,
-                    const char *name)
-{
+                    const char *name) {
   int i = getEncodingIndex(name);
   if (i == UNKNOWN_ENC)
     return 0;
@@ -96,9 +87,8 @@
 }
 
 static const ENCODING *
-NS(findEncoding)(const ENCODING *enc, const char *ptr, const char *end)
-{
-#define ENCODING_MAX 128
+NS(findEncoding)(const ENCODING *enc, const char *ptr, const char *end) {
+#  define ENCODING_MAX 128
   char buf[ENCODING_MAX];
   char *p = buf;
   int i;
@@ -115,28 +105,14 @@
 }
 
 int
-NS(XmlParseXmlDecl)(int isGeneralTextEntity,
-                    const ENCODING *enc,
-                    const char *ptr,
-                    const char *end,
-                    const char **badPtr,
-                    const char **versionPtr,
-                    const char **versionEndPtr,
-                    const char **encodingName,
-                    const ENCODING **encoding,
-                    int *standalone)
-{
-  return doParseXmlDecl(NS(findEncoding),
-                        isGeneralTextEntity,
-                        enc,
-                        ptr,
-                        end,
-                        badPtr,
-                        versionPtr,
-                        versionEndPtr,
-                        encodingName,
-                        encoding,
-                        standalone);
+NS(XmlParseXmlDecl)(int isGeneralTextEntity, const ENCODING *enc,
+                    const char *ptr, const char *end, const char **badPtr,
+                    const char **versionPtr, const char **versionEndPtr,
+                    const char **encodingName, const ENCODING **encoding,
+                    int *standalone) {
+  return doParseXmlDecl(NS(findEncoding), isGeneralTextEntity, enc, ptr, end,
+                        badPtr, versionPtr, versionEndPtr, encodingName,
+                        encoding, standalone);
 }
 
 #endif /* XML_TOK_NS_C */
diff --git a/third_party/tlslite/README.chromium b/third_party/tlslite/README.chromium
index d84deb2..04978d8 100644
--- a/third_party/tlslite/README.chromium
+++ b/third_party/tlslite/README.chromium
@@ -59,3 +59,5 @@
 - patches/tls13_intolerance.patch: Extend the intolerance simulation to TLS 1.3.
 - patches/simulate_tls13_downgrade.patch: Add an option to simulate the TLS 1.3
   downgrade signal.
+- patches/thread_safe_python_rsa_key.patch: Make Python_RSAKey thread safe,
+  inspired by tlslite-ng implementation.
diff --git a/third_party/tlslite/patches/thread_safe_python_rsa_key.patch b/third_party/tlslite/patches/thread_safe_python_rsa_key.patch
new file mode 100644
index 0000000..fe68d88
--- /dev/null
+++ b/third_party/tlslite/patches/thread_safe_python_rsa_key.patch
@@ -0,0 +1,68 @@
+diff --git a/third_party/tlslite/tlslite/utils/python_rsakey.py b/third_party/tlslite/tlslite/utils/python_rsakey.py
+index 1281f1dc899c..a62fc68b4701 100644
+--- a/third_party/tlslite/tlslite/utils/python_rsakey.py
++++ b/third_party/tlslite/tlslite/utils/python_rsakey.py
+@@ -2,7 +2,7 @@
+ # See the LICENSE file for legal information regarding use of this file.
+ 
+ """Pure-Python RSA implementation."""
+-
++import threading
+ from .cryptomath import *
+ from .asn1parser import ASN1Parser
+ from .rsakey import *
+@@ -22,33 +22,36 @@ class Python_RSAKey(RSAKey):
+         self.qInv = qInv
+         self.blinder = 0
+         self.unblinder = 0
++        self._lock = threading.Lock()
+ 
+     def hasPrivateKey(self):
+         return self.d != 0
+ 
+-    def _rawPrivateKeyOp(self, m):
+-        #Create blinding values, on the first pass:
+-        if not self.blinder:
+-            self.unblinder = getRandomNumber(2, self.n)
+-            self.blinder = powMod(invMod(self.unblinder, self.n), self.e,
+-                                  self.n)
+-
+-        #Blind the input
+-        m = (m * self.blinder) % self.n
++    def _rawPrivateKeyOp(self, message):
++        with self._lock:
++            # Create blinding values, on the first pass:
++            if not self.blinder:
++                self.unblinder = getRandomNumber(2, self.n)
++                self.blinder = powMod(invMod(self.unblinder, self.n), self.e,
++                                      self.n)
++            unblinder = self.unblinder
++            blinder = self.blinder
+ 
+-        #Perform the RSA operation
+-        c = self._rawPrivateKeyOpHelper(m)
++            # Update blinding values
++            self.blinder = (self.blinder * self.blinder) % self.n
++            self.unblinder = (self.unblinder * self.unblinder) % self.n
+ 
+-        #Unblind the output
+-        c = (c * self.unblinder) % self.n
++        # Blind the input
++        message = (message * blinder) % self.n
+ 
+-        #Update blinding values
+-        self.blinder = (self.blinder * self.blinder) % self.n
+-        self.unblinder = (self.unblinder * self.unblinder) % self.n
++        # Perform the RSA operation
++        cipher = self._rawPrivateKeyOpHelper(message)
+ 
+-        #Return the output
+-        return c
++        # Unblind the output
++        cipher = (cipher * unblinder) % self.n
+ 
++        # Return the output
++        return cipher
+ 
+     def _rawPrivateKeyOpHelper(self, m):
+         #Non-CRT version
diff --git a/third_party/tlslite/tlslite/utils/python_rsakey.py b/third_party/tlslite/tlslite/utils/python_rsakey.py
index 1281f1d..a62fc68 100644
--- a/third_party/tlslite/tlslite/utils/python_rsakey.py
+++ b/third_party/tlslite/tlslite/utils/python_rsakey.py
@@ -2,7 +2,7 @@
 # See the LICENSE file for legal information regarding use of this file.
 
 """Pure-Python RSA implementation."""
-
+import threading
 from .cryptomath import *
 from .asn1parser import ASN1Parser
 from .rsakey import *
@@ -22,33 +22,36 @@
         self.qInv = qInv
         self.blinder = 0
         self.unblinder = 0
+        self._lock = threading.Lock()
 
     def hasPrivateKey(self):
         return self.d != 0
 
-    def _rawPrivateKeyOp(self, m):
-        #Create blinding values, on the first pass:
-        if not self.blinder:
-            self.unblinder = getRandomNumber(2, self.n)
-            self.blinder = powMod(invMod(self.unblinder, self.n), self.e,
-                                  self.n)
+    def _rawPrivateKeyOp(self, message):
+        with self._lock:
+            # Create blinding values, on the first pass:
+            if not self.blinder:
+                self.unblinder = getRandomNumber(2, self.n)
+                self.blinder = powMod(invMod(self.unblinder, self.n), self.e,
+                                      self.n)
+            unblinder = self.unblinder
+            blinder = self.blinder
 
-        #Blind the input
-        m = (m * self.blinder) % self.n
+            # Update blinding values
+            self.blinder = (self.blinder * self.blinder) % self.n
+            self.unblinder = (self.unblinder * self.unblinder) % self.n
 
-        #Perform the RSA operation
-        c = self._rawPrivateKeyOpHelper(m)
+        # Blind the input
+        message = (message * blinder) % self.n
 
-        #Unblind the output
-        c = (c * self.unblinder) % self.n
+        # Perform the RSA operation
+        cipher = self._rawPrivateKeyOpHelper(message)
 
-        #Update blinding values
-        self.blinder = (self.blinder * self.blinder) % self.n
-        self.unblinder = (self.unblinder * self.unblinder) % self.n
+        # Unblind the output
+        cipher = (cipher * unblinder) % self.n
 
-        #Return the output
-        return c
-
+        # Return the output
+        return cipher
 
     def _rawPrivateKeyOpHelper(self, m):
         #Non-CRT version
diff --git a/tools/binary_size/libsupersize/archive.py b/tools/binary_size/libsupersize/archive.py
index 8205bbb..db1ed6c0 100644
--- a/tools/binary_size/libsupersize/archive.py
+++ b/tools/binary_size/libsupersize/archive.py
@@ -114,6 +114,9 @@
       'META-INF/MANIFEST.MF',
     }
 
+    self.analyze_java = True
+    self.analyze_native = True
+
     self.src_root = path_util.SRC_ROOT
 
 
@@ -1365,10 +1368,12 @@
       elf_object_paths = None
       known_inputs = None
       # When we don't know which elf file is used, just search all paths.
-      thin_archives = set(
-          p for p in source_mapper.IterAllPaths()
-          if p.endswith('.a') and ar.IsThinArchive(
-              os.path.join(output_directory, p)))
+      if knobs.analyze_native:
+        thin_archives = set(
+            p for p in source_mapper.IterAllPaths() if p.endswith('.a')
+            and ar.IsThinArchive(os.path.join(output_directory, p)))
+      else:
+        thin_archives = None
 
     outdir_context = _OutputDirectoryContext(
         elf_object_paths=elf_object_paths,
@@ -1377,13 +1382,17 @@
         source_mapper=source_mapper,
         thin_archives=thin_archives)
 
-  section_sizes, raw_symbols, object_paths_by_name = _ParseElfInfo(
-       map_path,
-       elf_path,
-       tool_prefix,
-       track_string_literals,
-       outdir_context=outdir_context,
-       linker_name=linker_name)
+  if knobs.analyze_native:
+    section_sizes, raw_symbols, object_paths_by_name = _ParseElfInfo(
+        map_path,
+        elf_path,
+        tool_prefix,
+        track_string_literals,
+        outdir_context=outdir_context,
+        linker_name=linker_name)
+  else:
+    section_sizes, raw_symbols, object_paths_by_name = {}, [], None
+
   elf_overhead_size = _CalculateElfOverhead(section_sizes, elf_path)
 
   pak_symbols_by_id = None
@@ -1393,22 +1402,28 @@
           section_sizes, metadata, apk_elf_result)
     pak_symbols_by_id = _FindPakSymbolsFromApk(
         section_sizes, apk_path, size_info_prefix, knobs)
-    dex_symbols = apkanalyzer.CreateDexSymbols(
-        apk_path, mapping_path, size_info_prefix, output_directory)
-    raw_symbols.extend(dex_symbols)
+
     dex_size, other_symbols = _ParseApkOtherSymbols(
         section_sizes, apk_path, apk_so_path, resources_pathmap_path,
         size_info_prefix, knobs)
+
+    if knobs.analyze_java:
+      dex_symbols = apkanalyzer.CreateDexSymbols(
+          apk_path, mapping_path, size_info_prefix, output_directory)
+      raw_symbols.extend(dex_symbols)
+
+      # We can't meaningfully track section size of dex methods vs other, so
+      # just fake the size of dex methods as the sum of symbols, and make
+      # "dex other" responsible for any unattributed bytes.
+      dex_method_size = int(
+          round(
+              sum(s.pss for s in dex_symbols
+                  if s.section_name == models.SECTION_DEX_METHOD)))
+      section_sizes[models.SECTION_DEX_METHOD] = dex_method_size
+      section_sizes[models.SECTION_DEX] = dex_size - dex_method_size
+
     raw_symbols.extend(other_symbols)
 
-    # We can't meaningfully track section size of dex methods vs other, so just
-    # fake the size of dex methods as the sum of symbols, and make "dex other"
-    # responsible for any unattributed bytes.
-    dex_method_size = int(round(sum(
-        s.pss for s in dex_symbols
-        if s.section_name == models.SECTION_DEX_METHOD)))
-    section_sizes[models.SECTION_DEX_METHOD] = dex_method_size
-    section_sizes[models.SECTION_DEX] = dex_size - dex_method_size
   elif pak_files and pak_info_file:
     pak_symbols_by_id = _FindPakSymbolsFromFiles(
         section_sizes, pak_files, pak_info_file, output_directory)
@@ -1422,7 +1437,9 @@
 
   if pak_symbols_by_id:
     logging.debug('Extracting pak IDs from symbol names, and creating symbols')
-    object_paths_by_pak_id = _CreatePakObjectMap(object_paths_by_name)
+    object_paths_by_pak_id = {}
+    if knobs.analyze_native:
+      object_paths_by_pak_id = _CreatePakObjectMap(object_paths_by_name)
     pak_raw_symbols = _ParsePakSymbols(
         pak_symbols_by_id, object_paths_by_pak_id)
     raw_symbols.extend(pak_raw_symbols)
@@ -1612,6 +1629,14 @@
                            'granular symbols.')
   parser.add_argument('--source-directory',
                       help='Custom path to the root source directory.')
+  parser.add_argument(
+      '--java-only', action='store_true', help='Run on only Java symbols')
+  parser.add_argument(
+      '--native-only', action='store_true', help='Run on only native symbols')
+  parser.add_argument(
+      '--no-java', action='store_true', help='Do not run on Java symbols')
+  parser.add_argument(
+      '--no-native', action='store_true', help='Do not run on native symbols')
   AddMainPathsArguments(parser)
 
 
@@ -1742,14 +1767,30 @@
    linker_name, size_info_prefix) = _DeduceMainPaths(
        args, parser, extracted_minimal_apk_path)
 
-  metadata = CreateMetadata(map_path, elf_path, args.apk_file,
-                            args.minimal_apks_file, tool_prefix,
-                            output_directory, linker_name)
-
   knobs = SectionSizeKnobs(is_bundle=bool(extracted_minimal_apk_path))
   if args.source_directory:
     knobs.src_root = args.source_directory
 
+  if args.java_only:
+    knobs.analyze_java = True
+    knobs.analyze_native = False
+  if args.native_only:
+    knobs.analyze_java = False
+    knobs.analyze_native = True
+  if args.no_java:
+    knobs.analyze_java = False
+  if args.no_native:
+    knobs.analyze_native = False
+
+  if not knobs.analyze_native:
+    map_path = None
+    elf_path = None
+    apk_so_path = None
+
+  metadata = CreateMetadata(map_path, elf_path, args.apk_file,
+                            args.minimal_apks_file, tool_prefix,
+                            output_directory, linker_name)
+
   section_sizes, raw_symbols = CreateSectionSizesAndSymbols(
       map_path=map_path,
       tool_prefix=tool_prefix,
diff --git a/tools/binary_size/libsupersize/console.py b/tools/binary_size/libsupersize/console.py
index 85c30f2c6..3152076 100644
--- a/tools/binary_size/libsupersize/console.py
+++ b/tools/binary_size/libsupersize/console.py
@@ -21,6 +21,7 @@
 import describe
 import diff
 import file_format
+import html_report
 import match_util
 import models
 import path_util
@@ -73,6 +74,7 @@
         'Print': self._PrintFunc,
         'Csv': self._CsvFunc,
         'Diff': self._DiffFunc,
+        'SaveNdjson': self._SaveNdjsonFunc,
         'ReadStringLiterals': self._ReadStringLiterals,
         'Disassemble': self._DisassembleFunc,
         'ExpandRegex': match_util.ExpandRegexIdentifierPlaceholder,
@@ -155,6 +157,31 @@
     after = after if after is not None else self._size_infos[1]
     return diff.Diff(before, after, sort=sort)
 
+  def _SaveNdjsonFunc(self, filtered_symbols, size_info=None, to_file=None):
+    """Saves a .ndjson file containing only filtered_symbols into to_file.
+
+    Args:
+      filtered_symbols: Which symbols to include
+      size_info: The size_info to filter. Defaults to size_infos[0].
+      to_file: Defaults to default.ndjson
+    """
+    size_info = size_info or self._size_infos[0]
+    to_file = to_file or 'default.ndjson'
+
+    old_raw_symbols = size_info.raw_symbols
+    size_info.raw_symbols = filtered_symbols
+    html_report.BuildReportFromSizeInfo(to_file, size_info)
+    size_info.raw_symbols = old_raw_symbols
+
+    shortname = os.path.basename(os.path.normpath(to_file))
+    msg = (
+        'Saved locally to {local}. To share, run:\n'
+        '> gsutil.py cp {local} gs://chrome-supersize/oneoffs && gsutil.py -m '
+        'acl ch -u AllUsers:R gs://chrome-supersize/oneoffs/{shortname}\n'
+        '  Then view it at https://storage.googleapis.com/chrome-supersize'
+        '/viewer.html?load_url=oneoffs%2F{shortname}')
+    print msg.format(local=to_file, shortname=shortname)
+
   def _SizeStats(self, size_info=None):
     """Prints some statistics for the given size info.
 
@@ -345,6 +372,10 @@
         '# Diff two .size files and save result to a file:',
         'Print(Diff(size_info1, size_info2), to_file="output.txt")',
         '',
+        '# Save a .ndjson containing only the filtered symbols',
+        'filtered_symbols = size_info.raw_symbols.Filter(lambda l: l.IsPak())',
+        'SaveNdjson(filtered_symbols, size_info, to_file="oneoff_paks.ndjson")',
+        '',
         '# View per-component breakdowns, then drill into the last entry.',
         'c = canned_queries.CategorizeByChromeComponent()',
         'Print(c)',
diff --git a/tools/binary_size/libsupersize/testdata/Console.golden b/tools/binary_size/libsupersize/testdata/Console.golden
index 1d6b910..24494bf 100644
--- a/tools/binary_size/libsupersize/testdata/Console.golden
+++ b/tools/binary_size/libsupersize/testdata/Console.golden
@@ -12,7 +12,7 @@
 
 canned_queries: CategorizeByChromeComponent, CategorizeGenerated, LargeFiles, PakByPath, StaticInitializers, TemplatesByName
 
-Functions: Csv(), Diff(), Disassemble(), ExpandRegex(), Print(), ReadStringLiterals(), ShowExamples(), SizeStats()
+Functions: Csv(), Diff(), Disassemble(), ExpandRegex(), Print(), ReadStringLiterals(), SaveNdjson(), ShowExamples(), SizeStats()
 Variables:
   printed: List of objects passed to Print().
   size_info: Loaded from {redacted}
@@ -49,6 +49,10 @@
 # Diff two .size files and save result to a file:
 Print(Diff(size_info1, size_info2), to_file="output.txt")
 
+# Save a .ndjson containing only the filtered symbols
+filtered_symbols = size_info.raw_symbols.Filter(lambda l: l.IsPak())
+SaveNdjson(filtered_symbols, size_info, to_file="oneoff_paks.ndjson")
+
 # View per-component breakdowns, then drill into the last entry.
 c = canned_queries.CategorizeByChromeComponent()
 Print(c)
diff --git a/tools/binary_size/milestone_apk_sizes.py b/tools/binary_size/milestone_apk_sizes.py
index 8108637..78533d6 100755
--- a/tools/binary_size/milestone_apk_sizes.py
+++ b/tools/binary_size/milestone_apk_sizes.py
@@ -67,6 +67,11 @@
     metrics[self.name + ' (method count)'] = self._resource_sizes_json[
         'charts']['Dex']['unique methods']['value']
 
+  def AddDfmSizes(self, metrics):
+    for k, v in sorted(self._resource_sizes_json['charts'].iteritems()):
+      if k.startswith('DFM_'):
+        metrics['DFM: ' + k[4:]] = v['Size with hindi']['value']
+
   def PrintLibraryCompression(self):
     with zipfile.ZipFile(self._path) as z:
       for info in z.infolist():
@@ -76,6 +81,13 @@
               info.file_size))
 
 
+def _DumpCsv(metrics):
+  csv_writer = csv.DictWriter(
+      sys.stdout, fieldnames=metrics.keys(), delimiter='\t')
+  csv_writer.writeheader()
+  csv_writer.writerow(metrics)
+
+
 def _DownloadAndAnalyze(signed_prefix):
   artifacts = []
 
@@ -105,14 +117,14 @@
   monochrome64.AddSize(metrics)
   webview.AddSize(metrics)
   webview64.AddSize(metrics)
+  _DumpCsv(metrics)
+
+  metrics = collections.OrderedDict()
   monochrome.AddAndroidGoSize(metrics)
   chrome.AddMethodCount(metrics)
   monochrome.AddMethodCount(metrics)
-
-  csv_writer = csv.DictWriter(
-      sys.stdout, fieldnames=metrics.keys(), delimiter='\t')
-  csv_writer.writeheader()
-  csv_writer.writerow(metrics)
+  monochrome.AddDfmSizes(metrics)
+  _DumpCsv(metrics)
 
   webview.PrintLibraryCompression()
 
diff --git a/tools/gritsettings/resource_ids b/tools/gritsettings/resource_ids
index 89c07d2..8849b94 100644
--- a/tools/gritsettings/resource_ids
+++ b/tools/gritsettings/resource_ids
@@ -90,7 +90,7 @@
     "includes": [11930],
     "structures": [11990],
   },
-  "chrome/browser/resources/chromeos/camera/strings/camera_strings.grd": {
+  "chrome/browser/resources/chromeos/camera/src/strings/camera_strings.grd": {
     "messages": [12030],
   },
   "chrome/browser/resources/chromeos/cellular_setup/cellular_setup_resources.grd": {
@@ -152,9 +152,6 @@
   "chrome/browser/resources/tab_strip/tab_strip_resources.grd": {
     "structures": [13880],
   },
-  "chrome/browser/resources/translate_internals/translate_internals_resources.grd": {
-    "includes": [13900],
-  },
   "chrome/browser/resources/webapks/webapks_ui_resources.grd": {
     "includes": [13910],
   },
@@ -194,10 +191,6 @@
   # END chromeos/ section.
 
   # START components/ section.
-  "components/chrome_apps/chrome_apps_resources.grd": {
-    "includes": [15020],
-  },
-
   # Chromium strings and Google Chrome strings must start at the same id.
   # We only use one file depending on whether we're building Chromium or
   # Google Chrome.
@@ -227,7 +220,7 @@
   "components/resources/components_scaled_resources.grd": {
     "structures": [17400],
   },
-  "components/embedder_suppport/android/java/strings/web_contents_delegate_android_strings.grd": {
+  "components/embedder_support/android/java/strings/web_contents_delegate_android_strings.grd": {
     "messages": [17600],
   },
   "components/autofill/core/browser/autofill_address_rewriter_resources.grd":{
@@ -303,9 +296,6 @@
   "ios/web/ios_web_resources.grd": {
     "includes": [20000],
   },
-  "ios/web/shell/shell_resources.grd": {
-    "includes": [21500],
-  },
   "ios/web/test/test_resources.grd": {
     "includes": [22000],
   },
@@ -341,13 +331,6 @@
   "ash/public/cpp/resources/ash_public_unscaled_resources.grd": {
     "includes": [24070],
   },
-  "ash/shell/ash_shell_resources.grd": {
-    "includes": [24080],
-  },
-
-  "chromecast/browser/cast_browser_resources.grd": {
-    "includes": [24100],
-  },
   "chromecast/renderer/resources/extensions_renderer_resources.grd": {
     "includes": [24110],
   },
@@ -437,9 +420,6 @@
   "ui/file_manager/file_manager_resources.grd": {
     "includes": [26550],
   },
-  "ui/login/login_resources.grd": {
-    "includes": [26900],
-  },
   "ui/resources/ui_resources.grd": {
     "structures": [27000],
   },
@@ -459,6 +439,9 @@
     "includes": [27880],
     "structures": [28080],
   },
+  "weblayer/weblayer_resources.grd": {
+    "includes": [28700],
+  },
 
   # This file is generated during the build.
   "<(SHARED_INTERMEDIATE_DIR)/devtools/devtools_resources.grd": {
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml
index 0125ece..08dfbc0f 100644
--- a/tools/metrics/histograms/enums.xml
+++ b/tools/metrics/histograms/enums.xml
@@ -10617,6 +10617,13 @@
   </int>
 </enum>
 
+<enum name="CookieEffectiveSameSite">
+  <int value="0" label="No restriction"/>
+  <int value="1" label="Lax mode"/>
+  <int value="2" label="Strict mode"/>
+  <int value="3" label="Lax mode allow unsafe"/>
+</enum>
+
 <enum name="CookieLoadProblem">
   <int value="0" label="Entry decryption failed"/>
   <int value="1" label="Entry decryption taking over a minute"/>
@@ -18094,6 +18101,8 @@
   <int value="602" label="ReportDeviceOsUpdateStatus"/>
   <int value="603" label="DeviceLoginScreenWebUsbAllowDevicesForUrls"/>
   <int value="604" label="AllowSyncXHRInPageDismissal"/>
+  <int value="605" label="DeviceLoginSpokenFeedbackEnabled"/>
+  <int value="606" label="DeviceLoginScreenHighContrastEnabled"/>
 </enum>
 
 <enum name="EnterprisePolicyInvalidations">
@@ -34758,6 +34767,7 @@
   <int value="-2075725205" label="disable-new-zip-unpacker"/>
   <int value="-2074080173" label="NightLight:disabled"/>
   <int value="-2073617042" label="CrostiniWebUIInstaller:enabled"/>
+  <int value="-2071515296" label="allow-sync-xhr-in-page-dismissal"/>
   <int value="-2067166422" label="enable-slimming-paint-v2"/>
   <int value="-2066541315" label="Mus:enabled"/>
   <int value="-2064164557" label="DownloadsForeground:disabled"/>
@@ -36821,6 +36831,7 @@
   <int value="651421878" label="VideoRotateToFullscreen:enabled"/>
   <int value="651844675" label="EasyUnlockPromotions:enabled"/>
   <int value="652561231" label="CustomContextMenu:enabled"/>
+  <int value="654199907" label="AllowSyncXHRInPageDismissal:disabled"/>
   <int value="656864700" label="FillOnAccountSelectHttp:disabled"/>
   <int value="659086147" label="OverlayScrollbarFlashWhenMouseEnter:enabled"/>
   <int value="661020875" label="AutofillSaveCardShowNoThanks:disabled"/>
@@ -37191,6 +37202,7 @@
   <int value="1182356056" label="MacV2GPUSandbox:enabled"/>
   <int value="1183260592" label="WebAssemblyBaseline:enabled"/>
   <int value="1183431946" label="v8-cache-options"/>
+  <int value="1184225265" label="AllowSyncXHRInPageDismissal:enabled"/>
   <int value="1185424279" label="enable-media-router"/>
   <int value="1190035852" label="MediaRemoting:enabled"/>
   <int value="1192302892" label="gesture-typing"/>
@@ -52839,6 +52851,17 @@
   <int value="3" label="Safety Tip for lookalike URL"/>
 </enum>
 
+<enum name="SameSiteCookieContext">
+  <summary>
+    The SameSiteCookieContext of a request describes the relation between the
+    cookie request and the navigational environment.
+  </summary>
+  <int value="0" label="Cross-site"/>
+  <int value="1" label="Lax method unsafe"/>
+  <int value="2" label="Laxly same-site"/>
+  <int value="3" label="Strictly same-site"/>
+</enum>
+
 <enum name="SamlInSessionPasswordChangeEvent">
   <summary>
     Track how often we try to guide users through the in-session flow to change
@@ -64627,26 +64650,52 @@
 
   <int value="0" label="Invalid Patch Level"/>
   <int value="170393600" label="Windows XP (Build 2600.0)"/>
+  <int value="170417534" label="Windows XP (Build 2600.23934)"/>
+  <int value="170418111" label="Windows XP (Build 2600.24511)"/>
   <int value="393216000" label="Windows Vista (Build 6000.0)"/>
   <int value="393216615" label="Windows Vista (Build 6000.615)"/>
   <int value="393239964" label="Windows Vista (Build 6000.23964)"/>
+  <int value="393240180" label="Windows Vista (Build 6000.24180)"/>
+  <int value="393306030"
+      label="Windows Vista Service Pack 1 (Build 6001.24494)"/>
   <int value="393347072" label="Windows Vista Service Pack 2 (Build 6002.0)"/>
+  <int value="393347339" label="Windows Vista Service Pack 2 (Build 6002.267)"/>
   <int value="393347957" label="Windows Vista Service Pack 2 (Build 6002.885)"/>
+  <int value="393348022" label="Windows Vista Service Pack 2 (Build 6002.950)"/>
+  <int value="393348159"
+      label="Windows Vista Service Pack 2 (Build 6002.1087)"/>
   <int value="393371006"
       label="Windows Vista Service Pack 2 (Build 6002.23934)"/>
   <int value="498073600" label="Windows 7 (Build 7600.0)"/>
+  <int value="498073615" label="Windows 7 (Build 7600.15)"/>
   <int value="498073839" label="Windows 7 (Build 7600.239)"/>
   <int value="498073867" label="Windows 7 (Build 7600.267)"/>
+  <int value="498073895" label="Windows 7 (Build 7600.295)"/>
+  <int value="498073929" label="Windows 7 (Build 7600.329)"/>
+  <int value="498073956" label="Windows 7 (Build 7600.356)"/>
   <int value="498074215" label="Windows 7 (Build 7600.615)"/>
+  <int value="498074278" label="Windows 7 (Build 7600.678)"/>
+  <int value="498074320" label="Windows 7 (Build 7600.720)"/>
+  <int value="498074337" label="Windows 7 (Build 7600.737)"/>
   <int value="498074485" label="Windows 7 (Build 7600.885)"/>
+  <int value="498074550" label="Windows 7 (Build 7600.950)"/>
+  <int value="498074606" label="Windows 7 (Build 7600.1006)"/>
+  <int value="498074868" label="Windows 7 (Build 7600.1268)"/>
+  <int value="498074931" label="Windows 7 (Build 7600.1331)"/>
   <int value="498075814" label="Windows 7 (Build 7600.2214)"/>
   <int value="498083606" label="Windows 7 (Build 7600.10006)"/>
+  <int value="498092782" label="Windows 7 (Build 7600.19182)"/>
   <int value="498097242" label="Windows 7 (Build 7600.23642)"/>
   <int value="498097889" label="Windows 7 (Build 7600.24289)"/>
+  <int value="498097934" label="Windows 7 (Build 7600.24334)"/>
   <int value="498097985" label="Windows 7 (Build 7600.24385)"/>
+  <int value="498098005" label="Windows 7 (Build 7600.24405)"/>
+  <int value="498098043" label="Windows 7 (Build 7600.24443)"/>
   <int value="498098068" label="Windows 7 (Build 7600.24468)"/>
   <int value="498098094" label="Windows 7 (Build 7600.24494)"/>
   <int value="498098096" label="Windows 7 (Build 7600.24496)"/>
+  <int value="498098111" label="Windows 7 (Build 7600.24511)"/>
+  <int value="498098119" label="Windows 7 (Build 7600.24519)"/>
   <int value="498139136" label="Windows 7 Service Pack 1 (Build 7601.0)"/>
   <int value="498162751" label="Windows 7 Service Pack 1 (Build 7601.23615)"/>
   <int value="498162778" label="Windows 7 Service Pack 1 (Build 7601.23642)"/>
@@ -64678,6 +64727,7 @@
   <int value="498163242" label="Windows 7 Service Pack 1 (Build 7601.24106)"/>
   <int value="498163266" label="Windows 7 Service Pack 1 (Build 7601.24130)"/>
   <int value="498163272" label="Windows 7 Service Pack 1 (Build 7601.24136)"/>
+  <int value="498163273" label="Windows 7 Service Pack 1 (Build 7601.24137)"/>
   <int value="498163285" label="Windows 7 Service Pack 1 (Build 7601.24149)"/>
   <int value="498163286" label="Windows 7 Service Pack 1 (Build 7601.24150)"/>
   <int value="498163316" label="Windows 7 Service Pack 1 (Build 7601.24180)"/>
@@ -64705,29 +64755,48 @@
   <int value="498163627" label="Windows 7 Service Pack 1 (Build 7601.24491)"/>
   <int value="498163630" label="Windows 7 Service Pack 1 (Build 7601.24494)"/>
   <int value="498163632" label="Windows 7 Service Pack 1 (Build 7601.24496)"/>
+  <int value="498163647" label="Windows 7 Service Pack 1 (Build 7601.24511)"/>
+  <int value="498163651" label="Windows 7 Service Pack 1 (Build 7601.24515)"/>
+  <int value="498163655" label="Windows 7 Service Pack 1 (Build 7601.24519)"/>
   <int value="550502400" label="Windows 8 Preview (Build 8400.0)"/>
   <int value="602931200" label="Windows 8 (Build 9200.0)"/>
+  <int value="602931201" label="Windows 8 (Build 9200.1)"/>
   <int value="602931251" label="Windows 8 (Build 9200.51)"/>
   <int value="602931439" label="Windows 8 (Build 9200.239)"/>
   <int value="602931467" label="Windows 8 (Build 9200.267)"/>
+  <int value="602931495" label="Windows 8 (Build 9200.295)"/>
+  <int value="602931529" label="Windows 8 (Build 9200.329)"/>
+  <int value="602931556" label="Windows 8 (Build 9200.356)"/>
   <int value="602931607" label="Windows 8 (Build 9200.407)"/>
   <int value="602931703" label="Windows 8 (Build 9200.503)"/>
+  <int value="602931790" label="Windows 8 (Build 9200.590)"/>
   <int value="602931815" label="Windows 8 (Build 9200.615)"/>
   <int value="602931852" label="Windows 8 (Build 9200.652)"/>
+  <int value="602931878" label="Windows 8 (Build 9200.678)"/>
+  <int value="602931937" label="Windows 8 (Build 9200.737)"/>
   <int value="602932029" label="Windows 8 (Build 9200.829)"/>
   <int value="602932085" label="Windows 8 (Build 9200.885)"/>
+  <int value="602932115" label="Windows 8 (Build 9200.915)"/>
   <int value="602932116" label="Windows 8 (Build 9200.916)"/>
+  <int value="602932150" label="Windows 8 (Build 9200.950)"/>
+  <int value="602932200" label="Windows 8 (Build 9200.1000)"/>
+  <int value="602932205" label="Windows 8 (Build 9200.1005)"/>
+  <int value="602932206" label="Windows 8 (Build 9200.1006)"/>
   <int value="602932287" label="Windows 8 (Build 9200.1087)"/>
   <int value="602932618" label="Windows 8 (Build 9200.1418)"/>
   <int value="602941206" label="Windows 8 (Build 9200.10006)"/>
   <int value="602947584" label="Windows 8 (Build 9200.16384)"/>
   <int value="602950601" label="Windows 8 (Build 9200.19401)"/>
+  <int value="602950631" label="Windows 8 (Build 9200.19431)"/>
+  <int value="602950663" label="Windows 8 (Build 9200.19463)"/>
   <int value="602953820" label="Windows 8 (Build 9200.22620)"/>
+  <int value="602953872" label="Windows 8 (Build 9200.22672)"/>
   <int value="602954001" label="Windows 8 (Build 9200.22801)"/>
   <int value="629145600" label="Windows 8.1 (Build 9600.0)"/>
   <int value="629164143" label="Windows 8.1 (Build 9600.18543)"/>
   <int value="629164219" label="Windows 8.1 (Build 9600.18619)"/>
   <int value="629164221" label="Windows 8.1 (Build 9600.18621)"/>
+  <int value="629164254" label="Windows 8.1 (Build 9600.18654)"/>
   <int value="629164284" label="Windows 8.1 (Build 9600.18684)"/>
   <int value="629164287" label="Windows 8.1 (Build 9600.18687)"/>
   <int value="629164320" label="Windows 8.1 (Build 9600.18720)"/>
@@ -64770,6 +64839,9 @@
   <int value="629164999" label="Windows 8.1 (Build 9600.19399)"/>
   <int value="629165001" label="Windows 8.1 (Build 9600.19401)"/>
   <int value="629165004" label="Windows 8.1 (Build 9600.19404)"/>
+  <int value="629165031" label="Windows 8.1 (Build 9600.19431)"/>
+  <int value="629165060" label="Windows 8.1 (Build 9600.19460)"/>
+  <int value="629165063" label="Windows 8.1 (Build 9600.19463)"/>
   <int value="671090283" label="Windows 10 1507 (Build 10240.1643)"/>
   <int value="671090292" label="Windows 10 1507 (Build 10240.1652)"/>
   <int value="671090299" label="Windows 10 1507 (Build 10240.1659)"/>
@@ -64784,12 +64856,15 @@
   <int value="671105085" label="Windows 10 1507 (Build 10240.16445)"/>
   <int value="671105103" label="Windows 10 1507 (Build 10240.16463)"/>
   <int value="671105127" label="Windows 10 1507 (Build 10240.16487)"/>
+  <int value="671105160" label="Windows 10 1507 (Build 10240.16520)"/>
   <int value="671105189" label="Windows 10 1507 (Build 10240.16549)"/>
   <int value="671105206" label="Windows 10 1507 (Build 10240.16566)"/>
+  <int value="671105230" label="Windows 10 1507 (Build 10240.16590)"/>
   <int value="671105241" label="Windows 10 1507 (Build 10240.16601)"/>
   <int value="671105284" label="Windows 10 1507 (Build 10240.16644)"/>
   <int value="671105323" label="Windows 10 1507 (Build 10240.16683)"/>
   <int value="671105365" label="Windows 10 1507 (Build 10240.16725)"/>
+  <int value="671105372" label="Windows 10 1507 (Build 10240.16732)"/>
   <int value="671105411" label="Windows 10 1507 (Build 10240.16771)"/>
   <int value="671105494" label="Windows 10 1507 (Build 10240.16854)"/>
   <int value="671105582" label="Windows 10 1507 (Build 10240.16942)"/>
@@ -64835,6 +64910,8 @@
   <int value="671106858" label="Windows 10 1507 (Build 10240.18218)"/>
   <int value="671106884" label="Windows 10 1507 (Build 10240.18244)"/>
   <int value="671106915" label="Windows 10 1507 (Build 10240.18275)"/>
+  <int value="671106945" label="Windows 10 1507 (Build 10240.18305)"/>
+  <int value="671106973" label="Windows 10 1507 (Build 10240.18333)"/>
   <int value="693764096" label="Windows 10 1511 (Build 10586.0)"/>
   <int value="693764099" label="Windows 10 1511 (Build 10586.3)"/>
   <int value="693764107" label="Windows 10 1511 (Build 10586.11)"/>
@@ -64969,6 +65046,9 @@
   <int value="943262704" label="Windows 10 1607 (Build 14393.3056)"/>
   <int value="943262733" label="Windows 10 1607 (Build 14393.3085)"/>
   <int value="943262763" label="Windows 10 1607 (Build 14393.3115)"/>
+  <int value="943262792" label="Windows 10 1607 (Build 14393.3144)"/>
+  <int value="943262829" label="Windows 10 1607 (Build 14393.3181)"/>
+  <int value="943262852" label="Windows 10 1607 (Build 14393.3204)"/>
   <int value="987168768" label="Windows 10 1703 (Build 15063.0)"/>
   <int value="987168779" label="Windows 10 1703 (Build 15063.11)"/>
   <int value="987168781" label="Windows 10 1703 (Build 15063.13)"/>
@@ -65034,6 +65114,10 @@
   <int value="987170666" label="Windows 10 1703 (Build 15063.1898)"/>
   <int value="987170696" label="Windows 10 1703 (Build 15063.1928)"/>
   <int value="987170723" label="Windows 10 1703 (Build 15063.1955)"/>
+  <int value="987170755" label="Windows 10 1703 (Build 15063.1987)"/>
+  <int value="987170756" label="Windows 10 1703 (Build 15063.1988)"/>
+  <int value="987170789" label="Windows 10 1703 (Build 15063.2021)"/>
+  <int value="987170813" label="Windows 10 1703 (Build 15063.2045)"/>
   <int value="1068171279" label="Windows 10 1709 (Build 16299.15)"/>
   <int value="1068171283" label="Windows 10 1709 (Build 16299.19)"/>
   <int value="1068171328" label="Windows 10 1709 (Build 16299.64)"/>
@@ -65085,6 +65169,9 @@
   <int value="1068172503" label="Windows 10 1709 (Build 16299.1239)"/>
   <int value="1068172532" label="Windows 10 1709 (Build 16299.1268)"/>
   <int value="1068172560" label="Windows 10 1709 (Build 16299.1296)"/>
+  <int value="1068172595" label="Windows 10 1709 (Build 16299.1331)"/>
+  <int value="1068172629" label="Windows 10 1709 (Build 16299.1365)"/>
+  <int value="1068172651" label="Windows 10 1709 (Build 16299.1387)"/>
   <int value="1122893825" label="Windows 10 1803 (Build 17134.1)"/>
   <int value="1122893829" label="Windows 10 1803 (Build 17134.5)"/>
   <int value="1122893856" label="Windows 10 1803 (Build 17134.32)"/>
@@ -65126,6 +65213,9 @@
   <int value="1122894684" label="Windows 10 1803 (Build 17134.860)"/>
   <int value="1122894709" label="Windows 10 1803 (Build 17134.885)"/>
   <int value="1122894739" label="Windows 10 1803 (Build 17134.915)"/>
+  <int value="1122894774" label="Windows 10 1803 (Build 17134.950)"/>
+  <int value="1122894808" label="Windows 10 1803 (Build 17134.984)"/>
+  <int value="1122894830" label="Windows 10 1803 (Build 17134.1006)"/>
   <int value="1164115969" label="Windows 10 1809 (Build 17763.1)"/>
   <int value="1164115985" label="Windows 10 1809 (Build 17763.17)"/>
   <int value="1164116023" label="Windows 10 1809 (Build 17763.55)"/>
@@ -65155,6 +65245,9 @@
   <int value="1164116561" label="Windows 10 1809 (Build 17763.593)"/>
   <int value="1164116583" label="Windows 10 1809 (Build 17763.615)"/>
   <int value="1164116620" label="Windows 10 1809 (Build 17763.652)"/>
+  <int value="1164116646" label="Windows 10 1809 (Build 17763.678)"/>
+  <int value="1164116688" label="Windows 10 1809 (Build 17763.720)"/>
+  <int value="1164116705" label="Windows 10 1809 (Build 17763.737)"/>
   <int value="1203372033" label="Windows 10 1903 (Build 18362.1)"/>
   <int value="1203372062" label="Windows 10 1903 (Build 18362.30)"/>
   <int value="1203372085" label="Windows 10 1903 (Build 18362.53)"/>
@@ -65169,9 +65262,19 @@
   <int value="1203372296" label="Windows 10 1903 (Build 18362.264)"/>
   <int value="1203372298" label="Windows 10 1903 (Build 18362.266)"/>
   <int value="1203372299" label="Windows 10 1903 (Build 18362.267)"/>
+  <int value="1203372327" label="Windows 10 1903 (Build 18362.295)"/>
+  <int value="1203372357" label="Windows 10 1903 (Build 18362.325)"/>
+  <int value="1203372359" label="Windows 10 1903 (Build 18362.327)"/>
+  <int value="1203372361" label="Windows 10 1903 (Build 18362.329)"/>
+  <int value="1203372388" label="Windows 10 1903 (Build 18362.356)"/>
   <int value="1203382032" label="Windows 10 1903 (Build 18362.10000)"/>
   <int value="1203382037" label="Windows 10 1903 (Build 18362.10005)"/>
   <int value="1203382038" label="Windows 10 1903 (Build 18362.10006)"/>
+  <int value="1203382044" label="Windows 10 1903 (Build 18362.10012)"/>
+  <int value="1203382045" label="Windows 10 1903 (Build 18362.10013)"/>
+  <int value="1203382046" label="Windows 10 1903 (Build 18362.10014)"/>
+  <int value="1203382047" label="Windows 10 1903 (Build 18362.10015)"/>
+  <int value="1203382051" label="Windows 10 1903 (Build 18362.10019)"/>
   <int value="1239155688" label="Windows 10 Insider (Build 18908.1000)"/>
   <int value="1240073192" label="Windows 10 Insider (Build 18922.1000)"/>
   <int value="1240728552" label="Windows 10 Insider (Build 18932.1000)"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml
index c1ac71f..96bc7312 100644
--- a/tools/metrics/histograms/histograms.xml
+++ b/tools/metrics/histograms/histograms.xml
@@ -1229,7 +1229,10 @@
 </histogram>
 
 <histogram name="AnchorElementMetrics.Clicked.HrefEngagementScorePositive"
-    units="score" expires_after="M77">
+    units="score">
+  <obsolete>
+    Obsoleted in M79.
+  </obsolete>
   <owner>chelu@chromium.org</owner>
   <owner>tbansal@chromium.org</owner>
   <summary>
@@ -1396,6 +1399,9 @@
 
 <histogram base="true" name="AnchorElementMetrics.DocumentEngagementScore"
     units="score">
+  <obsolete>
+    Obsoleted in M79.
+  </obsolete>
   <owner>chelu@chromium.org</owner>
   <owner>tbansal@chromium.org</owner>
   <summary>
@@ -1406,6 +1412,9 @@
 
 <histogram base="true" name="AnchorElementMetrics.HrefEngagementScore2"
     units="score">
+  <obsolete>
+    Obsoleted in M79.
+  </obsolete>
   <owner>chelu@chromium.org</owner>
   <owner>tbansal@chromium.org</owner>
   <summary>
@@ -1416,6 +1425,9 @@
 
 <histogram base="true" name="AnchorElementMetrics.HrefEngagementScoreExternal"
     units="score">
+  <obsolete>
+    Obsoleted in M79.
+  </obsolete>
   <owner>chelu@chromium.org</owner>
   <owner>tbansal@chromium.org</owner>
   <summary>
@@ -24656,6 +24668,17 @@
   </summary>
 </histogram>
 
+<histogram name="Cookie.RequestSameSiteContext" enum="SameSiteCookieContext"
+    expires_after="M90">
+  <owner>chlily@chromium.org</owner>
+  <owner>morlovich@chromium.org</owner>
+  <summary>
+    The same-site context of a request, i.e. the relationship between the
+    request and the navigational environment. Logged on every request to access
+    a cookie.
+  </summary>
+</histogram>
+
 <histogram name="Cookie.SameSiteAttributeValue" enum="CookieSameSiteString"
     expires_after="M90">
   <owner>chlily@chromium.org</owner>
@@ -24676,6 +24699,18 @@
   </summary>
 </histogram>
 
+<histogram name="Cookie.SameSiteUnspecifiedEffective"
+    enum="CookieEffectiveSameSite" expires_after="M90">
+  <owner>chlily@chromium.org</owner>
+  <owner>morlovich@chromium.org</owner>
+  <summary>
+    If a cookie had an unspecified SameSite attribute, this records what mode it
+    was treated as, i.e. what the effective SameSite mode is. Logged once per
+    attempt to determine SameSite inclusion/exclusion for an
+    unspecified-SameSite cookie.
+  </summary>
+</histogram>
+
 <histogram name="Cookie.SameSiteUnspecifiedTooOldToAllowUnsafe" units="ms"
     expires_after="M85">
   <owner>chlily@chromium.org</owner>
@@ -68976,7 +69011,7 @@
 </histogram>
 
 <histogram name="MobileFre.SignInChoice" enum="MobileFreSignInChoice"
-    expires_after="M77">
+    expires_after="M82">
   <owner>aruslan@chromium.org</owner>
   <summary>
     Android: How the user left the sign-in part of the &quot;first run
@@ -134002,6 +134037,9 @@
 
 <histogram name="SingleThreadedCompositorLatency" units="microseconds"
     expires_after="2020-08-31">
+  <obsolete>
+    Removed on 9/2019: metric is not monitored for the UI compositor.
+  </obsolete>
   <owner>sadrul@chromium.org</owner>
   <owner>graphics-dev@chromium.org</owner>
   <summary>
@@ -134018,6 +134056,9 @@
 
 <histogram name="SingleThreadedCompositorLatency.MissedFrame"
     units="microseconds" expires_after="2020-08-31">
+  <obsolete>
+    Removed on 9/2019: metric is not monitored for the UI compositor.
+  </obsolete>
   <owner>sadrul@chromium.org</owner>
   <owner>graphics-dev@chromium.org</owner>
   <summary>
@@ -164072,23 +164113,63 @@
   <affected-histogram name="CompositorLatency.RAF"/>
   <affected-histogram name="CompositorLatency.TouchScroll"/>
   <affected-histogram name="CompositorLatency.WheelScroll"/>
-  <affected-histogram name="SingleThreadedCompositorLatency"/>
+  <affected-histogram name="SingleThreadedCompositorLatency">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
-      name="SingleThreadedCompositorLatency.CompositorAnimation"/>
+      name="SingleThreadedCompositorLatency.CompositorAnimation">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
-      name="SingleThreadedCompositorLatency.MainThreadAnimation"/>
-  <affected-histogram name="SingleThreadedCompositorLatency.MissedFrame"/>
+      name="SingleThreadedCompositorLatency.MainThreadAnimation">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
+  <affected-histogram name="SingleThreadedCompositorLatency.MissedFrame">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
-      name="SingleThreadedCompositorLatency.MissedFrame.CompositorAnimation"/>
+      name="SingleThreadedCompositorLatency.MissedFrame.CompositorAnimation">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
-      name="SingleThreadedCompositorLatency.MissedFrame.MainThreadAnimation"/>
+      name="SingleThreadedCompositorLatency.MissedFrame.MainThreadAnimation">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
-      name="SingleThreadedCompositorLatency.MissedFrame.PinchZoom"/>
-  <affected-histogram name="SingleThreadedCompositorLatency.MissedFrame.RAF"/>
+      name="SingleThreadedCompositorLatency.MissedFrame.PinchZoom">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
+  <affected-histogram name="SingleThreadedCompositorLatency.MissedFrame.RAF">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
-      name="SingleThreadedCompositorLatency.MissedFrame.TouchScroll"/>
+      name="SingleThreadedCompositorLatency.MissedFrame.TouchScroll">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
-      name="SingleThreadedCompositorLatency.MissedFrame.WheelScroll"/>
+      name="SingleThreadedCompositorLatency.MissedFrame.WheelScroll">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
   <affected-histogram
       name="SingleThreadedCompositorLatency.MissedFrameLatencyIncrease">
     <obsolete>
@@ -164131,10 +164212,26 @@
       Removed on 9/2019. Did not provide enough information about latency.
     </obsolete>
   </affected-histogram>
-  <affected-histogram name="SingleThreadedCompositorLatency.PinchZoom"/>
-  <affected-histogram name="SingleThreadedCompositorLatency.RAF"/>
-  <affected-histogram name="SingleThreadedCompositorLatency.TouchScroll"/>
-  <affected-histogram name="SingleThreadedCompositorLatency.WheelScroll"/>
+  <affected-histogram name="SingleThreadedCompositorLatency.PinchZoom">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
+  <affected-histogram name="SingleThreadedCompositorLatency.RAF">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
+  <affected-histogram name="SingleThreadedCompositorLatency.TouchScroll">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
+  <affected-histogram name="SingleThreadedCompositorLatency.WheelScroll">
+    <obsolete>
+      Removed on 9/2019: metric is not monitored for the UI compositor.
+    </obsolete>
+  </affected-histogram>
 </histogram_suffixes>
 
 <histogram_suffixes name="CompositorPendingTreeType" separator=".">
diff --git a/tools/traffic_annotation/auditor/BUILD.gn b/tools/traffic_annotation/auditor/BUILD.gn
index 8c9f65c5..b3c2a1e 100644
--- a/tools/traffic_annotation/auditor/BUILD.gn
+++ b/tools/traffic_annotation/auditor/BUILD.gn
@@ -18,6 +18,8 @@
         "/components/policy/proto/cloud_policy_full_runtime.proto",
     "$root_gen_dir" +
         "/components/policy/proto/chrome_settings_full_runtime.proto",
+    "$root_gen_dir" +
+        "/components/policy/proto/policy_common_definitions_full_runtime.proto",
   ]
 
   use_protobuf_full = true
diff --git a/tools/traffic_annotation/summary/annotations.xml b/tools/traffic_annotation/summary/annotations.xml
index de32b09..5cc6255f 100644
--- a/tools/traffic_annotation/summary/annotations.xml
+++ b/tools/traffic_annotation/summary/annotations.xml
@@ -295,7 +295,7 @@
  <item id="web_push_message" hash_code="39886742" type="0" content_hash_code="110064650" os_list="linux,windows" file_path="components/gcm_driver/web_push_sender.cc"/>
  <item id="webrtc_event_log_uploader" hash_code="24186190" type="0" content_hash_code="11005245" os_list="linux,windows" file_path="chrome/browser/media/webrtc/webrtc_event_log_uploader.cc"/>
  <item id="webrtc_log_upload" hash_code="62443804" type="0" content_hash_code="33661169" os_list="linux,windows" file_path="chrome/browser/media/webrtc/webrtc_log_uploader.cc"/>
- <item id="webrtc_peer_connection" hash_code="63497370" type="0" content_hash_code="60553259" os_list="linux,windows" file_path="third_party/blink/renderer/modules/peerconnection/peer_connection_dependency_factory.cc"/>
+ <item id="webrtc_peer_connection" hash_code="63497370" type="0" content_hash_code="60553259" os_list="linux,windows" file_path="content/renderer/media/webrtc/peer_connection_dependency_factory.cc"/>
  <item id="websocket_basic_stream" hash_code="51586722" type="0" content_hash_code="68121427" os_list="linux,windows" file_path="net/websockets/websocket_basic_stream.cc"/>
  <item id="websocket_stream" hash_code="17188928" type="0" content_hash_code="7250776" os_list="linux,windows" file_path="net/websockets/websocket_stream.cc"/>
  <item id="webstore_data_fetcher" hash_code="26302604" type="0" content_hash_code="24000746" os_list="linux,windows" file_path="chrome/browser/extensions/webstore_data_fetcher.cc"/>
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc
index 692533b..4daefd7 100644
--- a/ui/accessibility/platform/ax_platform_node_auralinux.cc
+++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -4177,18 +4177,18 @@
     case ax::mojom::TextDirection::kNone:
       break;
     case ax::mojom::TextDirection::kLtr:
-      AddTextAttributeToSet(ATK_TEXT_ATTR_LANGUAGE, "ltr", &attributes);
+      AddTextAttributeToSet(ATK_TEXT_ATTR_DIRECTION, "ltr", &attributes);
       break;
     case ax::mojom::TextDirection::kRtl:
-      AddTextAttributeToSet(ATK_TEXT_ATTR_LANGUAGE, "rtl", &attributes);
+      AddTextAttributeToSet(ATK_TEXT_ATTR_DIRECTION, "rtl", &attributes);
       break;
     case ax::mojom::TextDirection::kTtb:
       // Not listed in the ATK docs.
-      AddTextAttributeToSet(ATK_TEXT_ATTR_LANGUAGE, "ttb", &attributes);
+      AddTextAttributeToSet(ATK_TEXT_ATTR_DIRECTION, "ttb", &attributes);
       break;
     case ax::mojom::TextDirection::kBtt:
       // Not listed in the ATK docs.
-      AddTextAttributeToSet(ATK_TEXT_ATTR_LANGUAGE, "btt", &attributes);
+      AddTextAttributeToSet(ATK_TEXT_ATTR_DIRECTION, "btt", &attributes);
       break;
   }
 
diff --git a/ui/aura/test/ui_controls_factory_aurawin.cc b/ui/aura/test/ui_controls_factory_aurawin.cc
index 82cea207..ad765361 100644
--- a/ui/aura/test/ui_controls_factory_aurawin.cc
+++ b/ui/aura/test/ui_controls_factory_aurawin.cc
@@ -24,7 +24,6 @@
 using ui_controls::RIGHT;
 using ui_controls::UIControlsAura;
 using ui_controls::UP;
-using namespace ui_controls::internal;
 
 class UIControlsWin : public UIControlsAura {
  public:
@@ -40,8 +39,8 @@
     DCHECK(!command);  // No command key on Aura
     HWND window =
         native_window->GetHost()->GetAcceleratedWidget();
-    return SendKeyPressImpl(window, key, control, shift, alt,
-                            base::OnceClosure());
+    return ui_controls::internal::SendKeyPressImpl(window, key, control, shift,
+                                                   alt, base::OnceClosure());
   }
   bool SendKeyPressNotifyWhenDone(gfx::NativeWindow native_window,
                                   ui::KeyboardCode key,
@@ -53,34 +52,37 @@
     DCHECK(!command);  // No command key on Aura
     HWND window =
         native_window->GetHost()->GetAcceleratedWidget();
-    return SendKeyPressImpl(window, key, control, shift, alt, std::move(task));
+    return ui_controls::internal::SendKeyPressImpl(window, key, control, shift,
+                                                   alt, std::move(task));
   }
   bool SendMouseMove(long screen_x, long screen_y) override {
-    return SendMouseMoveImpl(screen_x, screen_y, base::OnceClosure());
+    return ui_controls::internal::SendMouseMoveImpl(screen_x, screen_y,
+                                                    base::OnceClosure());
   }
   bool SendMouseMoveNotifyWhenDone(long screen_x,
                                    long screen_y,
                                    base::OnceClosure task) override {
-    return SendMouseMoveImpl(screen_x, screen_y, std::move(task));
+    return ui_controls::internal::SendMouseMoveImpl(screen_x, screen_y,
+                                                    std::move(task));
   }
   bool SendMouseEvents(MouseButton type,
                        int button_state,
                        int accelerator_state) override {
-    return SendMouseEventsImpl(type, button_state, base::OnceClosure(),
-                               accelerator_state);
+    return ui_controls::internal::SendMouseEventsImpl(
+        type, button_state, base::OnceClosure(), accelerator_state);
   }
   bool SendMouseEventsNotifyWhenDone(MouseButton type,
                                      int button_state,
                                      base::OnceClosure task,
                                      int accelerator_state) override {
-    return SendMouseEventsImpl(type, button_state, std::move(task),
-                               accelerator_state);
+    return ui_controls::internal::SendMouseEventsImpl(
+        type, button_state, std::move(task), accelerator_state);
   }
   bool SendMouseClick(MouseButton type) override {
     return SendMouseEvents(type, UP | DOWN, ui_controls::kNoAccelerator);
   }
   bool SendTouchEvents(int action, int num, int x, int y) override {
-    return SendTouchEventsImpl(action, num, x, y);
+    return ui_controls::internal::SendTouchEventsImpl(action, num, x, y);
   }
 
  private:
diff --git a/ui/base/ime/fuchsia/BUILD.gn b/ui/base/ime/fuchsia/BUILD.gn
index 83e6d24..281366e 100644
--- a/ui/base/ime/fuchsia/BUILD.gn
+++ b/ui/base/ime/fuchsia/BUILD.gn
@@ -19,6 +19,7 @@
   defines = [ "IS_UI_BASE_IME_FUCHSIA_IMPL" ]
 
   public_deps = [
+    "//third_party/fuchsia-sdk/sdk:sys_cpp",
     "//third_party/fuchsia-sdk/sdk:ui_input",
     "//ui/base/ime",
     "//ui/events",
diff --git a/ui/base/ime/fuchsia/input_method_fuchsia.cc b/ui/base/ime/fuchsia/input_method_fuchsia.cc
index f3d0e1a2..8238d841 100644
--- a/ui/base/ime/fuchsia/input_method_fuchsia.cc
+++ b/ui/base/ime/fuchsia/input_method_fuchsia.cc
@@ -5,10 +5,11 @@
 #include "ui/base/ime/fuchsia/input_method_fuchsia.h"
 
 #include <fuchsia/ui/input/cpp/fidl.h>
+#include <lib/sys/cpp/component_context.h>
 #include <memory>
 #include <utility>
 
-#include "base/fuchsia/service_directory_client.h"
+#include "base/fuchsia/default_context.h"
 #include "ui/base/ime/text_input_client.h"
 #include "ui/events/base_event_utils.h"
 #include "ui/events/keycodes/dom/dom_code.h"
@@ -20,8 +21,9 @@
     : InputMethodBase(delegate),
       event_converter_(this),
       ime_client_binding_(this),
-      ime_service_(base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-                       ->ConnectToService<fuchsia::ui::input::ImeService>()),
+      ime_service_(base::fuchsia::ComponentContextForCurrentProcess()
+                       ->svc()
+                       ->Connect<fuchsia::ui::input::ImeService>()),
       virtual_keyboard_controller_(ime_service_.get()) {}
 
 InputMethodFuchsia::~InputMethodFuchsia() {}
diff --git a/ui/base/ime/fuchsia/input_method_keyboard_controller_fuchsia.cc b/ui/base/ime/fuchsia/input_method_keyboard_controller_fuchsia.cc
index 47ca7597..c284253 100644
--- a/ui/base/ime/fuchsia/input_method_keyboard_controller_fuchsia.cc
+++ b/ui/base/ime/fuchsia/input_method_keyboard_controller_fuchsia.cc
@@ -4,10 +4,11 @@
 
 #include "ui/base/ime/fuchsia/input_method_keyboard_controller_fuchsia.h"
 
+#include <lib/sys/cpp/component_context.h>
 #include <utility>
 
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 #include "base/logging.h"
 
 namespace ui {
@@ -16,8 +17,9 @@
     fuchsia::ui::input::ImeService* ime_service)
     : ime_service_(ime_service),
       ime_visibility_(
-          base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-              ->ConnectToService<fuchsia::ui::input::ImeVisibilityService>()) {
+          base::fuchsia::ComponentContextForCurrentProcess()
+              ->svc()
+              ->Connect<fuchsia::ui::input::ImeVisibilityService>()) {
   DCHECK(ime_service_);
 
   ime_visibility_.set_error_handler([](zx_status_t status) {
diff --git a/ui/gl/gl_surface_presentation_helper.cc b/ui/gl/gl_surface_presentation_helper.cc
index 8593e43..c11968e 100644
--- a/ui/gl/gl_surface_presentation_helper.cc
+++ b/ui/gl/gl_surface_presentation_helper.cc
@@ -275,7 +275,6 @@
     return;
   }
 
-  bool need_update_vsync = false;
   bool disjoint_occurred =
       gpu_timing_client_ && gpu_timing_client_->CheckAndResetTimerErrors();
   if (disjoint_occurred ||
@@ -299,13 +298,6 @@
         std::move(frame.callback).Run(gfx::PresentationFeedback::Failure());
     }
     pending_frames_.clear();
-    // We want to update VSync, if we can not get VSync parameters
-    // synchronously. Otherwise we will update the VSync parameters with the
-    // next SwapBuffers.
-    if (vsync_provider_ &&
-        !vsync_provider_->SupportGetVSyncParametersIfAvailable()) {
-      need_update_vsync = true;
-    }
   }
 
   while (!pending_frames_.empty()) {
@@ -337,9 +329,8 @@
         gfx::PresentationFeedback(timestamp, interval, flags));
   }
 
-  if (pending_frames_.empty() && !need_update_vsync)
-    return;
-  ScheduleCheckPendingFrames(true /* align_with_next_vsync */);
+  if (!pending_frames_.empty())
+    ScheduleCheckPendingFrames(true /* align_with_next_vsync */);
 }
 
 void GLSurfacePresentationHelper::CheckPendingFramesCallback() {
@@ -349,21 +340,42 @@
 }
 
 void GLSurfacePresentationHelper::UpdateVSyncCallback(
+    bool should_check_pending_frames,
     const base::TimeTicks timebase,
     const base::TimeDelta interval) {
-  DCHECK(check_pending_frame_scheduled_);
-  check_pending_frame_scheduled_ = false;
+  DCHECK(update_vsync_pending_);
+  update_vsync_pending_ = false;
   vsync_timebase_ = timebase;
   vsync_interval_ = interval;
-  CheckPendingFrames();
+  if (should_check_pending_frames) {
+    DCHECK(check_pending_frame_scheduled_);
+    check_pending_frame_scheduled_ = false;
+    CheckPendingFrames();
+  }
 }
 
 void GLSurfacePresentationHelper::ScheduleCheckPendingFrames(
     bool align_with_next_vsync) {
+  // Always GetVSyncParameters to minimize clock-skew in vsync_timebase_.
+  bool vsync_provider_schedules_check = false;
+  if (vsync_provider_ &&
+      !vsync_provider_->SupportGetVSyncParametersIfAvailable() &&
+      !update_vsync_pending_) {
+    update_vsync_pending_ = true;
+    vsync_provider_schedules_check =
+        !check_pending_frame_scheduled_ && !align_with_next_vsync;
+    vsync_provider_->GetVSyncParameters(base::BindOnce(
+        &GLSurfacePresentationHelper::UpdateVSyncCallback,
+        weak_ptr_factory_.GetWeakPtr(), vsync_provider_schedules_check));
+  }
+
   if (check_pending_frame_scheduled_)
     return;
   check_pending_frame_scheduled_ = true;
 
+  if (vsync_provider_schedules_check)
+    return;
+
   if (!align_with_next_vsync) {
     base::ThreadTaskRunnerHandle::Get()->PostTask(
         FROM_HERE,
@@ -372,16 +384,6 @@
     return;
   }
 
-  if (vsync_provider_ &&
-      !vsync_provider_->SupportGetVSyncParametersIfAvailable()) {
-    // In this case, the |vsync_provider_| will call the callback when the next
-    // VSync is received.
-    vsync_provider_->GetVSyncParameters(
-        base::BindRepeating(&GLSurfacePresentationHelper::UpdateVSyncCallback,
-                            weak_ptr_factory_.GetWeakPtr()));
-    return;
-  }
-
   // If the |vsync_provider_| can not notify us for the next VSync
   // asynchronically, we have to compute the next VSync time and post a delayed
   // task so we can check the VSync later.
diff --git a/ui/gl/gl_surface_presentation_helper.h b/ui/gl/gl_surface_presentation_helper.h
index 88d8738..67a163c 100644
--- a/ui/gl/gl_surface_presentation_helper.h
+++ b/ui/gl/gl_surface_presentation_helper.h
@@ -91,7 +91,8 @@
   // Callback used by PostDelayedTask for running CheckPendingFrames().
   void CheckPendingFramesCallback();
 
-  void UpdateVSyncCallback(const base::TimeTicks timebase,
+  void UpdateVSyncCallback(bool should_check_pending_frames,
+                           const base::TimeTicks timebase,
                            const base::TimeDelta interval);
 
   void ScheduleCheckPendingFrames(bool align_with_next_vsync);
@@ -106,6 +107,7 @@
   bool check_pending_frame_scheduled_ = false;
   bool gl_fence_supported_ = false;
   EGLTimestampClient* egl_timestamp_client_ = nullptr;
+  bool update_vsync_pending_ = false;
 
   base::WeakPtrFactory<GLSurfacePresentationHelper> weak_ptr_factory_{this};
 
diff --git a/ui/native_theme/caption_style_win.cc b/ui/native_theme/caption_style_win.cc
index 9706bb1..0e081c5 100644
--- a/ui/native_theme/caption_style_win.cc
+++ b/ui/native_theme/caption_style_win.cc
@@ -18,9 +18,9 @@
 #include "ui/gfx/color_utils.h"
 #include "ui/gfx/geometry/safe_integer_conversions.h"
 
-namespace ui {
+namespace CC = ABI::Windows::Media::ClosedCaptioning;
 
-using namespace ABI::Windows::Media::ClosedCaptioning;
+namespace ui {
 
 namespace {
 
@@ -44,34 +44,34 @@
 // CSS FontFamily value.
 // These fonts were chosen to satisfy the characteristics represented by values
 // of ClosedCaptionStyle Enum in Windows Settings.
-void GetFontFamilyString(ClosedCaptionStyle closed_caption_style,
+void GetFontFamilyString(CC::ClosedCaptionStyle closed_caption_style,
                          std::string* css_font_family,
                          std::string* css_font_variant) {
   *css_font_variant = "normal";
   switch (closed_caption_style) {
-    case ClosedCaptionStyle_MonospacedWithSerifs:
+    case CC::ClosedCaptionStyle_MonospacedWithSerifs:
       *css_font_family = "Courier New";
       break;
-    case ClosedCaptionStyle_ProportionalWithSerifs:
+    case CC::ClosedCaptionStyle_ProportionalWithSerifs:
       *css_font_family = "Times New Roman";
       break;
-    case ClosedCaptionStyle_MonospacedWithoutSerifs:
+    case CC::ClosedCaptionStyle_MonospacedWithoutSerifs:
       *css_font_family = "Consolas";
       break;
-    case ClosedCaptionStyle_ProportionalWithoutSerifs:
+    case CC::ClosedCaptionStyle_ProportionalWithoutSerifs:
       *css_font_family = "Tahoma";
       break;
-    case ClosedCaptionStyle_Casual:
+    case CC::ClosedCaptionStyle_Casual:
       *css_font_family = "Segoe Print";
       break;
-    case ClosedCaptionStyle_Cursive:
+    case CC::ClosedCaptionStyle_Cursive:
       *css_font_family = "Segoe Script";
       break;
-    case ClosedCaptionStyle_SmallCapitals:
+    case CC::ClosedCaptionStyle_SmallCapitals:
       *css_font_family = "Tahoma";
       *css_font_variant = "small-caps";
       break;
-    case ClosedCaptionStyle_Default:
+    case CC::ClosedCaptionStyle_Default:
       // We shouldn't override with OS Styling for Default case.
       NOTREACHED();
       *css_font_family = std::string();
@@ -81,23 +81,23 @@
 
 // Translates a Windows::Media::ClosedCaptioning::ClosedCaptionEdgeEffect to a
 // CSS style value.
-std::string GetEdgeEffectString(ClosedCaptionEdgeEffect edge_effect) {
+std::string GetEdgeEffectString(CC::ClosedCaptionEdgeEffect edge_effect) {
   switch (edge_effect) {
-    case ClosedCaptionEdgeEffect_None:
+    case CC::ClosedCaptionEdgeEffect_None:
       return "none";
-    case ClosedCaptionEdgeEffect_Raised:
+    case CC::ClosedCaptionEdgeEffect_Raised:
       return "-1px 0px 0px silver, 0px -1px 0px silver, 1px 1px 0px black, 2px "
              "2px 0px black, 3px 3px 0px black";
-    case ClosedCaptionEdgeEffect_Depressed:
+    case CC::ClosedCaptionEdgeEffect_Depressed:
       return "1px 1px 0px silver, 0px 1px 0px silver, -1px -1px 0px black, "
              "-1px "
              "0px 0px black";
-    case ClosedCaptionEdgeEffect_Uniform:
+    case CC::ClosedCaptionEdgeEffect_Uniform:
       return "0px 0px 4px black, 0px 0px 4px black, 0px 0px 4px black, 0px 0px "
              "4px black";
-    case ClosedCaptionEdgeEffect_DropShadow:
+    case CC::ClosedCaptionEdgeEffect_DropShadow:
       return "3px 3px 3px 2px black";
-    case ClosedCaptionEdgeEffect_Default:
+    case CC::ClosedCaptionEdgeEffect_Default:
       // We shouldn't override with OS Styling for Default case.
       NOTREACHED();
       return std::string();
@@ -106,17 +106,17 @@
 
 // Translates a Windows::Media::ClosedCaptioning::ClosedCaptionSize to a CSS
 // style value.
-std::string GetCaptionSizeString(ClosedCaptionSize caption_size) {
+std::string GetCaptionSizeString(CC::ClosedCaptionSize caption_size) {
   switch (caption_size) {
-    case ClosedCaptionSize_FiftyPercent:
+    case CC::ClosedCaptionSize_FiftyPercent:
       return "50%";
-    case ClosedCaptionSize_OneHundredPercent:
+    case CC::ClosedCaptionSize_OneHundredPercent:
       return "100%";
-    case ClosedCaptionSize_OneHundredFiftyPercent:
+    case CC::ClosedCaptionSize_OneHundredFiftyPercent:
       return "150%";
-    case ClosedCaptionSize_TwoHundredPercent:
+    case CC::ClosedCaptionSize_TwoHundredPercent:
       return "200%";
-    case ClosedCaptionSize_Default:
+    case CC::ClosedCaptionSize_Default:
       // We shouldn't override with OS Styling for Default case.
       NOTREACHED();
       return std::string();
@@ -125,16 +125,16 @@
 
 // Translates a Windows::Media::ClosedCaptioning::ClosedCaptionOpacity to an
 // SkAlpha value.
-SkAlpha GetCaptionOpacity(ClosedCaptionOpacity caption_opacity) {
+SkAlpha GetCaptionOpacity(CC::ClosedCaptionOpacity caption_opacity) {
   switch (caption_opacity) {
-    case ClosedCaptionOpacity_ZeroPercent:
+    case CC::ClosedCaptionOpacity_ZeroPercent:
       return SK_AlphaTRANSPARENT;
-    case ClosedCaptionOpacity_TwentyFivePercent:
+    case CC::ClosedCaptionOpacity_TwentyFivePercent:
       return gfx::ToRoundedInt(SK_AlphaOPAQUE * 0.25);
-    case ClosedCaptionOpacity_SeventyFivePercent:
+    case CC::ClosedCaptionOpacity_SeventyFivePercent:
       return gfx::ToRoundedInt(SK_AlphaOPAQUE * 0.75);
-    case ClosedCaptionOpacity_OneHundredPercent:
-    case ClosedCaptionOpacity_Default:
+    case CC::ClosedCaptionOpacity_OneHundredPercent:
+    case CC::ClosedCaptionOpacity_Default:
     default:
       return SK_AlphaOPAQUE;
   }
@@ -142,25 +142,25 @@
 
 // Translates a Windows::Media::ClosedCaptioning::ClosedCaptionColor to an
 // SkColor value.
-SkColor GetCaptionColor(ClosedCaptionColor caption_color) {
+SkColor GetCaptionColor(CC::ClosedCaptionColor caption_color) {
   switch (caption_color) {
-    case ClosedCaptionColor_Black:
+    case CC::ClosedCaptionColor_Black:
       return SK_ColorBLACK;
-    case ClosedCaptionColor_Red:
+    case CC::ClosedCaptionColor_Red:
       return SK_ColorRED;
-    case ClosedCaptionColor_Green:
+    case CC::ClosedCaptionColor_Green:
       return SK_ColorGREEN;
-    case ClosedCaptionColor_Blue:
+    case CC::ClosedCaptionColor_Blue:
       return SK_ColorBLUE;
-    case ClosedCaptionColor_Yellow:
+    case CC::ClosedCaptionColor_Yellow:
       return SK_ColorYELLOW;
-    case ClosedCaptionColor_Magenta:
+    case CC::ClosedCaptionColor_Magenta:
       return SK_ColorMAGENTA;
-    case ClosedCaptionColor_Cyan:
+    case CC::ClosedCaptionColor_Cyan:
       return SK_ColorCYAN;
-    case ClosedCaptionColor_White:
+    case CC::ClosedCaptionColor_White:
       return SK_ColorWHITE;
-    case ClosedCaptionColor_Default:
+    case CC::ClosedCaptionColor_Default:
     default:
       // We shouldn't override with OS Styling for Default case.
       NOTREACHED();
@@ -171,8 +171,8 @@
 // Translates a Windows::Media::ClosedCaptioning::ClosedCaptionColor and a
 // Windows::Media::ClosedCaptioning::ClosedCaptionOpacity to an RGBA CSS color
 // string.
-std::string GetCssColorWithAlpha(ClosedCaptionColor caption_color,
-                                 ClosedCaptionOpacity caption_opacity) {
+std::string GetCssColorWithAlpha(CC::ClosedCaptionColor caption_color,
+                                 CC::ClosedCaptionOpacity caption_opacity) {
   const SkAlpha opacity = GetCaptionOpacity(caption_opacity);
   const SkColor color = GetCaptionColor(caption_color);
   return color_utils::SkColorToRgbaString(SkColorSetA(color, opacity));
@@ -196,7 +196,7 @@
   base::win::ScopedHString closed_caption_properties_string =
       base::win::ScopedHString::Create(
           RuntimeClass_Windows_Media_ClosedCaptioning_ClosedCaptionProperties);
-  Microsoft::WRL::ComPtr<IClosedCaptionPropertiesStatics>
+  Microsoft::WRL::ComPtr<CC::IClosedCaptionPropertiesStatics>
       closed_caption_properties_statics;
   HRESULT hr = base::win::RoGetActivationFactory(
       closed_caption_properties_string.get(),
@@ -208,7 +208,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionSize font_size = ClosedCaptionSize_Default;
+  CC::ClosedCaptionSize font_size = CC::ClosedCaptionSize_Default;
   hr = closed_caption_properties_statics->get_FontSize(&font_size);
   if (FAILED(hr)) {
     DLOG(ERROR) << "Failed to retrieve Font Size"
@@ -217,7 +217,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionEdgeEffect edge_effect = ClosedCaptionEdgeEffect_Default;
+  CC::ClosedCaptionEdgeEffect edge_effect = CC::ClosedCaptionEdgeEffect_Default;
   hr = closed_caption_properties_statics->get_FontEffect(&edge_effect);
   if (FAILED(hr)) {
     DLOG(ERROR) << "Failed to retrieve Font Effect"
@@ -226,7 +226,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionStyle font_family = ClosedCaptionStyle_Default;
+  CC::ClosedCaptionStyle font_family = CC::ClosedCaptionStyle_Default;
   hr = closed_caption_properties_statics->get_FontStyle(&font_family);
   if (FAILED(hr)) {
     DLOG(ERROR) << "Failed to retrieve Font Family"
@@ -235,7 +235,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionColor font_color = ClosedCaptionColor_Default;
+  CC::ClosedCaptionColor font_color = CC::ClosedCaptionColor_Default;
   hr = closed_caption_properties_statics->get_FontColor(&font_color);
   if (FAILED(hr)) {
     DLOG(ERROR) << "Failed to retrieve Font Color"
@@ -244,7 +244,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionOpacity font_opacity = ClosedCaptionOpacity_Default;
+  CC::ClosedCaptionOpacity font_opacity = CC::ClosedCaptionOpacity_Default;
   hr = closed_caption_properties_statics->get_FontOpacity(&font_opacity);
   if (FAILED(hr)) {
     DLOG(ERROR) << "Failed to retrieve Font Opacity"
@@ -253,7 +253,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionColor background_color = ClosedCaptionColor_Default;
+  CC::ClosedCaptionColor background_color = CC::ClosedCaptionColor_Default;
   hr =
       closed_caption_properties_statics->get_BackgroundColor(&background_color);
   if (FAILED(hr)) {
@@ -263,7 +263,8 @@
     return base::nullopt;
   }
 
-  ClosedCaptionOpacity background_opacity = ClosedCaptionOpacity_Default;
+  CC::ClosedCaptionOpacity background_opacity =
+      CC::ClosedCaptionOpacity_Default;
   hr = closed_caption_properties_statics->get_BackgroundOpacity(
       &background_opacity);
   if (FAILED(hr)) {
@@ -273,7 +274,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionColor region_color = ClosedCaptionColor_Default;
+  CC::ClosedCaptionColor region_color = CC::ClosedCaptionColor_Default;
   hr = closed_caption_properties_statics->get_RegionColor(&region_color);
   if (FAILED(hr)) {
     DLOG(ERROR) << "Failed to retrieve Region Color"
@@ -282,7 +283,7 @@
     return base::nullopt;
   }
 
-  ClosedCaptionOpacity region_opacity = ClosedCaptionOpacity_Default;
+  CC::ClosedCaptionOpacity region_opacity = CC::ClosedCaptionOpacity_Default;
   hr = closed_caption_properties_statics->get_RegionOpacity(&region_opacity);
   if (FAILED(hr)) {
     DLOG(ERROR) << "Failed to retrieve Region Opacity"
@@ -292,32 +293,32 @@
   }
 
   CaptionStyle caption_style;
-  if (font_family != ClosedCaptionStyle_Default) {
+  if (font_family != CC::ClosedCaptionStyle_Default) {
     GetFontFamilyString(font_family, &(caption_style.font_family),
                         &(caption_style.font_variant));
     caption_style.font_family = AddCSSImportant(caption_style.font_family);
     caption_style.font_variant = AddCSSImportant(caption_style.font_variant);
   }
 
-  if (font_size != ClosedCaptionSize_Default)
+  if (font_size != CC::ClosedCaptionSize_Default)
     caption_style.text_size = AddCSSImportant(GetCaptionSizeString(font_size));
 
-  if (edge_effect != ClosedCaptionEdgeEffect_Default) {
+  if (edge_effect != CC::ClosedCaptionEdgeEffect_Default) {
     caption_style.text_shadow =
         AddCSSImportant(GetEdgeEffectString(edge_effect));
   }
 
-  if (font_color != ClosedCaptionColor_Default) {
+  if (font_color != CC::ClosedCaptionColor_Default) {
     caption_style.text_color =
         AddCSSImportant(GetCssColorWithAlpha(font_color, font_opacity));
   }
 
-  if (background_color != ClosedCaptionColor_Default) {
+  if (background_color != CC::ClosedCaptionColor_Default) {
     caption_style.background_color = AddCSSImportant(
         GetCssColorWithAlpha(background_color, background_opacity));
   }
 
-  if (region_color != ClosedCaptionColor_Default) {
+  if (region_color != CC::ClosedCaptionColor_Default) {
     caption_style.window_color =
         AddCSSImportant(GetCssColorWithAlpha(region_color, region_opacity));
   }
diff --git a/ui/ozone/platform/scenic/scenic_surface_factory.cc b/ui/ozone/platform/scenic/scenic_surface_factory.cc
index e5c8c89..ac4aebc 100644
--- a/ui/ozone/platform/scenic/scenic_surface_factory.cc
+++ b/ui/ozone/platform/scenic/scenic_surface_factory.cc
@@ -4,12 +4,13 @@
 
 #include "ui/ozone/platform/scenic/scenic_surface_factory.h"
 
+#include <lib/sys/cpp/component_context.h>
 #include <lib/zx/event.h>
 #include <memory>
 
 #include "base/bind.h"
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 #include "base/macros.h"
 #include "base/memory/ptr_util.h"
 #include "ui/gfx/native_pixmap.h"
@@ -64,14 +65,19 @@
   DISALLOW_COPY_AND_ASSIGN(GLOzoneEGLScenic);
 };
 
+fuchsia::sysmem::AllocatorSyncPtr ConnectSysmemAllocator() {
+  fuchsia::sysmem::AllocatorSyncPtr allocator;
+  base::fuchsia::ComponentContextForCurrentProcess()->svc()->Connect(
+      allocator.NewRequest());
+  return allocator;
+}
+
 }  // namespace
 
 ScenicSurfaceFactory::ScenicSurfaceFactory(mojom::ScenicGpuHost* gpu_host)
     : gpu_host_(gpu_host),
       egl_implementation_(std::make_unique<GLOzoneEGLScenic>()),
-      sysmem_buffer_manager_(
-          base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-              ->ConnectToServiceSync<fuchsia::sysmem::Allocator>()),
+      sysmem_buffer_manager_(ConnectSysmemAllocator()),
       weak_ptr_factory_(this) {
   // TODO(spang, crbug.com/923445): Add message loop to GPU tests.
   if (base::ThreadTaskRunnerHandle::IsSet())
@@ -213,8 +219,9 @@
     fidl::InterfaceHandle<fuchsia::ui::scenic::SessionListener> listener) {
   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
   if (!scenic_) {
-    scenic_ = base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-                  ->ConnectToService<fuchsia::ui::scenic::Scenic>();
+    scenic_ = base::fuchsia::ComponentContextForCurrentProcess()
+                  ->svc()
+                  ->Connect<fuchsia::ui::scenic::Scenic>();
     scenic_.set_error_handler([](zx_status_t status) {
       ZX_LOG(FATAL, status) << "Scenic connection failed";
     });
diff --git a/ui/ozone/platform/scenic/scenic_window_manager.cc b/ui/ozone/platform/scenic/scenic_window_manager.cc
index da55cee..8c43500 100644
--- a/ui/ozone/platform/scenic/scenic_window_manager.cc
+++ b/ui/ozone/platform/scenic/scenic_window_manager.cc
@@ -4,10 +4,11 @@
 
 #include "ui/ozone/platform/scenic/scenic_window_manager.h"
 
+#include <lib/sys/cpp/component_context.h>
 #include <memory>
 
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 #include "ui/ozone/platform/scenic/ozone_platform_scenic.h"
 
 namespace ui {
@@ -24,8 +25,9 @@
 
 fuchsia::ui::scenic::Scenic* ScenicWindowManager::GetScenic() {
   if (!scenic_) {
-    scenic_ = base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-                  ->ConnectToService<fuchsia::ui::scenic::Scenic>();
+    scenic_ = base::fuchsia::ComponentContextForCurrentProcess()
+                  ->svc()
+                  ->Connect<fuchsia::ui::scenic::Scenic>();
     scenic_.set_error_handler(
         [](zx_status_t status) { ZX_LOG(FATAL, status) << " Scenic lost."; });
   }
diff --git a/ui/platform_window/BUILD.gn b/ui/platform_window/BUILD.gn
index 37a3b3a..8330427 100644
--- a/ui/platform_window/BUILD.gn
+++ b/ui/platform_window/BUILD.gn
@@ -29,6 +29,7 @@
 
     public_deps = [
       "//third_party/fuchsia-sdk/sdk:scenic_cpp",
+      "//third_party/fuchsia-sdk/sdk:sys_cpp",
       "//third_party/fuchsia-sdk/sdk:ui_policy",
       "//third_party/fuchsia-sdk/sdk:ui_views",
     ]
diff --git a/ui/platform_window/fuchsia/initialize_presenter_api_view.cc b/ui/platform_window/fuchsia/initialize_presenter_api_view.cc
index 4397182..292c4ae 100644
--- a/ui/platform_window/fuchsia/initialize_presenter_api_view.cc
+++ b/ui/platform_window/fuchsia/initialize_presenter_api_view.cc
@@ -6,11 +6,12 @@
 
 #include <fuchsia/ui/policy/cpp/fidl.h>
 #include <fuchsia/ui/views/cpp/fidl.h>
+#include <lib/sys/cpp/component_context.h>
 #include <lib/ui/scenic/cpp/view_ref_pair.h>
 #include <lib/ui/scenic/cpp/view_token_pair.h>
 
+#include "base/fuchsia/default_context.h"
 #include "base/fuchsia/fuchsia_logging.h"
-#include "base/fuchsia/service_directory_client.h"
 
 namespace ui {
 namespace fuchsia {
@@ -28,8 +29,9 @@
   window_properties_out->view_ref_pair = scenic::ViewRefPair::New();
 
   // Request Presenter to show the view full-screen.
-  auto presenter = base::fuchsia::ServiceDirectoryClient::ForCurrentProcess()
-                       ->ConnectToService<::fuchsia::ui::policy::Presenter>();
+  auto presenter = base::fuchsia::ComponentContextForCurrentProcess()
+                       ->svc()
+                       ->Connect<::fuchsia::ui::policy::Presenter>();
 
   presenter->PresentView(std::move(view_holder_token), nullptr);
 }
diff --git a/ui/views/border_unittest.cc b/ui/views/border_unittest.cc
index 3a79f56..5439d485c 100644
--- a/ui/views/border_unittest.cc
+++ b/ui/views/border_unittest.cc
@@ -23,8 +23,6 @@
 #include "ui/views/test/views_test_base.h"
 #include "ui/views/view.h"
 
-using namespace testing;
-
 namespace {
 
 class MockCanvas : public SkCanvas {
diff --git a/weblayer/BUILD.gn b/weblayer/BUILD.gn
index 997aa5c..05f0d52 100644
--- a/weblayer/BUILD.gn
+++ b/weblayer/BUILD.gn
@@ -50,6 +50,12 @@
     "browser/navigation_impl.h",
     "browser/profile_impl.cc",
     "browser/profile_impl.h",
+    "browser/weblayer_content_browser_overlay_manifest.cc",
+    "browser/weblayer_content_browser_overlay_manifest.h",
+    "browser/webui/web_ui_controller_factory.cc",
+    "browser/webui/web_ui_controller_factory.h",
+    "browser/webui/weblayer_internals_ui.cc",
+    "browser/webui/weblayer_internals_ui.h",
     "common/content_client_impl.cc",
     "common/content_client_impl.h",
     "public/browser_controller.h",
@@ -102,8 +108,11 @@
     "//ui/gfx/ipc/skia",
     "//ui/gl",
     "//ui/platform_window",
+    "//ui/webui",
     "//url",
     "//v8",
+    "//weblayer:resources",
+    "//weblayer/browser/webui:mojo_bindings",
   ]
 
   if (enable_vulkan) {
@@ -165,6 +174,24 @@
   }
 }
 
+grit("resources") {
+  source = "weblayer_resources.grd"
+
+  source_is_generated = true
+
+  outputs = [
+    "grit/weblayer_resources.h",
+    "weblayer_resources.pak",
+  ]
+  grit_flags = [
+    "-E",
+    "root_gen_dir=" + rebase_path(root_gen_dir, root_build_dir),
+  ]
+  deps = [
+    "//weblayer/browser/webui:mojo_bindings_js",
+  ]
+}
+
 # TODO(jam): move weblayer_shell_resources_grit and copy_shell_resources here in
 # a way that's shareable?
 
diff --git a/weblayer/browser/DEPS b/weblayer/browser/DEPS
index b1f3a7f..6a65baa 100644
--- a/weblayer/browser/DEPS
+++ b/weblayer/browser/DEPS
@@ -2,6 +2,7 @@
   "+cc",
   "+components/embedder_support",
   "+content/public",
+  "+mojo/public",
   "+net",
   "+sandbox",
   "+services/service_manager",
@@ -12,5 +13,6 @@
   "+ui/events",
   "+ui/gfx",
   "+ui/views",
+  "+ui/webui",
   "+ui/wm",
 ]
diff --git a/weblayer/browser/OWNERS b/weblayer/browser/OWNERS
new file mode 100644
index 0000000..ddc16097
--- /dev/null
+++ b/weblayer/browser/OWNERS
@@ -0,0 +1,4 @@
+per-file weblayer_content_browser_overlay_manifest.cc=set noparent
+per-file weblayer_content_browser_overlay_manifest.cc=file://ipc/SECURITY_OWNERS
+per-file weblayer_content_browser_overlay_manifest.h=set noparent
+per-file weblayer_content_browser_overlay_manifest.h=file://ipc/SECURITY_OWNERS
diff --git a/weblayer/browser/browser_main_parts_impl.cc b/weblayer/browser/browser_main_parts_impl.cc
index c20c009..c3e0cb41 100644
--- a/weblayer/browser/browser_main_parts_impl.cc
+++ b/weblayer/browser/browser_main_parts_impl.cc
@@ -21,6 +21,7 @@
 #include "services/service_manager/embedder/result_codes.h"
 #include "ui/base/material_design/material_design_controller.h"
 #include "ui/base/resource/resource_bundle.h"
+#include "weblayer/browser/webui/web_ui_controller_factory.h"
 #include "weblayer/public/main.h"
 
 #if defined(OS_ANDROID)
@@ -84,6 +85,9 @@
   ui::MaterialDesignController::Initialize();
   params_->delegate->PreMainMessageLoopRun();
 
+  content::WebUIControllerFactory::RegisterFactory(
+      WebUIControllerFactory::GetInstance());
+
   if (main_function_params_.ui_task) {
     main_function_params_.ui_task->Run();
     delete main_function_params_.ui_task;
diff --git a/weblayer/browser/content_browser_client_impl.cc b/weblayer/browser/content_browser_client_impl.cc
index faa4e8a..5164e09 100644
--- a/weblayer/browser/content_browser_client_impl.cc
+++ b/weblayer/browser/content_browser_client_impl.cc
@@ -11,11 +11,14 @@
 #include "base/files/file_util.h"
 #include "base/stl_util.h"
 #include "build/build_config.h"
+#include "content/public/browser/devtools_manager_delegate.h"
+#include "content/public/common/service_names.mojom.h"
 #include "content/public/common/user_agent.h"
 #include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
 #include "url/gurl.h"
 #include "url/origin.h"
 #include "weblayer/browser/browser_main_parts_impl.h"
+#include "weblayer/browser/weblayer_content_browser_overlay_manifest.h"
 #include "weblayer/public/main.h"
 
 #if defined(OS_ANDROID)
@@ -59,6 +62,17 @@
     content::WebContents* web_contents) {
   return nullptr;
 }
+content::DevToolsManagerDelegate*
+ContentBrowserClientImpl::GetDevToolsManagerDelegate() {
+  return new content::DevToolsManagerDelegate();
+}
+
+base::Optional<service_manager::Manifest>
+ContentBrowserClientImpl::GetServiceManifestOverlay(base::StringPiece name) {
+  if (name == content::mojom::kBrowserServiceName)
+    return GetWebLayerContentBrowserOverlayManifest();
+  return base::nullopt;
+}
 
 std::string ContentBrowserClientImpl::GetUserAgent() {
   std::string product = "Chrome/";
diff --git a/weblayer/browser/content_browser_client_impl.h b/weblayer/browser/content_browser_client_impl.h
index b2dee373..43a58a63 100644
--- a/weblayer/browser/content_browser_client_impl.h
+++ b/weblayer/browser/content_browser_client_impl.h
@@ -30,6 +30,9 @@
   std::string GetAcceptLangs(content::BrowserContext* context) override;
   content::WebContentsViewDelegate* GetWebContentsViewDelegate(
       content::WebContents* web_contents) override;
+  content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override;
+  base::Optional<service_manager::Manifest> GetServiceManifestOverlay(
+      base::StringPiece name) override;
   std::string GetUserAgent() override;
   blink::UserAgentMetadata GetUserAgentMetadata() override;
 
diff --git a/weblayer/browser/java/BUILD.gn b/weblayer/browser/java/BUILD.gn
index 4cb52946..035dc83b 100644
--- a/weblayer/browser/java/BUILD.gn
+++ b/weblayer/browser/java/BUILD.gn
@@ -17,6 +17,7 @@
     "org/chromium/weblayer_private/ProfileImpl.java",
     "org/chromium/weblayer_private/TopControlsContainerView.java",
     "org/chromium/weblayer_private/WebLayerImpl.java",
+    "org/chromium/weblayer_private/ChildProcessServiceImpl.java",
   ]
 
   deps = [
@@ -55,6 +56,7 @@
   sources = [
     "org/chromium/weblayer_private/aidl/IBrowserController.aidl",
     "org/chromium/weblayer_private/aidl/IBrowserControllerClient.aidl",
+    "org/chromium/weblayer_private/aidl/IChildProcessService.aidl",
     "org/chromium/weblayer_private/aidl/IClientNavigation.aidl",
     "org/chromium/weblayer_private/aidl/INavigation.aidl",
     "org/chromium/weblayer_private/aidl/INavigationController.aidl",
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java
new file mode 100644
index 0000000..2a9f956
--- /dev/null
+++ b/weblayer/browser/java/org/chromium/weblayer_private/ChildProcessServiceImpl.java
@@ -0,0 +1,47 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.weblayer_private;
+
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.os.IBinder;
+
+import org.chromium.base.annotations.UsedByReflection;
+import org.chromium.base.process_launcher.ChildProcessService;
+import org.chromium.content_public.app.ChildProcessServiceFactory;
+import org.chromium.weblayer_private.aidl.IChildProcessService;
+import org.chromium.weblayer_private.aidl.IObjectWrapper;
+import org.chromium.weblayer_private.aidl.ObjectWrapper;
+
+@UsedByReflection("WebLayer")
+public final class ChildProcessServiceImpl extends IChildProcessService.Stub {
+    private ChildProcessService mService;
+
+    @UsedByReflection("WebLayer")
+    public static IBinder create(Service service, Context context) {
+        return new ChildProcessServiceImpl(service, context);
+    }
+
+    @Override
+    public void onCreate() {
+        mService.onCreate();
+    }
+
+    @Override
+    public void onDestroy() {
+        mService.onDestroy();
+        mService = null;
+    }
+
+    @Override
+    public IObjectWrapper onBind(IObjectWrapper intent) {
+        return ObjectWrapper.wrap(mService.onBind(ObjectWrapper.unwrap(intent, Intent.class)));
+    }
+
+    private ChildProcessServiceImpl(Service service, Context context) {
+        mService = ChildProcessServiceFactory.create(service, context);
+    }
+}
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java b/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java
index ec1e2e5b..fd7d6102 100644
--- a/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java
+++ b/weblayer/browser/java/org/chromium/weblayer_private/WebLayerImpl.java
@@ -52,9 +52,11 @@
         ResourceBundle.setNoAvailableLocalePaks();
         PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX);
 
-        ChildProcessCreationParams.set(implContext.getPackageName(), true /* isExternalService */,
+        ChildProcessCreationParams.set(application.getPackageName(), false /* isExternalService */,
                 LibraryProcessType.PROCESS_CHILD, true /* bindToCaller */,
-                false /* ignoreVisibilityForImportance */);
+                false /* ignoreVisibilityForImportance */,
+                "org.chromium.weblayer.ChildProcessService$Privileged",
+                "org.chromium.weblayer.ChildProcessService$Sandboxed");
 
         if (!CommandLine.isInitialized()) {
             CommandLine.initFromFile(COMMAND_LINE_FILE);
diff --git a/weblayer/browser/java/org/chromium/weblayer_private/aidl/IChildProcessService.aidl b/weblayer/browser/java/org/chromium/weblayer_private/aidl/IChildProcessService.aidl
new file mode 100644
index 0000000..e5f6ff23
--- /dev/null
+++ b/weblayer/browser/java/org/chromium/weblayer_private/aidl/IChildProcessService.aidl
@@ -0,0 +1,14 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.weblayer_private.aidl;
+
+/** Interface to forward service calls to the service implementation. */
+interface IChildProcessService {
+  void onCreate() = 0;
+
+  void onDestroy() = 1;
+
+  IObjectWrapper onBind(IObjectWrapper intent) = 2;
+}
diff --git a/weblayer/browser/resources/weblayer_internals/weblayer_internals.html b/weblayer/browser/resources/weblayer_internals/weblayer_internals.html
new file mode 100644
index 0000000..196be11
--- /dev/null
+++ b/weblayer/browser/resources/weblayer_internals/weblayer_internals.html
@@ -0,0 +1,24 @@
+<!doctype html>
+<html lang="en" dir="ltr">
+  <head>
+    <meta charset="utf-8">
+    <title>WebLayer Internals</title>
+    <link rel="stylesheet" href="chrome://resources/css/text_defaults.css">
+
+    <script src="chrome://resources/js/cr.js"></script>
+    <script src="chrome://resources/js/promise_resolver.js"></script>
+    <script src="chrome://resources/js/util.js"></script>
+    <script src="chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js"></script>
+    <script src="weblayer_internals.mojom-lite.js"></script>
+    <script src="weblayer_internals.js"></script>
+  </head>
+  <body>
+    <h1>WebLayer Internals</h1>
+    <div>
+      <label id="remote-debug-label" hidden>
+        <input type="checkbox" id="remote-debug">
+        Enable remote debugging
+      </label>
+    </div>
+  </body>
+</html>
diff --git a/weblayer/browser/resources/weblayer_internals/weblayer_internals.js b/weblayer/browser/resources/weblayer_internals/weblayer_internals.js
new file mode 100644
index 0000000..e742ba2
--- /dev/null
+++ b/weblayer/browser/resources/weblayer_internals/weblayer_internals.js
@@ -0,0 +1,27 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+'use strict';
+
+/* Javascript module for chrome://weblayer. */
+(function() {
+
+/* Main entry point. */
+document.addEventListener('DOMContentLoaded', function() {
+  // Setup backend mojo.
+  const pageHandler = weblayerInternals.mojom.PageHandler.getRemote();
+  if (cr.isAndroid) {
+    pageHandler.getRemoteDebuggingEnabled().then((response) => {
+        let checkbox = $('remote-debug');
+        checkbox.checked = response.enabled;
+        checkbox.addEventListener('click', (event) => {
+          pageHandler.setRemoteDebuggingEnabled(event.target.checked);
+        });
+
+        $('remote-debug-label').removeAttribute('hidden');
+    });
+  }
+});
+
+}());
diff --git a/weblayer/browser/weblayer_content_browser_overlay_manifest.cc b/weblayer/browser/weblayer_content_browser_overlay_manifest.cc
new file mode 100644
index 0000000..6b4fbc6
--- /dev/null
+++ b/weblayer/browser/weblayer_content_browser_overlay_manifest.cc
@@ -0,0 +1,24 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "weblayer/browser/weblayer_content_browser_overlay_manifest.h"
+
+#include "base/no_destructor.h"
+#include "services/service_manager/public/cpp/manifest_builder.h"
+#include "weblayer/browser/webui/weblayer_internals.mojom.h"
+
+namespace weblayer {
+
+const service_manager::Manifest& GetWebLayerContentBrowserOverlayManifest() {
+  static base::NoDestructor<service_manager::Manifest> manifest{
+      service_manager::ManifestBuilder()
+          .ExposeInterfaceFilterCapability_Deprecated(
+              "navigation:frame", "renderer",
+              service_manager::Manifest::InterfaceList<
+                  weblayer_internals::mojom::PageHandler>())
+          .Build()};
+  return *manifest;
+}
+
+}  // namespace weblayer
diff --git a/weblayer/browser/weblayer_content_browser_overlay_manifest.h b/weblayer/browser/weblayer_content_browser_overlay_manifest.h
new file mode 100644
index 0000000..e4ed366
--- /dev/null
+++ b/weblayer/browser/weblayer_content_browser_overlay_manifest.h
@@ -0,0 +1,20 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef WEBLAYER_BROWSER_WEBLAYER_CONTENT_BROWSER_OVERLAY_MANIFEST_H_
+#define WEBLAYER_BROWSER_WEBLAYER_CONTENT_BROWSER_OVERLAY_MANIFEST_H_
+
+#include "services/service_manager/public/cpp/manifest.h"
+
+namespace weblayer {
+
+// Returns the manifest WebLayer amends to Content's content_browser service
+// manifest. This allows WebLayer to extend the capabilities exposed and/or
+// required by content_browser service instances, as well as declaring any
+// additional in- and out-of-process per-profile packaged services.
+const service_manager::Manifest& GetWebLayerContentBrowserOverlayManifest();
+
+}  // namespace weblayer
+
+#endif  // WEBLAYER_BROWSER_WEBLAYER_CONTENT_BROWSER_OVERLAY_MANIFEST_H_
diff --git a/weblayer/browser/webui/BUILD.gn b/weblayer/browser/webui/BUILD.gn
new file mode 100644
index 0000000..71f297a
--- /dev/null
+++ b/weblayer/browser/webui/BUILD.gn
@@ -0,0 +1,11 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import("//mojo/public/tools/bindings/mojom.gni")
+
+mojom("mojo_bindings") {
+  sources = [
+    "weblayer_internals.mojom",
+  ]
+}
diff --git a/weblayer/browser/webui/OWNERS b/weblayer/browser/webui/OWNERS
new file mode 100644
index 0000000..08850f4
--- /dev/null
+++ b/weblayer/browser/webui/OWNERS
@@ -0,0 +1,2 @@
+per-file *.mojom=set noparent
+per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/weblayer/browser/webui/web_ui_controller_factory.cc b/weblayer/browser/webui/web_ui_controller_factory.cc
new file mode 100644
index 0000000..cc1aa55
--- /dev/null
+++ b/weblayer/browser/webui/web_ui_controller_factory.cc
@@ -0,0 +1,84 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "weblayer/browser/webui/web_ui_controller_factory.h"
+
+#include "base/memory/ptr_util.h"
+#include "content/public/browser/web_ui.h"
+#include "url/gurl.h"
+#include "weblayer/browser/webui/weblayer_internals_ui.h"
+
+namespace weblayer {
+namespace {
+
+const content::WebUI::TypeID kWebLayerID = &kWebLayerID;
+
+// A function for creating a new WebUI. The caller owns the return value, which
+// may be nullptr (for example, if the URL refers to an non-existent extension).
+typedef content::WebUIController* (
+    *WebUIFactoryFunctionPointer)(content::WebUI* web_ui, const GURL& url);
+
+// Template for defining WebUIFactoryFunctionPointer.
+template <class T>
+content::WebUIController* NewWebUI(content::WebUI* web_ui, const GURL& url) {
+  return new T(web_ui);
+}
+
+WebUIFactoryFunctionPointer GetWebUIFactoryFunctionPointer(const GURL& url) {
+  if (url.host() == kChromeUIWebLayerHost) {
+    return &NewWebUI<WebLayerInternalsUI>;
+  }
+
+  return nullptr;
+}
+
+content::WebUI::TypeID GetWebUITypeID(const GURL& url) {
+  if (url.host() == kChromeUIWebLayerHost) {
+    return kWebLayerID;
+  }
+
+  return content::WebUI::kNoWebUI;
+}
+
+}  // namespace
+
+// static
+WebUIControllerFactory* WebUIControllerFactory::GetInstance() {
+  static base::NoDestructor<WebUIControllerFactory> instance;
+  return instance.get();
+}
+
+WebUIControllerFactory::WebUIControllerFactory() {}
+
+WebUIControllerFactory::~WebUIControllerFactory() {}
+
+content::WebUI::TypeID WebUIControllerFactory::GetWebUIType(
+    content::BrowserContext* browser_context,
+    const GURL& url) {
+  return GetWebUITypeID(url);
+}
+
+bool WebUIControllerFactory::UseWebUIForURL(
+    content::BrowserContext* browser_context,
+    const GURL& url) {
+  return GetWebUIType(browser_context, url) != content::WebUI::kNoWebUI;
+}
+
+bool WebUIControllerFactory::UseWebUIBindingsForURL(
+    content::BrowserContext* browser_context,
+    const GURL& url) {
+  return UseWebUIForURL(browser_context, url);
+}
+
+std::unique_ptr<content::WebUIController>
+WebUIControllerFactory::CreateWebUIControllerForURL(content::WebUI* web_ui,
+                                                    const GURL& url) {
+  WebUIFactoryFunctionPointer function = GetWebUIFactoryFunctionPointer(url);
+  if (!function)
+    return nullptr;
+
+  return base::WrapUnique((*function)(web_ui, url));
+}
+
+}  // namespace weblayer
diff --git a/weblayer/browser/webui/web_ui_controller_factory.h b/weblayer/browser/webui/web_ui_controller_factory.h
new file mode 100644
index 0000000..ba01680
--- /dev/null
+++ b/weblayer/browser/webui/web_ui_controller_factory.h
@@ -0,0 +1,40 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef WEBLAYER_BROWSER_WEBUI_WEB_UI_CONTROLLER_FACTORY_H_
+#define WEBLAYER_BROWSER_WEBUI_WEB_UI_CONTROLLER_FACTORY_H_
+
+#include "base/macros.h"
+#include "base/no_destructor.h"
+#include "content/public/browser/web_ui_controller_factory.h"
+
+namespace weblayer {
+
+class WebUIControllerFactory : public content::WebUIControllerFactory {
+ public:
+  static WebUIControllerFactory* GetInstance();
+
+  // content::WebUIControllerFactory overrides
+  content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context,
+                                      const GURL& url) override;
+  bool UseWebUIForURL(content::BrowserContext* browser_context,
+                      const GURL& url) override;
+  bool UseWebUIBindingsForURL(content::BrowserContext* browser_context,
+                              const GURL& url) override;
+  std::unique_ptr<content::WebUIController> CreateWebUIControllerForURL(
+      content::WebUI* web_ui,
+      const GURL& url) override;
+
+ private:
+  friend base::NoDestructor<WebUIControllerFactory>;
+
+  WebUIControllerFactory();
+  ~WebUIControllerFactory() override;
+
+  DISALLOW_COPY_AND_ASSIGN(WebUIControllerFactory);
+};
+
+}  // namespace weblayer
+
+#endif  // WEBLAYER_BROWSER_WEBUI_WEB_UI_CONTROLLER_FACTORY_H_
diff --git a/weblayer/browser/webui/weblayer_internals.mojom b/weblayer/browser/webui/weblayer_internals.mojom
new file mode 100644
index 0000000..71b83cb
--- /dev/null
+++ b/weblayer/browser/webui/weblayer_internals.mojom
@@ -0,0 +1,16 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module weblayer_internals.mojom;
+
+// Browser interface.
+interface PageHandler {
+  // Gets whether remote debugging is currently enabled.
+  [EnableIf=is_android]
+  GetRemoteDebuggingEnabled() => (bool enabled);
+
+  // Enables or disables remote debugging.
+  [EnableIf=is_android]
+  SetRemoteDebuggingEnabled(bool enabled);
+};
diff --git a/weblayer/browser/webui/weblayer_internals_ui.cc b/weblayer/browser/webui/weblayer_internals_ui.cc
new file mode 100644
index 0000000..f7476c11
--- /dev/null
+++ b/weblayer/browser/webui/weblayer_internals_ui.cc
@@ -0,0 +1,118 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "weblayer/browser/webui/weblayer_internals_ui.h"
+
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_ui_data_source.h"
+#include "weblayer/grit/weblayer_resources.h"
+
+#if defined(OS_ANDROID)
+#include "content/public/browser/android/devtools_auth.h"
+#include "content/public/browser/devtools_manager_delegate.h"
+#include "content/public/browser/devtools_socket_factory.h"
+#include "net/socket/unix_domain_server_socket_posix.h"
+#endif
+
+namespace weblayer {
+namespace {
+
+#if defined(OS_ANDROID)
+bool g_remote_debugging_enabled = false;
+
+const char kSocketNameFormat[] = "weblayer_devtools_remote_%d";
+const char kTetheringSocketName[] = "weblayer_devtools_tethering_%d_%d";
+
+const int kBackLog = 10;
+
+// Factory for UnixDomainServerSocket.
+class UnixDomainServerSocketFactory : public content::DevToolsSocketFactory {
+ public:
+  explicit UnixDomainServerSocketFactory(const std::string& socket_name)
+      : socket_name_(socket_name) {}
+
+ private:
+  // content::DevToolsAgentHost::ServerSocketFactory.
+  std::unique_ptr<net::ServerSocket> CreateForHttpServer() override {
+    auto socket = std::make_unique<net::UnixDomainServerSocket>(
+        base::BindRepeating(&content::CanUserConnectToDevTools),
+        true /* use_abstract_namespace */);
+    if (socket->BindAndListen(socket_name_, kBackLog) != net::OK)
+      return nullptr;
+
+    return std::move(socket);
+  }
+
+  std::unique_ptr<net::ServerSocket> CreateForTethering(
+      std::string* name) override {
+    *name = base::StringPrintf(kTetheringSocketName, getpid(),
+                               ++last_tethering_socket_);
+    auto socket = std::make_unique<net::UnixDomainServerSocket>(
+        base::BindRepeating(&content::CanUserConnectToDevTools),
+        true /* use_abstract_namespace */);
+    if (socket->BindAndListen(*name, kBackLog) != net::OK)
+      return nullptr;
+
+    return std::move(socket);
+  }
+
+  std::string socket_name_;
+  int last_tethering_socket_ = 0;
+
+  DISALLOW_COPY_AND_ASSIGN(UnixDomainServerSocketFactory);
+};
+#endif
+
+}  // namespace
+
+const char kChromeUIWebLayerHost[] = "weblayer";
+
+WebLayerInternalsUI::WebLayerInternalsUI(content::WebUI* web_ui)
+    : ui::MojoWebUIController(web_ui) {
+  content::WebUIDataSource* source =
+      content::WebUIDataSource::Create(kChromeUIWebLayerHost);
+  source->AddResourcePath("weblayer_internals.js", IDR_WEBLAYER_INTERNALS_JS);
+  source->AddResourcePath("weblayer_internals.mojom-lite.js",
+                          IDR_WEBLAYER_INTERNALS_MOJO_JS);
+  source->SetDefaultResource(IDR_WEBLAYER_INTERNALS_HTML);
+  content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
+                                source);
+  AddHandlerToRegistry(base::BindRepeating(
+      &WebLayerInternalsUI::BindPageHandler, base::Unretained(this)));
+}
+
+WebLayerInternalsUI::~WebLayerInternalsUI() {}
+
+#if defined(OS_ANDROID)
+void WebLayerInternalsUI::GetRemoteDebuggingEnabled(
+    GetRemoteDebuggingEnabledCallback callback) {
+  std::move(callback).Run(g_remote_debugging_enabled);
+}
+
+void WebLayerInternalsUI::SetRemoteDebuggingEnabled(bool enabled) {
+  if (g_remote_debugging_enabled == enabled)
+    return;
+
+  g_remote_debugging_enabled = enabled;
+  if (enabled) {
+    auto factory = std::make_unique<UnixDomainServerSocketFactory>(
+        base::StringPrintf(kSocketNameFormat, getpid()));
+    content::DevToolsAgentHost::StartRemoteDebuggingServer(
+        std::move(factory), base::FilePath(), base::FilePath());
+  } else {
+    content::DevToolsAgentHost::StopRemoteDebuggingServer();
+  }
+}
+#endif
+
+void WebLayerInternalsUI::BindPageHandler(
+    mojo::PendingReceiver<weblayer_internals::mojom::PageHandler>
+        pending_receiver) {
+  if (receiver_.is_bound())
+    receiver_.reset();
+
+  receiver_.Bind(std::move(pending_receiver));
+}
+
+}  // namespace weblayer
diff --git a/weblayer/browser/webui/weblayer_internals_ui.h b/weblayer/browser/webui/weblayer_internals_ui.h
new file mode 100644
index 0000000..9cf7011
--- /dev/null
+++ b/weblayer/browser/webui/weblayer_internals_ui.h
@@ -0,0 +1,43 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef WEBLAYER_BROWSER_WEBUI_WEBLAYER_INTERNALS_UI_H_
+#define WEBLAYER_BROWSER_WEBUI_WEBLAYER_INTERNALS_UI_H_
+
+#include "build/build_config.h"
+#include "mojo/public/cpp/bindings/receiver.h"
+#include "ui/webui/mojo_web_ui_controller.h"
+#include "weblayer/browser/webui/weblayer_internals.mojom.h"
+
+namespace weblayer {
+
+extern const char kChromeUIWebLayerHost[];
+
+class WebLayerInternalsUI : public ui::MojoWebUIController,
+                            public weblayer_internals::mojom::PageHandler {
+ public:
+  explicit WebLayerInternalsUI(content::WebUI* web_ui);
+
+  ~WebLayerInternalsUI() override;
+
+ private:
+  // weblayer_internals::mojom::PageHandler:
+#if defined(OS_ANDROID)
+  void GetRemoteDebuggingEnabled(
+      GetRemoteDebuggingEnabledCallback callback) override;
+  void SetRemoteDebuggingEnabled(bool enabled) override;
+#endif
+
+  void BindPageHandler(
+      mojo::PendingReceiver<weblayer_internals::mojom::PageHandler>
+          pending_receiver);
+
+  mojo::Receiver<weblayer_internals::mojom::PageHandler> receiver_{this};
+
+  DISALLOW_COPY_AND_ASSIGN(WebLayerInternalsUI);
+};
+
+}  // namespace weblayer
+
+#endif  // WEBLAYER_BROWSER_WEBUI_WEBLAYER_INTERNALS_UI_H_
diff --git a/weblayer/public/java/BUILD.gn b/weblayer/public/java/BUILD.gn
index 0a4b80c..31640f61 100644
--- a/weblayer/public/java/BUILD.gn
+++ b/weblayer/public/java/BUILD.gn
@@ -16,6 +16,7 @@
     "org/chromium/weblayer/ObserverList.java",
     "org/chromium/weblayer/Profile.java",
     "org/chromium/weblayer/WebLayer.java",
+    "org/chromium/weblayer/ChildProcessService.java",
   ]
 
   deps = [
diff --git a/weblayer/public/java/org/chromium/weblayer/ChildProcessService.java b/weblayer/public/java/org/chromium/weblayer/ChildProcessService.java
new file mode 100644
index 0000000..9514db7
--- /dev/null
+++ b/weblayer/public/java/org/chromium/weblayer/ChildProcessService.java
@@ -0,0 +1,128 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package org.chromium.weblayer;
+
+import android.app.Service;
+import android.content.ComponentCallbacks;
+import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
+import android.os.IBinder;
+import android.os.RemoteException;
+
+import org.chromium.weblayer_private.aidl.APICallException;
+import org.chromium.weblayer_private.aidl.IChildProcessService;
+import org.chromium.weblayer_private.aidl.ObjectWrapper;
+
+/**
+ * Delegates service calls to the chrome service implementation.
+ */
+public abstract class ChildProcessService extends Service {
+    private IChildProcessService mImpl;
+
+    public ChildProcessService() {}
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+        try {
+            Context remoteContext = WebLayer.createRemoteContext(getApplication());
+            mImpl = IChildProcessService.Stub.asInterface(
+                    (IBinder) remoteContext.getClassLoader()
+                            .loadClass("org.chromium.weblayer_private.ChildProcessServiceImpl")
+                            .getMethod("create", Service.class, Context.class)
+                            .invoke(null, this, new ContextWrapper(remoteContext) {
+                                @Override
+                                public Context getApplicationContext() {
+                                    return remoteContext;
+                                }
+
+                                @Override
+                                public void registerComponentCallbacks(
+                                        ComponentCallbacks callback) {
+                                    getApplication().registerComponentCallbacks(callback);
+                                }
+
+                                @Override
+                                public void unregisterComponentCallbacks(
+                                        ComponentCallbacks callback) {
+                                    getApplication().unregisterComponentCallbacks(callback);
+                                }
+                            }));
+            mImpl.onCreate();
+        } catch (Exception e) {
+            throw new APICallException(e);
+        }
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        try {
+            mImpl.onDestroy();
+            mImpl = null;
+        } catch (RemoteException e) {
+            throw new APICallException(e);
+        }
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        try {
+            return ObjectWrapper.unwrap(mImpl.onBind(ObjectWrapper.wrap(intent)), IBinder.class);
+        } catch (RemoteException e) {
+            throw new APICallException(e);
+        }
+    }
+
+    public static class Privileged extends ChildProcessService {}
+    public static final class Privileged0 extends Privileged {}
+    public static final class Privileged1 extends Privileged {}
+    public static final class Privileged2 extends Privileged {}
+    public static final class Privileged3 extends Privileged {}
+    public static final class Privileged4 extends Privileged {}
+
+    public static class Sandboxed extends ChildProcessService {}
+    public static final class Sandboxed0 extends Sandboxed {}
+    public static final class Sandboxed1 extends Sandboxed {}
+    public static final class Sandboxed2 extends Sandboxed {}
+    public static final class Sandboxed3 extends Sandboxed {}
+    public static final class Sandboxed4 extends Sandboxed {}
+    public static final class Sandboxed5 extends Sandboxed {}
+    public static final class Sandboxed6 extends Sandboxed {}
+    public static final class Sandboxed7 extends Sandboxed {}
+    public static final class Sandboxed8 extends Sandboxed {}
+    public static final class Sandboxed9 extends Sandboxed {}
+    public static final class Sandboxed10 extends Sandboxed {}
+    public static final class Sandboxed11 extends Sandboxed {}
+    public static final class Sandboxed12 extends Sandboxed {}
+    public static final class Sandboxed13 extends Sandboxed {}
+    public static final class Sandboxed14 extends Sandboxed {}
+    public static final class Sandboxed15 extends Sandboxed {}
+    public static final class Sandboxed16 extends Sandboxed {}
+    public static final class Sandboxed17 extends Sandboxed {}
+    public static final class Sandboxed18 extends Sandboxed {}
+    public static final class Sandboxed19 extends Sandboxed {}
+    public static final class Sandboxed20 extends Sandboxed {}
+    public static final class Sandboxed21 extends Sandboxed {}
+    public static final class Sandboxed22 extends Sandboxed {}
+    public static final class Sandboxed23 extends Sandboxed {}
+    public static final class Sandboxed24 extends Sandboxed {}
+    public static final class Sandboxed25 extends Sandboxed {}
+    public static final class Sandboxed26 extends Sandboxed {}
+    public static final class Sandboxed27 extends Sandboxed {}
+    public static final class Sandboxed28 extends Sandboxed {}
+    public static final class Sandboxed29 extends Sandboxed {}
+    public static final class Sandboxed30 extends Sandboxed {}
+    public static final class Sandboxed31 extends Sandboxed {}
+    public static final class Sandboxed32 extends Sandboxed {}
+    public static final class Sandboxed33 extends Sandboxed {}
+    public static final class Sandboxed34 extends Sandboxed {}
+    public static final class Sandboxed35 extends Sandboxed {}
+    public static final class Sandboxed36 extends Sandboxed {}
+    public static final class Sandboxed37 extends Sandboxed {}
+    public static final class Sandboxed38 extends Sandboxed {}
+    public static final class Sandboxed39 extends Sandboxed {}
+}
diff --git a/weblayer/public/java/org/chromium/weblayer/Profile.java b/weblayer/public/java/org/chromium/weblayer/Profile.java
index 5702c4b..a64d52e 100644
--- a/weblayer/public/java/org/chromium/weblayer/Profile.java
+++ b/weblayer/public/java/org/chromium/weblayer/Profile.java
@@ -47,7 +47,7 @@
         try {
             return new BrowserFragmentImpl(
                     mImpl.createBrowserController(ObjectWrapper.wrap(context),
-                            ObjectWrapper.wrap(WebLayer.getInstance().createRemoteContext())));
+                            ObjectWrapper.wrap(WebLayer.createRemoteContext(context))));
         } catch (RemoteException e) {
             throw new APICallException(e);
         }
diff --git a/weblayer/public/java/org/chromium/weblayer/WebLayer.java b/weblayer/public/java/org/chromium/weblayer/WebLayer.java
index f7fbc98..8a20e2f8 100644
--- a/weblayer/public/java/org/chromium/weblayer/WebLayer.java
+++ b/weblayer/public/java/org/chromium/weblayer/WebLayer.java
@@ -31,8 +31,6 @@
     private static WebLayer sInstance;
     private IWebLayer mImpl;
 
-    private Application mApplication;
-
     public static WebLayer getInstance() {
         if (sInstance == null) {
             sInstance = new WebLayer();
@@ -43,7 +41,6 @@
     WebLayer() {}
 
     public void init(Application application) {
-        mApplication = application;
         try {
             // TODO: Make asset loading work on L, where WebViewDelegate doesn't exist.
             // WebViewDelegate.addWebViewAssetPath() accesses the currently loaded package info from
@@ -61,7 +58,7 @@
             WebViewDelegate delegate = (WebViewDelegate) constructor.newInstance();
             delegate.addWebViewAssetPath(application);
 
-            Context remoteContext = createRemoteContext();
+            Context remoteContext = createRemoteContext(application);
             mImpl = IWebLayer.Stub.asInterface(
                     (IBinder) remoteContext.getClassLoader()
                             .loadClass("org.chromium.weblayer_private.WebLayerImpl")
@@ -96,9 +93,11 @@
     /**
      * Creates a Context for the remote (weblayer implementation) side.
      */
-    Context createRemoteContext() {
+    static Context createRemoteContext(Context localContext) {
         try {
-            return mApplication.createPackageContext(
+            // TODO(cduvall): Might want to cache the remote context so we don't need to call into
+            // package manager more than we need to.
+            return localContext.createPackageContext(
                     PACKAGE_NAME, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
         } catch (NameNotFoundException e) {
             throw new AndroidRuntimeException(e);
diff --git a/weblayer/shell/BUILD.gn b/weblayer/shell/BUILD.gn
index e8cb4942..ad6f90de 100644
--- a/weblayer/shell/BUILD.gn
+++ b/weblayer/shell/BUILD.gn
@@ -70,6 +70,7 @@
     "//ui/platform_window",
     "//url",
     "//v8",
+    "//weblayer:resources",
   ]
 
   if (is_linux) {
@@ -182,6 +183,7 @@
     "$root_gen_dir/ui/resources/webui_resources.pak",
     "$root_gen_dir/ui/strings/app_locale_settings_en-US.pak",
     "$root_gen_dir/ui/strings/ui_strings_en-US.pak",
+    "$root_gen_dir/weblayer/weblayer_resources.pak",
   ]
 
   deps = [
@@ -195,6 +197,7 @@
     "//third_party/blink/public/strings",
     "//ui/resources",
     "//ui/strings",
+    "//weblayer:resources",
   ]
 
   if (toolkit_views) {
diff --git a/weblayer/shell/android/shell_apk/AndroidManifest.xml b/weblayer/shell/android/shell_apk/AndroidManifest.xml
index 61565f96..b97bece9 100644
--- a/weblayer/shell/android/shell_apk/AndroidManifest.xml
+++ b/weblayer/shell/android/shell_apk/AndroidManifest.xml
@@ -30,5 +30,29 @@
                 <category android:name="android.intent.category.LAUNCHER"/>
             </intent-filter>
         </activity>
+        <!-- The following service entries exist in order to allow us to
+             start more than one sandboxed process. -->
+
+        <!-- NOTE: If you change the values of "android:process" for any of the below services,
+             you also need to update kHelperProcessExecutableName in chrome_constants.cc. -->
+        {% set num_sandboxed_services = 40 %}
+        <meta-data android:name="org.chromium.content.browser.NUM_SANDBOXED_SERVICES"
+                   android:value="{{ num_sandboxed_services }}"/>
+        {% for i in range(num_sandboxed_services) %}
+        <service android:name="org.chromium.weblayer.ChildProcessService$Sandboxed{{ i }}"
+                 android:process=":sandboxed_process{{ i }}"
+                 android:isolatedProcess="true"
+                 android:exported="false" />
+        {% endfor %}
+
+        {% set num_privileged_services = 5 %}
+        <meta-data android:name="org.chromium.content.browser.NUM_PRIVILEGED_SERVICES"
+                   android:value="{{ num_privileged_services }}"/>
+        {% for i in range(num_privileged_services) %}
+        <service android:name="org.chromium.weblayer.ChildProcessService$Privileged{{ i }}"
+                 android:process=":privileged_process{{ i }}"
+                 android:isolatedProcess="false"
+                 android:exported="false" />
+        {% endfor %}
     </application>
 </manifest>
diff --git a/weblayer/shell/android/support_apk/AndroidManifest.xml b/weblayer/shell/android/support_apk/AndroidManifest.xml
index 025cc3d..55fca00 100644
--- a/weblayer/shell/android/support_apk/AndroidManifest.xml
+++ b/weblayer/shell/android/support_apk/AndroidManifest.xml
@@ -18,32 +18,4 @@
     <uses-permission android:name="android.permission.VIBRATE"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-
-    <application android:label="WebLayer support">
-        <!-- The following service entries exist in order to allow us to
-             start more than one sandboxed process. -->
-
-        <!-- NOTE: If you change the values of "android:process" for any of the below services,
-             you also need to update kHelperProcessExecutableName in chrome_constants.cc. -->
-        {% set num_sandboxed_services = 40 %}
-        <meta-data android:name="org.chromium.content.browser.NUM_SANDBOXED_SERVICES"
-                   android:value="{{ num_sandboxed_services }}"/>
-        {% for i in range(num_sandboxed_services) %}
-        <service android:name="org.chromium.content.app.SandboxedProcessService{{ i }}"
-                 android:process=":sandboxed_process{{ i }}"
-                 android:isolatedProcess="true"
-                 android:externalService="true"
-                 android:exported="true" />
-        {% endfor %}
-
-        {% set num_privileged_services = 5 %}
-        <meta-data android:name="org.chromium.content.browser.NUM_PRIVILEGED_SERVICES"
-                   android:value="{{ num_privileged_services }}"/>
-        {% for i in range(num_privileged_services) %}
-        <service android:name="org.chromium.content.app.PrivilegedProcessService{{ i }}"
-                 android:process=":privileged_process{{ i }}"
-                 android:isolatedProcess="false"
-                 android:exported="true" />
-        {% endfor %}
-    </application>
 </manifest>
diff --git a/weblayer/weblayer_resources.grd b/weblayer/weblayer_resources.grd
new file mode 100644
index 0000000..1dd5006
--- /dev/null
+++ b/weblayer/weblayer_resources.grd
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<grit latest_public_release="0" current_release="1" output_all_resource_defines="false">
+  <outputs>
+    <output filename="grit/weblayer_resources.h" type="rc_header">
+      <emit emit_type='prepend'></emit>
+    </output>
+    <output filename="weblayer_resources.pak" type="data_package" />
+  </outputs>
+  <translations />
+  <release seq="1">
+    <includes>
+      <include name="IDR_WEBLAYER_INTERNALS_HTML" file="browser/resources/weblayer_internals/weblayer_internals.html" flattenhtml="true" allowexternalscript="true" compress="gzip" type="BINDATA" />
+      <include name="IDR_WEBLAYER_INTERNALS_JS" file="browser/resources/weblayer_internals/weblayer_internals.js" flattenhtml="true" compress="gzip" type="BINDATA" />
+      <include name="IDR_WEBLAYER_INTERNALS_MOJO_JS" file="${root_gen_dir}/weblayer/browser/webui/weblayer_internals.mojom-lite.js" use_base_dir="false" type="BINDATA" compress="gzip" />
+    </includes>
+  </release>
+</grit>