diff --git a/DEPS b/DEPS
index 14bfdab..a8e176c 100644
--- a/DEPS
+++ b/DEPS
@@ -96,7 +96,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': 'be072d088a44c58e422f7a640631bf8749484f56',
+  'catapult_revision': '3e38417eedda889b4aa978a777b29de401f85b74',
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling libFuzzer
   # and whatever else without interference from each other.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java b/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java
index ce221b55..90d94411 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/banners/AppBannerManager.java
@@ -156,8 +156,8 @@
 
     /** Returns whether the native AppBannerManager is working. */
     @VisibleForTesting
-    public boolean isActiveForTesting() {
-        return nativeIsActiveForTesting(mNativePointer);
+    public boolean isRunningForTesting() {
+        return nativeIsRunningForTesting(mNativePointer);
     }
 
     /** Signal to native that the add to homescreen menu item was tapped for metrics purposes. */
@@ -202,7 +202,7 @@
             AppData data, String title, String packageName, String imageUrl);
 
     // Testing methods.
-    private native boolean nativeIsActiveForTesting(long nativeAppBannerManagerAndroid);
+    private native boolean nativeIsRunningForTesting(long nativeAppBannerManagerAndroid);
     private static native void nativeSetDaysAfterDismissAndIgnoreToTrigger(
             int dismissDays, int ignoreDays);
     private static native void nativeSetTimeDeltaForTesting(int days);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/SectionList.java b/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/SectionList.java
index ccd6938..a0a9e3e0 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/SectionList.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/SectionList.java
@@ -317,22 +317,22 @@
     }
 
     /**
-     * Records the currently visible suggestion state: how many categories are visible and how many
+     * Records the currently visible suggestion state: which categories are visible and how many
      * suggestions per category.
      * @see org.chromium.chrome.browser.suggestions.SuggestionsEventReporter#onPageShown
      */
     private void recordDisplayedSuggestions(int[] categories) {
         int[] suggestionsPerCategory = new int[categories.length];
-        int visibleCategoriesCount = 0;
+        boolean[] isCategoryVisible = new boolean[categories.length];
 
         for (int i = 0; i < categories.length; ++i) {
             SuggestionsSection section = mSections.get(categories[i]);
-            suggestionsPerCategory[i] = section == null ? 0 : section.getSuggestionsCount();
-            visibleCategoriesCount += section == null ? 0 : 1;
+            suggestionsPerCategory[i] = section != null ? section.getSuggestionsCount() : 0;
+            isCategoryVisible[i] = section != null;
         }
 
         mUiDelegate.getEventReporter().onPageShown(
-                categories, suggestionsPerCategory, visibleCategoriesCount);
+                categories, suggestionsPerCategory, isCategoryVisible);
     }
 
     SuggestionsSection getSectionForTesting(@CategoryInt int categoryId) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporter.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporter.java
index 36d00b9f..ac9cf2f 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporter.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporter.java
@@ -22,9 +22,10 @@
      * Tracks per-page-load metrics for content suggestions.
      * @param categories The categories of content suggestions.
      * @param suggestionsPerCategory The number of content suggestions in each category.
-     * @param visibleCategoriesCount The number of (possibly empty) categories visible in the UI.
+     * @param isCategoryVisible A boolean array representing which categories (possibly empty) are
+     *                          visible in the UI.
      */
-    void onPageShown(int[] categories, int[] suggestionsPerCategory, int visibleCategoriesCount);
+    void onPageShown(int[] categories, int[] suggestionsPerCategory, boolean[] isCategoryVisible);
 
     /**
      * Tracks impression metrics for a content suggestion.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporterBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporterBridge.java
index 21a1978..1cf2e82 100644
--- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporterBridge.java
+++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsEventReporterBridge.java
@@ -21,8 +21,8 @@
 
     @Override
     public void onPageShown(
-            int[] categories, int[] suggestionsPerCategory, int visibleCategoriesCount) {
-        nativeOnPageShown(categories, suggestionsPerCategory, visibleCategoriesCount);
+            int[] categories, int[] suggestionsPerCategory, boolean[] isCategoryVisible) {
+        nativeOnPageShown(categories, suggestionsPerCategory, isCategoryVisible);
     }
 
     @Override
@@ -88,7 +88,7 @@
     }
 
     private static native void nativeOnPageShown(
-            int[] categories, int[] suggestionsPerCategory, int visibleCategoriesCount);
+            int[] categories, int[] suggestionsPerCategory, boolean[] isCategoryVisible);
     private static native void nativeOnSuggestionShown(int globalPosition, int category,
             int positionInCategory, long publishTimestampMs, float score, long fetchTimestampMs);
     private static native void nativeOnSuggestionOpened(int globalPosition, int category,
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java
index 183bd0ead..9e3c250 100644
--- a/chrome/android/javatests/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java
+++ b/chrome/android/javatests/src/org/chromium/chrome/browser/banners/AppBannerManagerTest.java
@@ -246,7 +246,7 @@
                 AppBannerManager manager =
                         mActivityTestRule.getActivity().getActivityTab().getAppBannerManager();
                 return mDetailsDelegate.mNumRetrieved == numExpected
-                        && !manager.isActiveForTesting();
+                        && !manager.isRunningForTesting();
             }
         });
     }
@@ -344,7 +344,7 @@
             public boolean isSatisfied() {
                 AppBannerManager manager =
                         mActivityTestRule.getActivity().getActivityTab().getAppBannerManager();
-                return !manager.isActiveForTesting();
+                return !manager.isRunningForTesting();
             }
         });
         InfoBarUtil.waitUntilNoInfoBarsExist(mActivityTestRule.getInfoBars());
@@ -364,7 +364,7 @@
             public boolean isSatisfied() {
                 AppBannerManager manager =
                         mActivityTestRule.getActivity().getActivityTab().getAppBannerManager();
-                return !manager.isActiveForTesting();
+                return !manager.isRunningForTesting();
             }
         });
         waitUntilAppBannerInfoBarAppears(expectedTitle);
@@ -656,7 +656,7 @@
             public boolean isSatisfied() {
                 AppBannerManager manager =
                         mActivityTestRule.getActivity().getActivityTab().getAppBannerManager();
-                return !manager.isActiveForTesting();
+                return !manager.isRunningForTesting();
             }
         });
         waitUntilAppBannerInfoBarAppears(WEB_APP_TITLE);
@@ -678,7 +678,7 @@
             public boolean isSatisfied() {
                 AppBannerManager manager =
                         mActivityTestRule.getActivity().getActivityTab().getAppBannerManager();
-                return !manager.isActiveForTesting();
+                return !manager.isRunningForTesting();
             }
         });
         Assert.assertTrue(mActivityTestRule.getInfoBars().isEmpty());
diff --git a/chrome/browser/android/banners/app_banner_manager_android.cc b/chrome/browser/android/banners/app_banner_manager_android.cc
index 967a2758..a5c12745 100644
--- a/chrome/browser/android/banners/app_banner_manager_android.cc
+++ b/chrome/browser/android/banners/app_banner_manager_android.cc
@@ -87,10 +87,10 @@
   return java_banner_manager_;
 }
 
-bool AppBannerManagerAndroid::IsActiveForTesting(
+bool AppBannerManagerAndroid::IsRunningForTesting(
     JNIEnv* env,
     const JavaParamRef<jobject>& obj) {
-  return is_active();
+  return IsRunning();
 }
 
 void AppBannerManagerAndroid::RecordMenuOpen(JNIEnv* env,
@@ -225,10 +225,8 @@
   if (bitmap.drawsNothing()) {
     ReportStatus(web_contents(), NO_ICON_AVAILABLE);
     Stop();
-  }
-
-  if (!is_active())
     return;
+  }
 
   primary_icon_ = bitmap;
   SendBannerPromptRequest();
diff --git a/chrome/browser/android/banners/app_banner_manager_android.h b/chrome/browser/android/banners/app_banner_manager_android.h
index 9a6cd3cd..e442309 100644
--- a/chrome/browser/android/banners/app_banner_manager_android.h
+++ b/chrome/browser/android/banners/app_banner_manager_android.h
@@ -42,8 +42,8 @@
       const;
 
   // Returns true if the banner pipeline is currently running.
-  bool IsActiveForTesting(JNIEnv* env,
-                          const base::android::JavaParamRef<jobject>& jobj);
+  bool IsRunningForTesting(JNIEnv* env,
+                           const base::android::JavaParamRef<jobject>& jobj);
 
   // Informs the InstallableManager for the WebContents we are attached to that
   // the add to homescreen menu item has been tapped.
diff --git a/chrome/browser/android/ntp/suggestions_event_reporter_bridge.cc b/chrome/browser/android/ntp/suggestions_event_reporter_bridge.cc
index aa3703a..0d348897 100644
--- a/chrome/browser/android/ntp/suggestions_event_reporter_bridge.cc
+++ b/chrome/browser/android/ntp/suggestions_event_reporter_bridge.cc
@@ -66,21 +66,22 @@
     const JavaParamRef<jclass>& caller,
     const JavaParamRef<jintArray>& jcategories,
     const JavaParamRef<jintArray>& jsuggestions_per_category,
-    jint j_visible_categories_count) {
+    const JavaParamRef<jbooleanArray>& jis_category_visible) {
   std::vector<int> categories_int;
   JavaIntArrayToIntVector(env, jcategories, &categories_int);
-  std::vector<int> suggestions_per_category_int;
+  std::vector<int> suggestions_per_category;
   JavaIntArrayToIntVector(env, jsuggestions_per_category,
-                          &suggestions_per_category_int);
-  DCHECK_EQ(categories_int.size(), suggestions_per_category_int.size());
-  std::vector<std::pair<Category, int>> suggestions_per_category;
+                          &suggestions_per_category);
+  DCHECK_EQ(categories_int.size(), suggestions_per_category.size());
+  std::vector<bool> is_category_visible;
+  JavaBooleanArrayToBoolVector(env, jis_category_visible, &is_category_visible);
+  DCHECK_EQ(categories_int.size(), is_category_visible.size());
+  std::vector<Category> categories;
   for (size_t i = 0; i < categories_int.size(); i++) {
-    suggestions_per_category.push_back(
-        std::make_pair(Category::FromIDValue(categories_int[i]),
-                       suggestions_per_category_int[i]));
+    categories.push_back(Category::FromIDValue(categories_int[i]));
   }
-  ntp_snippets::metrics::OnPageShown(suggestions_per_category,
-                                     j_visible_categories_count);
+  ntp_snippets::metrics::OnPageShown(categories, suggestions_per_category,
+                                     is_category_visible);
   GetUserClassifier()->OnEvent(UserClassifier::Metric::NTP_OPENED);
 }
 
diff --git a/chrome/browser/banners/app_banner_manager.cc b/chrome/browser/banners/app_banner_manager.cc
index b9675ac71..59e0a228f 100644
--- a/chrome/browser/banners/app_banner_manager.cc
+++ b/chrome/browser/banners/app_banner_manager.cc
@@ -62,14 +62,13 @@
 
   // The only time we should start the pipeline while it is already running is
   // if it's been triggered from devtools.
-  if (is_active_or_pending()) {
+  if (state_ != State::INACTIVE) {
     DCHECK(is_debug_mode);
     ResetBindings();
   }
 
   UpdateState(State::ACTIVE);
   triggered_by_devtools_ = is_debug_mode;
-  page_requested_prompt_ = false;
 
   // We only need to call ReportStatus if we aren't in debug mode (this avoids
   // skew from testing).
@@ -100,7 +99,7 @@
   if (binding_.is_bound())
     binding_.Close();
 
-  UpdateState(State::PENDING_MANIFEST);
+  UpdateState(State::FETCHING_MANIFEST);
   manager_->GetData(
       ParamsToGetManifest(),
       base::Bind(&AppBannerManager::OnDidGetManifest, GetWeakPtr()));
@@ -137,7 +136,6 @@
       binding_(this),
       has_sufficient_engagement_(false),
       load_finished_(false),
-      page_requested_prompt_(false),
       triggered_by_devtools_(false),
       need_to_log_status_(false),
       weak_factory_(this) {
@@ -298,12 +296,10 @@
   // Record the status if we are currently waiting for data.
   InstallableStatusCode code = NO_ERROR_DETECTED;
   switch (state_) {
-    case State::PENDING_EVENT:
-      if (!page_requested_prompt_) {
-        TrackBeforeInstallEvent(
-            BEFORE_INSTALL_EVENT_PROMPT_NOT_CALLED_AFTER_PREVENT_DEFAULT);
-        code = RENDERER_CANCELLED;
-      }
+    case State::PENDING_PROMPT:
+      TrackBeforeInstallEvent(
+          BEFORE_INSTALL_EVENT_PROMPT_NOT_CALLED_AFTER_PREVENT_DEFAULT);
+      code = RENDERER_CANCELLED;
       break;
     case State::PENDING_ENGAGEMENT:
       if (!has_sufficient_engagement_) {
@@ -311,13 +307,15 @@
         code = INSUFFICIENT_ENGAGEMENT;
       }
       break;
-    case State::PENDING_MANIFEST:
+    case State::FETCHING_MANIFEST:
       code = WAITING_FOR_MANIFEST;
       break;
     case State::PENDING_INSTALLABLE_CHECK:
       code = WAITING_FOR_INSTALLABLE_CHECK;
       break;
     case State::ACTIVE:
+    case State::SENDING_EVENT:
+    case State::SENDING_EVENT_GOT_EARLY_PROMPT:
     case State::INACTIVE:
     case State::COMPLETE:
       break;
@@ -328,9 +326,11 @@
 
   // In every non-debug run through the banner pipeline, we should have called
   // ReportStatus() and set need_to_log_status_ to false. The only case where
-  // we don't is if we're still active and waiting for native app data, which is
-  // explicitly not logged.
-  DCHECK(!need_to_log_status_ || is_active());
+  // we don't is if we're still running and aren't blocked on the network. When
+  // running and blocked on the network the state should be logged.
+  // TODO(dominickn): log when the pipeline is fetching native app banner
+  // details.
+  DCHECK(!need_to_log_status_ || (IsRunning() && !IsWaitingForData()));
 
   ResetBindings();
   UpdateState(State::COMPLETE);
@@ -340,6 +340,8 @@
 
 void AppBannerManager::SendBannerPromptRequest() {
   RecordCouldShowBanner();
+
+  UpdateState(State::SENDING_EVENT);
   TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_CREATED);
 
   web_contents()->GetMainFrame()->GetRemoteInterfaces()->GetInterface(
@@ -354,21 +356,17 @@
 
 void AppBannerManager::UpdateState(State state) {
   state_ = state;
-
-  // If we are PENDING_EVENT, we must have sufficient engagement.
-  DCHECK(!is_pending_event() || has_sufficient_engagement_);
 }
 
 void AppBannerManager::DidStartNavigation(content::NavigationHandle* handle) {
   if (!handle->IsInMainFrame() || handle->IsSameDocument())
     return;
 
-  if (is_active_or_pending())
+  if (state_ != State::COMPLETE && state_ != State::INACTIVE)
     Stop();
   UpdateState(State::INACTIVE);
   load_finished_ = false;
   has_sufficient_engagement_ = false;
-  page_requested_prompt_ = false;
 }
 
 void AppBannerManager::DidFinishNavigation(content::NavigationHandle* handle) {
@@ -401,7 +399,7 @@
 
   // Start the pipeline immediately if we pass (or bypass) the engagement check,
   // or if the feature to run the installability check on page load is enabled.
-  if (!is_active_or_pending() &&
+  if (state_ == State::INACTIVE &&
       (has_sufficient_engagement_ ||
        base::FeatureList::IsEnabled(
            features::kCheckInstallabilityForBannerOnLoad))) {
@@ -428,12 +426,6 @@
 void AppBannerManager::OnEngagementIncreased(content::WebContents* contents,
                                              const GURL& url,
                                              double score) {
-  // In the ACTIVE state, we may have triggered the installability check, but
-  // not checked engagement yet. In the INACTIVE or PENDING_ENGAGEMENT states,
-  // we are waiting for an engagement signal to trigger the pipeline.
-  if (is_complete() || is_pending_event())
-    return;
-
   // Only trigger a banner using site engagement if:
   //  1. engagement increased for the web contents which we are attached to; and
   //  2. there are no currently active media players; and
@@ -447,7 +439,7 @@
       // directly to sending the banner prompt request.
       UpdateState(State::ACTIVE);
       SendBannerPromptRequest();
-    } else if (load_finished_ && !is_active_or_pending()) {
+    } else if (load_finished_ && state_ == State::INACTIVE) {
       // This performs some simple tests and starts async checks to test
       // installability. It should be safe to start in response to user input.
       // Don't call if we're already working on processing a banner request.
@@ -456,6 +448,28 @@
   }
 }
 
+bool AppBannerManager::IsRunning() const {
+  switch (state_) {
+    case State::INACTIVE:
+    case State::PENDING_PROMPT:
+    case State::PENDING_ENGAGEMENT:
+    case State::COMPLETE:
+      return false;
+    case State::ACTIVE:
+    case State::FETCHING_MANIFEST:
+    case State::PENDING_INSTALLABLE_CHECK:
+    case State::SENDING_EVENT:
+    case State::SENDING_EVENT_GOT_EARLY_PROMPT:
+      return true;
+  }
+  return false;
+}
+
+bool AppBannerManager::IsWaitingForData() const {
+  return (state_ == State::FETCHING_MANIFEST ||
+          state_ == State::PENDING_INSTALLABLE_CHECK);
+}
+
 void AppBannerManager::ResetBindings() {
   weak_factory_.InvalidateWeakPtrs();
   binding_.Close();
@@ -525,26 +539,28 @@
   // that the cancelation was requested, so Stop() can be called if a redisplay
   // isn't asked for.
   //
-  // We use the additional page_requested_prompt_ variable because the redisplay
-  // request may be received *before* the Cancel prompt reply (e.g. if redisplay
-  // is requested in the beforeinstallprompt event handler).
+  // If the redisplay request has not been received already, we stop here and
+  // wait for the prompt function to be called. If the redisplay request has
+  // already been received before cancel was sent (e.g. if redisplay was
+  // requested in the beforeinstallprompt event handler), we keep going and show
+  // the banner immediately.
   referrer_ = referrer;
   if (reply == blink::mojom::AppBannerPromptReply::CANCEL) {
-    UpdateState(State::PENDING_EVENT);
     TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_PREVENT_DEFAULT_CALLED);
-    if (!page_requested_prompt_)
+    if (state_ == State::SENDING_EVENT) {
+      UpdateState(State::PENDING_PROMPT);
       return;
+    }
+    DCHECK_EQ(State::SENDING_EVENT_GOT_EARLY_PROMPT, state_);
   }
 
-  // If we haven't yet returned, but we're in the PENDING_EVENT state or
-  // |page_requested_prompt_| is true, the page has requested a delayed showing
-  // of the prompt. Otherwise, the prompt was never canceled by the page.
-  if (is_pending_event()) {
+  // If we are still in the SENDING_EVENT state, the prompt was never canceled
+  // by the page. Otherwise the page requested a delayed showing of the prompt.
+  if (state_ == State::SENDING_EVENT) {
+    TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_NO_ACTION);
+  } else {
     TrackBeforeInstallEvent(
         BEFORE_INSTALL_EVENT_PROMPT_CALLED_AFTER_PREVENT_DEFAULT);
-    UpdateState(State::ACTIVE);
-  } else {
-    TrackBeforeInstallEvent(BEFORE_INSTALL_EVENT_NO_ACTION);
   }
 
   AppBannerSettingsHelper::RecordMinutesFromFirstVisitToShow(
@@ -561,12 +577,11 @@
 }
 
 void AppBannerManager::DisplayAppBanner(bool user_gesture) {
-  if (is_pending_event()) {
+  if (state_ == State::PENDING_PROMPT) {
     // Simulate a non-canceled OnBannerPromptReply to show the delayed banner.
     OnBannerPromptReply(blink::mojom::AppBannerPromptReply::NONE, referrer_);
-  } else {
-    // Log that the prompt request was made for when we get the prompt reply.
-    page_requested_prompt_ = true;
+  } else if (state_ == State::SENDING_EVENT) {
+    UpdateState(State::SENDING_EVENT_GOT_EARLY_PROMPT);
   }
 }
 
diff --git a/chrome/browser/banners/app_banner_manager.h b/chrome/browser/banners/app_banner_manager.h
index d2745644..1131063 100644
--- a/chrome/browser/banners/app_banner_manager.h
+++ b/chrome/browser/banners/app_banner_manager.h
@@ -101,19 +101,28 @@
 
     // The banner pipeline is currently waiting for the page manifest to be
     // fetched.
-    PENDING_MANIFEST,
+    FETCHING_MANIFEST,
 
     // The banner pipeline is currently waiting for the installability criteria
-    // to be checked.
+    // to be checked. In this state the pipeline could be paused while waiting
+    // for the site to register a service worker.
     PENDING_INSTALLABLE_CHECK,
 
     // The banner pipeline has finished running, but is waiting for sufficient
     // engagement to trigger the banner.
     PENDING_ENGAGEMENT,
 
-    // The banner pipeline has finished running, but is waiting for an event to
-    // trigger the banner.
-    PENDING_EVENT,
+    // The banner has sent the beforeinstallprompt event and is waiting for the
+    // response to the event.
+    SENDING_EVENT,
+
+    // The banner has sent the beforeinstallprompt, and the web page called
+    // prompt on the event while the event was being handled.
+    SENDING_EVENT_GOT_EARLY_PROMPT,
+
+    // The banner pipeline has finished running, but is waiting for the web page
+    // to call prompt on the event.
+    PENDING_PROMPT,
 
     // The banner pipeline has finished running for this page load and no more
     // processing is to be done.
@@ -215,28 +224,13 @@
   // Subclass accessors for private fields which should not be changed outside
   // this class.
   InstallableManager* manager() const { return manager_; }
-  bool is_active() const { return state_ == State::ACTIVE; }
-  bool is_active_or_pending() const {
-    switch (state_) {
-      case State::ACTIVE:
-      case State::PENDING_MANIFEST:
-      case State::PENDING_INSTALLABLE_CHECK:
-      case State::PENDING_ENGAGEMENT:
-      case State::PENDING_EVENT:
-        return true;
-      case State::INACTIVE:
-      case State::COMPLETE:
-        return false;
-    }
-    return false;
-  }
+  bool is_inactive() const { return state_ == State::INACTIVE; }
   bool is_complete() const { return state_ == State::COMPLETE; }
   bool is_pending_engagement() const {
     return state_ == State::PENDING_ENGAGEMENT;
   }
-  bool is_pending_event() const {
-    return state_ == State::PENDING_EVENT || page_requested_prompt_;
-  }
+  bool IsRunning() const;
+  bool IsWaitingForData() const;
 
   // The URL for which the banner check is being conducted.
   GURL validated_url_;
@@ -303,9 +297,6 @@
   bool has_sufficient_engagement_;
   bool load_finished_;
 
-  // Record whether the page requests for a banner to be shown later on.
-  bool page_requested_prompt_;
-
   // Whether the current flow was begun via devtools.
   bool triggered_by_devtools_;
 
diff --git a/chrome/browser/banners/app_banner_manager_browsertest.cc b/chrome/browser/banners/app_banner_manager_browsertest.cc
index 60ac59b..3328089 100644
--- a/chrome/browser/banners/app_banner_manager_browsertest.cc
+++ b/chrome/browser/banners/app_banner_manager_browsertest.cc
@@ -54,9 +54,7 @@
 
   void clear_will_show() { will_show_.reset(); }
 
-  bool is_active_or_pending() {
-    return AppBannerManager::is_active_or_pending();
-  }
+  bool is_inactive() { return AppBannerManager::is_inactive(); }
 
   bool is_complete() { return AppBannerManager::is_complete(); }
 
@@ -180,7 +178,7 @@
         ui_test_utils::NavigateToURL(browser, test_url);
 
         EXPECT_FALSE(manager->will_show());
-        EXPECT_FALSE(manager->is_active_or_pending());
+        EXPECT_TRUE(manager->is_inactive());
 
         histograms.ExpectTotalCount(banners::kMinutesHistogram, 0);
         histograms.ExpectTotalCount(banners::kInstallableStatusCodeHistogram,
@@ -201,7 +199,10 @@
     run_loop.Run();
 
     EXPECT_EQ(expected_to_show, manager->will_show());
-    EXPECT_FALSE(manager->is_active_or_pending());
+
+    // Generally the manager will be in the complete state, however some test
+    // cases navigate the page, causing the state to go back to INACTIVE.
+    EXPECT_TRUE(manager->is_complete() || manager->is_inactive());
 
     // Check the tab title; this allows the test page to send data back out to
     // be inspected by the test case.
@@ -482,7 +483,6 @@
   }
 
   EXPECT_TRUE(manager->will_show());
-  EXPECT_FALSE(manager->is_active_or_pending());
   EXPECT_FALSE(manager->need_to_log_status());
   EXPECT_TRUE(manager->is_complete());
 
@@ -526,7 +526,7 @@
   }
 
   EXPECT_FALSE(manager->will_show());
-  EXPECT_FALSE(manager->is_active_or_pending());
+  EXPECT_TRUE(manager->is_inactive());
   EXPECT_FALSE(manager->need_to_log_status());
 
   histograms.ExpectTotalCount(banners::kMinutesHistogram, 0);
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
index 4aecdb5..9970e00 100644
--- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
+++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -177,7 +177,7 @@
         TestParameter(NOT_IN_GUEST_MODE, "deleteOneItemFromToolbar")));
 
 WRAPPED_INSTANTIATE_TEST_CASE_P(
-    DISABLED_QuickView,
+    QuickView,
     FileManagerBrowserTest,
     ::testing::Values(TestParameter(NOT_IN_GUEST_MODE, "openQuickView")));
 
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.cc b/chrome/browser/metrics/chrome_metrics_service_client.cc
index 5224097..631690d7 100644
--- a/chrome/browser/metrics/chrome_metrics_service_client.cc
+++ b/chrome/browser/metrics/chrome_metrics_service_client.cc
@@ -689,8 +689,7 @@
   }
   watcher_metrics_provider_ = new browser_watcher::WatcherMetricsProviderWin(
       chrome::GetBrowserExitCodesRegistryPath(), user_data_dir, crash_dir,
-      base::Bind(&GetExecutableVersionDetails),
-      content::BrowserThread::GetBlockingPool());
+      base::Bind(&GetExecutableVersionDetails));
   metrics_service_->RegisterMetricsProvider(
       std::unique_ptr<metrics::MetricsProvider>(watcher_metrics_provider_));
 
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter.cc b/chrome/browser/ssl/chrome_expect_ct_reporter.cc
index e569426..17c91a5 100644
--- a/chrome/browser/ssl/chrome_expect_ct_reporter.cc
+++ b/chrome/browser/ssl/chrome_expect_ct_reporter.cc
@@ -4,6 +4,7 @@
 
 #include "chrome/browser/ssl/chrome_expect_ct_reporter.h"
 
+#include <set>
 #include <string>
 
 #include "base/base64.h"
@@ -14,15 +15,39 @@
 #include "base/metrics/histogram_macros.h"
 #include "base/metrics/sparse_histogram.h"
 #include "base/strings/string_number_conversions.h"
+#include "base/strings/string_split.h"
+#include "base/strings/string_util.h"
 #include "base/strings/stringprintf.h"
 #include "base/values.h"
 #include "chrome/common/chrome_features.h"
+#include "net/base/load_flags.h"
 #include "net/cert/ct_serialization.h"
 #include "net/traffic_annotation/network_traffic_annotation.h"
 #include "net/url_request/report_sender.h"
+#include "net/url_request/url_request_context.h"
 
 namespace {
 
+// Returns true if |request| contains any of the |allowed_values| in a response
+// header field named |header|. |allowed_values| are expected to be lower-case
+// and the check is case-insensitive.
+bool HasHeaderValues(net::URLRequest* request,
+                     const std::string& header,
+                     const std::set<std::string>& allowed_values) {
+  std::string response_headers;
+  request->GetResponseHeaderByName(header, &response_headers);
+  const std::vector<std::string> response_values = base::SplitString(
+      response_headers, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
+  for (const auto& value : response_values) {
+    for (const auto& allowed : allowed_values) {
+      if (base::ToLowerASCII(allowed) == base::ToLowerASCII(value)) {
+        return true;
+      }
+    }
+  }
+  return false;
+}
+
 std::string TimeToISO8601(const base::Time& t) {
   base::Time::Exploded exploded;
   t.UTCExplode(&exploded);
@@ -129,7 +154,8 @@
 ChromeExpectCTReporter::ChromeExpectCTReporter(
     net::URLRequestContext* request_context)
     : report_sender_(
-          new net::ReportSender(request_context, kTrafficAnnotation)) {}
+          new net::ReportSender(request_context, kTrafficAnnotation)),
+      request_context_(request_context) {}
 
 ChromeExpectCTReporter::~ChromeExpectCTReporter() {}
 
@@ -173,7 +199,85 @@
 
   UMA_HISTOGRAM_BOOLEAN("SSL.ExpectCTReportSendingAttempt", true);
 
-  report_sender_->Send(report_uri, "application/json; charset=utf-8",
-                       serialized_report, base::Callback<void()>(),
+  SendPreflight(report_uri, serialized_report);
+}
+
+void ChromeExpectCTReporter::OnResponseStarted(net::URLRequest* request,
+                                               int net_error) {
+  auto preflight_it = inflight_preflights_.find(request);
+  DCHECK(inflight_preflights_.end() != inflight_preflights_.find(request));
+  PreflightInProgress* preflight = preflight_it->second.get();
+
+  const int response_code = request->GetResponseCode();
+
+  // Check that the preflight succeeded: it must have an HTTP OK status code,
+  // with the following headers:
+  // - Access-Control-Allow-Origin: * or null
+  // - Access-Control-Allow-Methods: POST
+  // - Access-Control-Allow-Headers: Content-Type
+
+  if (!request->status().is_success() || response_code < 200 ||
+      response_code > 299) {
+    RecordUMAOnFailure(preflight->report_uri, request->status().error(),
+                       request->status().is_success() ? response_code : -1);
+    inflight_preflights_.erase(request);
+    // Do not use |preflight| after this point, since it has been erased above.
+    return;
+  }
+
+  if (!HasHeaderValues(request, "Access-Control-Allow-Origin", {"*", "null"}) ||
+      !HasHeaderValues(request, "Access-Control-Allow-Methods", {"post"}) ||
+      !HasHeaderValues(request, "Access-Control-Allow-Headers",
+                       {"content-type"})) {
+    RecordUMAOnFailure(preflight->report_uri, request->status().error(),
+                       response_code);
+    inflight_preflights_.erase(request);
+    // Do not use |preflight| after this point, since it has been erased above.
+    return;
+  }
+
+  report_sender_->Send(preflight->report_uri,
+                       "application/expect-ct-report+json; charset=utf-8",
+                       preflight->serialized_report, base::Callback<void()>(),
                        base::Bind(RecordUMAOnFailure));
+  inflight_preflights_.erase(request);
+}
+
+void ChromeExpectCTReporter::OnReadCompleted(net::URLRequest* request,
+                                             int bytes_read) {
+  NOTREACHED();
+}
+
+ChromeExpectCTReporter::PreflightInProgress::PreflightInProgress(
+    std::unique_ptr<net::URLRequest> request,
+    const std::string& serialized_report,
+    const GURL& report_uri)
+    : request(std::move(request)),
+      serialized_report(serialized_report),
+      report_uri(report_uri) {}
+
+ChromeExpectCTReporter::PreflightInProgress::~PreflightInProgress() {}
+
+void ChromeExpectCTReporter::SendPreflight(
+    const GURL& report_uri,
+    const std::string& serialized_report) {
+  std::unique_ptr<net::URLRequest> url_request =
+      request_context_->CreateRequest(report_uri, net::DEFAULT_PRIORITY, this,
+                                      kTrafficAnnotation);
+  url_request->SetLoadFlags(net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
+                            net::LOAD_DO_NOT_SEND_AUTH_DATA |
+                            net::LOAD_DO_NOT_SEND_COOKIES |
+                            net::LOAD_DO_NOT_SAVE_COOKIES);
+  url_request->set_method("OPTIONS");
+
+  net::HttpRequestHeaders extra_headers;
+  extra_headers.SetHeader("Origin", "null");
+  extra_headers.SetHeader("Access-Control-Request-Method", "POST");
+  extra_headers.SetHeader("Access-Control-Request-Headers", "content-type");
+  url_request->SetExtraRequestHeaders(extra_headers);
+
+  net::URLRequest* raw_request = url_request.get();
+  inflight_preflights_[raw_request] = base::MakeUnique<PreflightInProgress>(
+      std::move(url_request), serialized_report, report_uri);
+  raw_request->Start();
 }
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter.h b/chrome/browser/ssl/chrome_expect_ct_reporter.h
index f45d9ad5..bb07a527 100644
--- a/chrome/browser/ssl/chrome_expect_ct_reporter.h
+++ b/chrome/browser/ssl/chrome_expect_ct_reporter.h
@@ -5,10 +5,12 @@
 #ifndef CHROME_BROWSER_SSL_CHROME_EXPECT_CT_REPORTER_H_
 #define CHROME_BROWSER_SSL_CHROME_EXPECT_CT_REPORTER_H_
 
+#include <map>
 #include <memory>
 
 #include "base/macros.h"
 #include "net/http/transport_security_state.h"
+#include "net/url_request/url_request.h"
 
 namespace net {
 class ReportSender;
@@ -19,8 +21,14 @@
 // about failures for sites that have opted in. Must be deleted before
 // the URLRequestContext that is passed to the constructor, so that it
 // can cancel its requests.
+//
+// Since reports are sent with a non-CORS-whitelisted Content-Type, this class
+// sends CORS preflight requests before sending reports. Expect-CT is not
+// evaluated with a particular frame or request as context, so the preflight
+// request contains an `Origin: null` header instead of a particular origin.
 class ChromeExpectCTReporter
-    : public net::TransportSecurityState::ExpectCTReporter {
+    : public net::TransportSecurityState::ExpectCTReporter,
+      net::URLRequest::Delegate {
  public:
   explicit ChromeExpectCTReporter(net::URLRequestContext* request_context);
   ~ChromeExpectCTReporter() override;
@@ -34,13 +42,54 @@
                         const net::SignedCertificateTimestampAndStatusList&
                             signed_certificate_timestamps) override;
 
+  // net::URLRequest::Delegate:
+  void OnResponseStarted(net::URLRequest* request, int net_error) override;
+  void OnReadCompleted(net::URLRequest* request, int bytes_read) override;
+
  private:
+  // Used to keep track of in-flight CORS preflight requests. When |request|
+  // completes successfully and the CORS check passes, |serialized_report| will
+  // be sent to |report_uri| using |report_sender_|.
+  struct PreflightInProgress {
+    PreflightInProgress(std::unique_ptr<net::URLRequest> request,
+                        const std::string& serialized_report,
+                        const GURL& report_uri);
+    ~PreflightInProgress();
+    // The preflight request.
+    const std::unique_ptr<net::URLRequest> request;
+    // |serialized_report| should be sent to |report_uri| if the preflight
+    // succeeds.
+    const std::string serialized_report;
+    const GURL report_uri;
+  };
+
   FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest, FeatureDisabled);
   FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest, EmptyReportURI);
   FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest, SendReport);
+  FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest,
+                           BadCORSPreflightResponseOrigin);
+  FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest,
+                           BadCORSPreflightResponseMethods);
+  FRIEND_TEST_ALL_PREFIXES(ChromeExpectCTReporterTest,
+                           BadCORSPreflightResponseHeaders);
+
+  // Starts a CORS preflight request to obtain permission from the server to
+  // send a report with Content-Type: application/expect-ct-report+json. The
+  // preflight result is checked in OnResponseStarted(), and an actual report is
+  // sent with |report_sender_| if the preflight succeeds.
+  void SendPreflight(const GURL& report_uri,
+                     const std::string& serialized_report);
 
   std::unique_ptr<net::ReportSender> report_sender_;
 
+  net::URLRequestContext* request_context_;
+
+  // The CORS preflight requests, with corresponding report information, that
+  // are currently in-flight. Entries in this map are deleted when the
+  // preflight's OnResponseStarted() is called.
+  std::map<net::URLRequest*, std::unique_ptr<PreflightInProgress>>
+      inflight_preflights_;
+
   DISALLOW_COPY_AND_ASSIGN(ChromeExpectCTReporter);
 };
 
diff --git a/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc b/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc
index 755444a..34ef988f 100644
--- a/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc
+++ b/chrome/browser/ssl/chrome_expect_ct_reporter_unittest.cc
@@ -9,7 +9,6 @@
 #include "base/base64.h"
 #include "base/command_line.h"
 #include "base/json/json_reader.h"
-#include "base/message_loop/message_loop.h"
 #include "base/run_loop.h"
 #include "base/test/histogram_tester.h"
 #include "base/test/scoped_feature_list.h"
@@ -19,6 +18,8 @@
 #include "net/cert/ct_serialization.h"
 #include "net/cert/signed_certificate_timestamp_and_status.h"
 #include "net/test/cert_test_util.h"
+#include "net/test/embedded_test_server/embedded_test_server.h"
+#include "net/test/embedded_test_server/http_response.h"
 #include "net/test/test_data_directory.h"
 #include "net/test/url_request/url_request_failed_job.h"
 #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
@@ -50,6 +51,10 @@
     latest_report_uri_ = report_uri;
     serialized_report.CopyToString(&latest_serialized_report_);
     content_type.CopyToString(&latest_content_type_);
+    if (!report_callback_.is_null()) {
+      EXPECT_EQ(expected_report_uri_, latest_report_uri_);
+      report_callback_.Run();
+    }
   }
 
   const GURL& latest_report_uri() const { return latest_report_uri_; }
@@ -62,10 +67,26 @@
     return latest_serialized_report_;
   }
 
+  // Can be called to wait for a single report, which is expected to be sent to
+  // |report_uri|. Returns immediately if a report has already been sent in the
+  // past.
+  void WaitForReport(const GURL& report_uri) {
+    if (!latest_report_uri_.is_empty()) {
+      EXPECT_EQ(report_uri, latest_report_uri_);
+      return;
+    }
+    base::RunLoop run_loop;
+    report_callback_ = run_loop.QuitClosure();
+    expected_report_uri_ = report_uri;
+    run_loop.Run();
+  }
+
  private:
   GURL latest_report_uri_;
   std::string latest_content_type_;
   std::string latest_serialized_report_;
+  base::Closure report_callback_;
+  GURL expected_report_uri_;
 };
 
 // Constructs a net::SignedCertificateTimestampAndStatus with the given
@@ -299,14 +320,97 @@
   DISALLOW_COPY_AND_ASSIGN(ChromeExpectCTReporterWaitTest);
 };
 
+// A test fixture that responds properly to CORS preflights so that reports can
+// be successfully sent to test_server().
+class ChromeExpectCTReporterTest : public ::testing::Test {
+ public:
+  ChromeExpectCTReporterTest()
+      : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
+  ~ChromeExpectCTReporterTest() override {}
+
+  void SetUp() override {
+    report_server_.RegisterRequestHandler(
+        base::Bind(&ChromeExpectCTReporterTest::HandleReportPreflight,
+                   base::Unretained(this)));
+    ASSERT_TRUE(report_server_.Start());
+  }
+
+  std::unique_ptr<net::test_server::HttpResponse> HandleReportPreflight(
+      const net::test_server::HttpRequest& request) {
+    num_requests_++;
+    if (!requests_callback_.is_null()) {
+      requests_callback_.Run();
+    }
+    std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
+        new net::test_server::BasicHttpResponse());
+    http_response->set_code(net::HTTP_OK);
+    for (const auto& cors_header : cors_headers_) {
+      http_response->AddCustomHeader(cors_header.first, cors_header.second);
+    }
+    return http_response;
+  }
+
+  void WaitForReportPreflight() {
+    if (num_requests_ >= 1) {
+      return;
+    }
+    base::RunLoop run_loop;
+    requests_callback_ = run_loop.QuitClosure();
+    run_loop.Run();
+  }
+
+ protected:
+  const net::EmbeddedTestServer& test_server() { return report_server_; }
+
+  // Tests that reports are not sent when the CORS preflight request returns the
+  // header field |preflight_header_name| with value given by
+  // |preflight_header_bad_value|, and that reports are successfully sent when
+  // it has value given by |preflight_header_good_value|.
+  void TestForReportPreflightFailure(
+      ChromeExpectCTReporter* reporter,
+      TestCertificateReportSender* sender,
+      const net::HostPortPair& host_port,
+      const net::SSLInfo& ssl_info,
+      const std::string& preflight_header_name,
+      const std::string& preflight_header_bad_value,
+      const std::string& preflight_header_good_value) {
+    cors_headers_[preflight_header_name] = preflight_header_bad_value;
+    const GURL fail_report_uri = test_server().GetURL("/report1");
+    reporter->OnExpectCTFailed(
+        host_port, fail_report_uri, base::Time(), ssl_info.cert.get(),
+        ssl_info.unverified_cert.get(), ssl_info.signed_certificate_timestamps);
+    WaitForReportPreflight();
+    EXPECT_TRUE(sender->latest_report_uri().is_empty());
+    EXPECT_TRUE(sender->latest_serialized_report().empty());
+
+    // Set the proper header value and send a dummy report. The test will fail
+    // if the previous OnExpectCTFailed() call unexpectedly resulted in a
+    // report, as WaitForReport() would see the previous report to /report1
+    // instead of the expected report to /report2.
+    const GURL successful_report_uri = test_server().GetURL("/report2");
+    cors_headers_[preflight_header_name] = preflight_header_good_value;
+    reporter->OnExpectCTFailed(
+        host_port, successful_report_uri, base::Time(), ssl_info.cert.get(),
+        ssl_info.unverified_cert.get(), ssl_info.signed_certificate_timestamps);
+    sender->WaitForReport(successful_report_uri);
+    EXPECT_EQ(successful_report_uri, sender->latest_report_uri());
+  }
+
+ private:
+  content::TestBrowserThreadBundle thread_bundle_;
+  net::EmbeddedTestServer report_server_;
+  uint32_t num_requests_ = 0;
+  base::Closure requests_callback_;
+  std::map<std::string, std::string> cors_headers_{
+      {"Access-Control-Allow-Origin", "*"},
+      {"Access-Control-Allow-Methods", "GET,POST"},
+      {"Access-Control-Allow-Headers", "content-type,another-header"}};
+};
+
 }  // namespace
 
 // Test that no report is sent when the feature is not enabled.
-TEST(ChromeExpectCTReporterTest, FeatureDisabled) {
-  base::test::ScopedFeatureList scoped_feature_list;
-  scoped_feature_list.InitAndDisableFeature(features::kExpectCTReporting);
-
-  base::MessageLoop message_loop;
+TEST_F(ChromeExpectCTReporterTest, FeatureDisabled) {
   base::HistogramTester histograms;
   histograms.ExpectTotalCount(kSendHistogramName, 0);
 
@@ -324,20 +428,39 @@
       net::GetTestCertsDirectory(), "localhost_cert.pem");
 
   net::HostPortPair host_port("example.test", 443);
-  GURL report_uri("http://example-report.test");
 
-  reporter.OnExpectCTFailed(host_port, report_uri, base::Time(),
-                            ssl_info.cert.get(), ssl_info.unverified_cert.get(),
-                            ssl_info.signed_certificate_timestamps);
-  EXPECT_TRUE(sender->latest_report_uri().is_empty());
-  EXPECT_TRUE(sender->latest_serialized_report().empty());
+  {
+    const GURL report_uri = test_server().GetURL("/report1");
+    base::test::ScopedFeatureList scoped_feature_list;
+    scoped_feature_list.InitAndDisableFeature(features::kExpectCTReporting);
 
-  histograms.ExpectTotalCount(kSendHistogramName, 0);
+    reporter.OnExpectCTFailed(
+        host_port, report_uri, base::Time(), ssl_info.cert.get(),
+        ssl_info.unverified_cert.get(), ssl_info.signed_certificate_timestamps);
+    EXPECT_TRUE(sender->latest_report_uri().is_empty());
+    EXPECT_TRUE(sender->latest_serialized_report().empty());
+
+    histograms.ExpectTotalCount(kSendHistogramName, 0);
+  }
+
+  // Enable the feature and send a dummy report. The test will fail if the
+  // previous OnExpectCTFailed() call unexpectedly resulted in a report, as the
+  // WaitForReport() would see the previous report to /report1 instead of the
+  // expected report to /report2.
+  {
+    const GURL report_uri = test_server().GetURL("/report2");
+    base::test::ScopedFeatureList scoped_feature_list;
+    scoped_feature_list.InitAndEnableFeature(features::kExpectCTReporting);
+    reporter.OnExpectCTFailed(
+        host_port, report_uri, base::Time(), ssl_info.cert.get(),
+        ssl_info.unverified_cert.get(), ssl_info.signed_certificate_timestamps);
+    sender->WaitForReport(report_uri);
+    EXPECT_EQ(report_uri, sender->latest_report_uri());
+  }
 }
 
 // Test that no report is sent if the report URI is empty.
-TEST(ChromeExpectCTReporterTest, EmptyReportURI) {
-  base::MessageLoop message_loop;
+TEST_F(ChromeExpectCTReporterTest, EmptyReportURI) {
   base::HistogramTester histograms;
   histograms.ExpectTotalCount(kSendHistogramName, 0);
 
@@ -385,8 +508,7 @@
 }
 
 // Test that a sent report has the right format.
-TEST(ChromeExpectCTReporterTest, SendReport) {
-  base::MessageLoop message_loop;
+TEST_F(ChromeExpectCTReporterTest, SendReport) {
   base::HistogramTester histograms;
   histograms.ExpectTotalCount(kFailureHistogramName, 0);
   histograms.ExpectTotalCount(kSendHistogramName, 0);
@@ -454,26 +576,104 @@
                        net::ct::SCT_STATUS_OK,
                        &ssl_info.signed_certificate_timestamps);
 
-  net::HostPortPair host_port("example.test", 443);
-  GURL report_uri("http://example-report.test");
-
   const char kExpirationTimeStr[] = "2017-01-01T00:00:00.000Z";
   base::Time expiration;
   ASSERT_TRUE(
       base::Time::FromUTCExploded({2017, 1, 0, 1, 0, 0, 0, 0}, &expiration));
 
+  const GURL report_uri = test_server().GetURL("/report");
+
   // Check that the report is sent and contains the correct information.
-  reporter.OnExpectCTFailed(host_port, report_uri, expiration,
-                            ssl_info.cert.get(), ssl_info.unverified_cert.get(),
+  reporter.OnExpectCTFailed(net::HostPortPair::FromURL(report_uri), report_uri,
+                            expiration, ssl_info.cert.get(),
+                            ssl_info.unverified_cert.get(),
                             ssl_info.signed_certificate_timestamps);
+
+  // A CORS preflight request should be sent before the actual report.
+  WaitForReportPreflight();
+  sender->WaitForReport(report_uri);
+
   EXPECT_EQ(report_uri, sender->latest_report_uri());
   EXPECT_FALSE(sender->latest_serialized_report().empty());
-  EXPECT_EQ("application/json; charset=utf-8", sender->latest_content_type());
-  ASSERT_NO_FATAL_FAILURE(
-      CheckExpectCTReport(sender->latest_serialized_report(), host_port,
-                          kExpirationTimeStr, ssl_info));
+  EXPECT_EQ("application/expect-ct-report+json; charset=utf-8",
+            sender->latest_content_type());
+  ASSERT_NO_FATAL_FAILURE(CheckExpectCTReport(
+      sender->latest_serialized_report(),
+      net::HostPortPair::FromURL(report_uri), kExpirationTimeStr, ssl_info));
 
   histograms.ExpectTotalCount(kFailureHistogramName, 0);
   histograms.ExpectTotalCount(kSendHistogramName, 1);
   histograms.ExpectBucketCount(kSendHistogramName, true, 1);
 }
+
+// Test that no report is sent when the CORS preflight returns an invalid
+// Access-Control-Allow-Origin.
+TEST_F(ChromeExpectCTReporterTest, BadCORSPreflightResponseOrigin) {
+  TestCertificateReportSender* sender = new TestCertificateReportSender();
+  net::TestURLRequestContext context;
+  ChromeExpectCTReporter reporter(&context);
+  reporter.report_sender_.reset(sender);
+  EXPECT_TRUE(sender->latest_report_uri().is_empty());
+  EXPECT_TRUE(sender->latest_serialized_report().empty());
+
+  net::SSLInfo ssl_info;
+  ssl_info.cert =
+      net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
+  ssl_info.unverified_cert = net::ImportCertFromFile(
+      net::GetTestCertsDirectory(), "localhost_cert.pem");
+
+  base::test::ScopedFeatureList scoped_feature_list;
+  scoped_feature_list.InitAndEnableFeature(features::kExpectCTReporting);
+  EXPECT_TRUE(sender->latest_serialized_report().empty());
+  ASSERT_NO_FATAL_FAILURE(TestForReportPreflightFailure(
+      &reporter, sender, net::HostPortPair("example.test", 443), ssl_info,
+      "Access-Control-Allow-Origin", "https://another-origin.test", "null"));
+}
+
+// Test that no report is sent when the CORS preflight returns an invalid
+// Access-Control-Allow-Methods.
+TEST_F(ChromeExpectCTReporterTest, BadCORSPreflightResponseMethods) {
+  TestCertificateReportSender* sender = new TestCertificateReportSender();
+  net::TestURLRequestContext context;
+  ChromeExpectCTReporter reporter(&context);
+  reporter.report_sender_.reset(sender);
+  EXPECT_TRUE(sender->latest_report_uri().is_empty());
+  EXPECT_TRUE(sender->latest_serialized_report().empty());
+
+  net::SSLInfo ssl_info;
+  ssl_info.cert =
+      net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
+  ssl_info.unverified_cert = net::ImportCertFromFile(
+      net::GetTestCertsDirectory(), "localhost_cert.pem");
+
+  base::test::ScopedFeatureList scoped_feature_list;
+  scoped_feature_list.InitAndEnableFeature(features::kExpectCTReporting);
+  EXPECT_TRUE(sender->latest_serialized_report().empty());
+  ASSERT_NO_FATAL_FAILURE(TestForReportPreflightFailure(
+      &reporter, sender, net::HostPortPair("example.test", 443), ssl_info,
+      "Access-Control-Allow-Methods", "GET,HEAD,POSSSST", "POST"));
+}
+
+// Test that no report is sent when the CORS preflight returns an invalid
+// Access-Control-Allow-Headers.
+TEST_F(ChromeExpectCTReporterTest, BadCORSPreflightResponseHeaders) {
+  TestCertificateReportSender* sender = new TestCertificateReportSender();
+  net::TestURLRequestContext context;
+  ChromeExpectCTReporter reporter(&context);
+  reporter.report_sender_.reset(sender);
+  EXPECT_TRUE(sender->latest_report_uri().is_empty());
+  EXPECT_TRUE(sender->latest_serialized_report().empty());
+
+  net::SSLInfo ssl_info;
+  ssl_info.cert =
+      net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
+  ssl_info.unverified_cert = net::ImportCertFromFile(
+      net::GetTestCertsDirectory(), "localhost_cert.pem");
+
+  base::test::ScopedFeatureList scoped_feature_list;
+  scoped_feature_list.InitAndEnableFeature(features::kExpectCTReporting);
+  EXPECT_TRUE(sender->latest_serialized_report().empty());
+  ASSERT_NO_FATAL_FAILURE(TestForReportPreflightFailure(
+      &reporter, sender, net::HostPortPair("example.test", 443), ssl_info,
+      "Access-Control-Allow-Headers", "Not-Content-Type", "Content-Type"));
+}
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/suggestions/DummySuggestionsEventReporter.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/suggestions/DummySuggestionsEventReporter.java
index 6afb9cb..f73e3aa4 100644
--- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/suggestions/DummySuggestionsEventReporter.java
+++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/suggestions/DummySuggestionsEventReporter.java
@@ -19,7 +19,7 @@
 
     @Override
     public void onPageShown(
-            int[] categories, int[] suggestionsPerCategory, int visibleCategoriesCount) {}
+            int[] categories, int[] suggestionsPerCategory, boolean[] isCategoryVisible) {}
 
     @Override
     public void onSuggestionShown(SnippetArticle suggestion) {}
diff --git a/chromeos/cryptohome/cryptohome_parameters.cc b/chromeos/cryptohome/cryptohome_parameters.cc
index 4f6d557..9eab9f00 100644
--- a/chromeos/cryptohome/cryptohome_parameters.cc
+++ b/chromeos/cryptohome/cryptohome_parameters.cc
@@ -253,12 +253,3 @@
 }
 
 }  // namespace cryptohome
-
-namespace BASE_HASH_NAMESPACE {
-
-std::size_t hash<cryptohome::Identification>::operator()(
-    const cryptohome::Identification& cryptohome_id) const {
-  return hash<std::string>()(cryptohome_id.id());
-}
-
-}  // namespace BASE_HASH_NAMESPACE
diff --git a/chromeos/cryptohome/cryptohome_parameters.h b/chromeos/cryptohome/cryptohome_parameters.h
index 8525f7f..60a4c14 100644
--- a/chromeos/cryptohome/cryptohome_parameters.h
+++ b/chromeos/cryptohome/cryptohome_parameters.h
@@ -189,15 +189,4 @@
 
 }  // namespace cryptohome
 
-namespace BASE_HASH_NAMESPACE {
-
-// Implement hashing of cryptohome::Identification, so it can be used as a key
-// in STL containers.
-template <>
-struct hash<cryptohome::Identification> {
-  std::size_t operator()(const cryptohome::Identification& cryptohome_id) const;
-};
-
-}  // namespace BASE_HASH_NAMESPACE
-
 #endif  // CHROMEOS_CRYPTOHOME_CRYPTOHOME_PARAMETERS_H_
diff --git a/chromeos/cryptohome/homedir_methods_unittest.cc b/chromeos/cryptohome/homedir_methods_unittest.cc
index 0ce060d6..9fb8c4d 100644
--- a/chromeos/cryptohome/homedir_methods_unittest.cc
+++ b/chromeos/cryptohome/homedir_methods_unittest.cc
@@ -13,37 +13,17 @@
 #include "base/bind_helpers.h"
 #include "base/compiler_specific.h"
 #include "base/macros.h"
+#include "base/run_loop.h"
+#include "base/test/scoped_task_environment.h"
 #include "chromeos/dbus/cryptohome/rpc.pb.h"
 #include "chromeos/dbus/cryptohome_client.h"
 #include "chromeos/dbus/dbus_method_call_status.h"
 #include "chromeos/dbus/dbus_thread_manager.h"
-#include "chromeos/dbus/mock_cryptohome_client.h"
 #include "components/signin/core/account_id/account_id.h"
-#include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
-using testing::_;
-using testing::Invoke;
-using testing::WithArg;
-
 namespace cryptohome {
 
-namespace {
-
-MATCHER_P(EqualsProto, expected_proto, "") {
-  std::string expected_value;
-  expected_proto.SerializeToString(&expected_value);
-  std::string actual_value;
-  arg.SerializeToString(&actual_value);
-  return actual_value == expected_value;
-}
-
-MATCHER_P(EqualsIdentification, expected_identification, "") {
-  return arg == expected_identification;
-}
-
-}  // namespace
-
 const char kUserID[] = "user@example.com";
 const char kKeyLabel[] = "key_label";
 
@@ -55,93 +35,32 @@
 
 class HomedirMethodsTest : public testing::Test {
  public:
-  HomedirMethodsTest();
-  ~HomedirMethodsTest() override;
+  HomedirMethodsTest() = default;
+  ~HomedirMethodsTest() override = default;
 
   // testing::Test:
-  void SetUp() override;
-  void TearDown() override;
+  void SetUp() override {
+    chromeos::DBusThreadManager::Initialize();
+    HomedirMethods::Initialize();
+  }
 
-  void RunProtobufMethodCallback(
-      const chromeos::CryptohomeClient::ProtobufMethodCallback& callback);
-
-  void StoreGetKeyDataExResult(
-      bool success,
-      MountError return_code,
-      const std::vector<KeyDefinition>& key_definitions);
+  void TearDown() override {
+    HomedirMethods::Shutdown();
+    chromeos::DBusThreadManager::Shutdown();
+  }
 
  protected:
-  chromeos::MockCryptohomeClient* cryptohome_client_;
-
-  // The reply that |cryptohome_client_| will make.
-  BaseReply cryptohome_reply_;
-
-  // The results of the most recent |HomedirMethods| method call.
-  bool success_;
-  MountError return_code_;
-  std::vector<KeyDefinition> key_definitions_;
+  base::test::ScopedTaskEnvironment task_environment_;
 
  private:
   DISALLOW_COPY_AND_ASSIGN(HomedirMethodsTest);
 };
 
-HomedirMethodsTest::HomedirMethodsTest() : cryptohome_client_(NULL),
-                                           success_(false),
-                                           return_code_(MOUNT_ERROR_FATAL) {
-}
-
-HomedirMethodsTest::~HomedirMethodsTest() {
-}
-
-void HomedirMethodsTest::SetUp() {
-  std::unique_ptr<chromeos::MockCryptohomeClient> cryptohome_client(
-      new chromeos::MockCryptohomeClient);
-  cryptohome_client_ = cryptohome_client.get();
-  chromeos::DBusThreadManager::GetSetterForTesting()->SetCryptohomeClient(
-      std::move(cryptohome_client));
-  HomedirMethods::Initialize();
-}
-
-void HomedirMethodsTest::TearDown() {
-  HomedirMethods::Shutdown();
-  chromeos::DBusThreadManager::Shutdown();
-}
-
-void HomedirMethodsTest::RunProtobufMethodCallback(
-    const chromeos::CryptohomeClient::ProtobufMethodCallback& callback) {
-  callback.Run(chromeos::DBUS_METHOD_CALL_SUCCESS,
-               true,
-               cryptohome_reply_);
-}
-
-void HomedirMethodsTest::StoreGetKeyDataExResult(
-    bool success,
-    MountError return_code,
-    const std::vector<KeyDefinition>& key_definitions) {
-  success_ = success;
-  return_code_ = return_code;
-  key_definitions_ = key_definitions;
-}
-
 // Verifies that the result of a GetKeyDataEx() call is correctly parsed.
 TEST_F(HomedirMethodsTest, GetKeyDataEx) {
-  const Identification expected_id(AccountId::FromUserEmail(kUserID));
-  const AuthorizationRequest expected_auth;
-  GetKeyDataRequest expected_request;
-  expected_request.mutable_key()->mutable_data()->set_label(kKeyLabel);
-
-  EXPECT_CALL(*cryptohome_client_,
-              GetKeyDataEx(EqualsIdentification(expected_id),
-                           EqualsProto(expected_auth),
-                           EqualsProto(expected_request), _))
-      .Times(1)
-      .WillOnce(WithArg<3>(
-          Invoke(this, &HomedirMethodsTest::RunProtobufMethodCallback)));
-
-  // Set up the reply that |cryptohome_client_| will make.
-  GetKeyDataReply* reply =
-      cryptohome_reply_.MutableExtension(GetKeyDataReply::reply);
-  KeyData* key_data = reply->add_key_data();
+  // Set up the pseudo KeyData.
+  AddKeyRequest request;
+  KeyData* key_data = request.mutable_key()->mutable_data();
   key_data->set_type(KeyData::KEY_TYPE_PASSWORD);
   key_data->set_label(kKeyLabel);
   key_data->mutable_privileges()->set_update(false);
@@ -149,24 +68,37 @@
   key_data->add_authorization_data()->set_type(
       KeyAuthorizationData::KEY_AUTHORIZATION_TYPE_HMACSHA256);
   KeyProviderData* data = key_data->mutable_provider_data();
-  KeyProviderData::Entry* entry = data->add_entry();
-  entry->set_name(kProviderData1Name);
-  entry->set_number(kProviderData1Number);
-  entry = data->add_entry();
-  entry->set_name(kProviderData2Name);
-  entry->set_bytes(kProviderData2Bytes);
+  KeyProviderData::Entry* entry1 = data->add_entry();
+  entry1->set_name(kProviderData1Name);
+  entry1->set_number(kProviderData1Number);
+  KeyProviderData::Entry* entry2 = data->add_entry();
+  entry2->set_name(kProviderData2Name);
+  entry2->set_bytes(kProviderData2Bytes);
+  chromeos::DBusThreadManager::Get()->GetCryptohomeClient()->AddKeyEx(
+      cryptohome::Identification(AccountId::FromUserEmail(kUserID)),
+      AuthorizationRequest(), request,
+      base::Bind([](chromeos::DBusMethodCallStatus call_status, bool result,
+                    const BaseReply& reply) { ASSERT_TRUE(result); }));
+  ASSERT_NO_FATAL_FAILURE(base::RunLoop().RunUntilIdle());
 
   // Call GetKeyDataEx().
+  std::vector<KeyDefinition> key_definitions;
   HomedirMethods::GetInstance()->GetKeyDataEx(
       Identification(AccountId::FromUserEmail(kUserID)), kKeyLabel,
-      base::Bind(&HomedirMethodsTest::StoreGetKeyDataExResult,
-                 base::Unretained(this)));
+      base::Bind(
+          [](std::vector<KeyDefinition>* out_key_definitions, bool success,
+             MountError return_code,
+             const std::vector<KeyDefinition>& key_definitions) {
+            EXPECT_TRUE(success);
+            EXPECT_EQ(MOUNT_ERROR_NONE, return_code);
+            *out_key_definitions = key_definitions;
+          },
+          &key_definitions));
+  base::RunLoop().RunUntilIdle();
 
   // Verify that the call was successful and the result was correctly parsed.
-  EXPECT_TRUE(success_);
-  EXPECT_EQ(MOUNT_ERROR_NONE, return_code_);
-  ASSERT_EQ(1u, key_definitions_.size());
-  const KeyDefinition& key_definition = key_definitions_.front();
+  ASSERT_EQ(1u, key_definitions.size());
+  const KeyDefinition& key_definition = key_definitions.front();
   EXPECT_EQ(KeyDefinition::TYPE_PASSWORD, key_definition.type);
   EXPECT_EQ(PRIV_MOUNT | PRIV_ADD | PRIV_REMOVE,
             key_definition.privileges);
diff --git a/chromeos/dbus/fake_cryptohome_client.cc b/chromeos/dbus/fake_cryptohome_client.cc
index 6fee9df..850a4f88 100644
--- a/chromeos/dbus/fake_cryptohome_client.cc
+++ b/chromeos/dbus/fake_cryptohome_client.cc
@@ -512,7 +512,14 @@
     const cryptohome::GetKeyDataRequest& request,
     const ProtobufMethodCallback& callback) {
   cryptohome::BaseReply reply;
-  reply.MutableExtension(cryptohome::GetKeyDataReply::reply);
+  auto it = key_data_map_.find(cryptohome_id);
+  if (it == key_data_map_.end()) {
+    reply.set_error(cryptohome::CRYPTOHOME_ERROR_ACCOUNT_NOT_FOUND);
+  } else {
+    cryptohome::GetKeyDataReply* key_data_reply =
+        reply.MutableExtension(cryptohome::GetKeyDataReply::reply);
+    *key_data_reply->add_key_data() = it->second;
+  }
   ReturnProtobufMethodCallback(reply, callback);
 }
 
@@ -547,6 +554,7 @@
     const cryptohome::AuthorizationRequest& auth,
     const cryptohome::AddKeyRequest& request,
     const ProtobufMethodCallback& callback) {
+  key_data_map_.insert(std::make_pair(cryptohome_id, request.key().data()));
   cryptohome::BaseReply reply;
   ReturnProtobufMethodCallback(reply, callback);
 }
diff --git a/chromeos/dbus/fake_cryptohome_client.h b/chromeos/dbus/fake_cryptohome_client.h
index eee04a5..32671a2d 100644
--- a/chromeos/dbus/fake_cryptohome_client.h
+++ b/chromeos/dbus/fake_cryptohome_client.h
@@ -14,6 +14,8 @@
 #include "base/macros.h"
 #include "base/memory/weak_ptr.h"
 #include "base/timer/timer.h"
+#include "chromeos/cryptohome/cryptohome_parameters.h"
+#include "chromeos/dbus/cryptohome/key.pb.h"
 #include "chromeos/dbus/cryptohome_client.h"
 
 namespace chromeos {
@@ -272,6 +274,8 @@
   std::map<std::string, std::vector<uint8_t>> install_attrs_;
   bool locked_;
 
+  std::map<cryptohome::Identification, cryptohome::KeyData> key_data_map_;
+
   DircryptoMigrationProgessHandler dircrypto_migration_progress_handler_;
   base::RepeatingTimer dircrypto_migration_progress_timer_;
   uint64_t dircrypto_migration_progress_;
diff --git a/components/browser_watcher/watcher_metrics_provider_win.cc b/components/browser_watcher/watcher_metrics_provider_win.cc
index dcd7881..a95e63a 100644
--- a/components/browser_watcher/watcher_metrics_provider_win.cc
+++ b/components/browser_watcher/watcher_metrics_provider_win.cc
@@ -23,6 +23,8 @@
 #include "base/strings/string_number_conversions.h"
 #include "base/strings/string_piece.h"
 #include "base/strings/utf_string_conversions.h"
+#include "base/task_scheduler/post_task.h"
+#include "base/task_scheduler/task_traits.h"
 #include "base/win/registry.h"
 #include "components/browser_watcher/features.h"
 #include "components/browser_watcher/postmortem_report_collector.h"
@@ -162,6 +164,14 @@
                             INIT_STATUS_MAX);
 }
 
+// Returns a task runner appropriate for running background tasks that perform
+// file I/O.
+scoped_refptr<base::TaskRunner> CreateBackgroundTaskRunner() {
+  return base::CreateSequencedTaskRunnerWithTraits(
+      {base::MayBlock(), base::TaskPriority::BACKGROUND,
+       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
+}
+
 }  // namespace
 
 const char WatcherMetricsProviderWin::kBrowserExitCodeHistogramName[] =
@@ -171,18 +181,15 @@
     const base::string16& registry_path,
     const base::FilePath& user_data_dir,
     const base::FilePath& crash_dir,
-    const GetExecutableDetailsCallback& exe_details_cb,
-    base::TaskRunner* io_task_runner)
+    const GetExecutableDetailsCallback& exe_details_cb)
     : recording_enabled_(false),
       cleanup_scheduled_(false),
       registry_path_(registry_path),
       user_data_dir_(user_data_dir),
       crash_dir_(crash_dir),
       exe_details_cb_(exe_details_cb),
-      io_task_runner_(io_task_runner),
-      weak_ptr_factory_(this) {
-  DCHECK(io_task_runner_);
-}
+      task_runner_(CreateBackgroundTaskRunner()),
+      weak_ptr_factory_(this) {}
 
 WatcherMetricsProviderWin::~WatcherMetricsProviderWin() {
 }
@@ -195,9 +202,10 @@
   if (!recording_enabled_ && !cleanup_scheduled_) {
     // When metrics reporting is disabled, the providers get an
     // OnRecordingDisabled notification at startup. Use that first notification
-    // to issue the cleanup task.
-    io_task_runner_->PostTask(
-        FROM_HERE, base::Bind(&DeleteExitCodeRegistryKey, registry_path_));
+    // to issue the cleanup task. Runs in the background because interacting
+    // with the registry can block.
+    task_runner_->PostTask(
+        FROM_HERE, base::BindOnce(&DeleteExitCodeRegistryKey, registry_path_));
 
     cleanup_scheduled_ = true;
   }
@@ -216,17 +224,16 @@
 
 void WatcherMetricsProviderWin::CollectPostmortemReports(
     const base::Closure& done_callback) {
-  io_task_runner_->PostTaskAndReply(
+  task_runner_->PostTaskAndReply(
       FROM_HERE,
-      base::Bind(
-          &WatcherMetricsProviderWin::CollectPostmortemReportsOnBlockingPool,
-          weak_ptr_factory_.GetWeakPtr()),
+      base::BindOnce(&WatcherMetricsProviderWin::CollectPostmortemReportsImpl,
+                     weak_ptr_factory_.GetWeakPtr()),
       done_callback);
 }
 
 // TODO(manzagop): consider mechanisms for partial collection if this is to be
 //     used on a critical path.
-void WatcherMetricsProviderWin::CollectPostmortemReportsOnBlockingPool() {
+void WatcherMetricsProviderWin::CollectPostmortemReportsImpl() {
   SCOPED_UMA_HISTOGRAM_TIMER("ActivityTracker.Collect.TotalTime");
 
   bool is_stability_debugging_on =
diff --git a/components/browser_watcher/watcher_metrics_provider_win.h b/components/browser_watcher/watcher_metrics_provider_win.h
index 65c5307d3..fbd408233c 100644
--- a/components/browser_watcher/watcher_metrics_provider_win.h
+++ b/components/browser_watcher/watcher_metrics_provider_win.h
@@ -11,7 +11,6 @@
 #include "base/memory/weak_ptr.h"
 #include "base/strings/string16.h"
 #include "base/task_runner.h"
-#include "base/threading/thread_checker.h"
 #include "components/metrics/metrics_provider.h"
 
 namespace browser_watcher {
@@ -26,14 +25,11 @@
 
   static const char kBrowserExitCodeHistogramName[];
 
-  // Initializes the reporter. |io_task_runner| is used for collecting
-  // postmortem reports and clearing leftover data in registry if metrics
-  // reporting is disabled.
+  // Initializes the reporter.
   WatcherMetricsProviderWin(const base::string16& registry_path,
                             const base::FilePath& user_data_dir,
                             const base::FilePath& crash_dir,
-                            const GetExecutableDetailsCallback& exe_details_cb,
-                            base::TaskRunner* io_task_runner);
+                            const GetExecutableDetailsCallback& exe_details_cb);
   ~WatcherMetricsProviderWin() override;
 
   // metrics::MetricsProvider implementation.
@@ -59,7 +55,7 @@
  private:
   // TODO(manzagop): avoid collecting reports for clean exits from the fast exit
   // path.
-  void CollectPostmortemReportsOnBlockingPool();
+  void CollectPostmortemReportsImpl();
 
   bool recording_enabled_;
   bool cleanup_scheduled_;
@@ -67,7 +63,11 @@
   const base::FilePath user_data_dir_;
   const base::FilePath crash_dir_;
   GetExecutableDetailsCallback exe_details_cb_;
-  scoped_refptr<base::TaskRunner> io_task_runner_;
+
+  // Used for collecting postmortem reports and clearing leftover data in
+  // registry if metrics reporting is disabled.
+  scoped_refptr<base::TaskRunner> task_runner_;
+
   base::WeakPtrFactory<WatcherMetricsProviderWin> weak_ptr_factory_;
 
   DISALLOW_COPY_AND_ASSIGN(WatcherMetricsProviderWin);
diff --git a/components/browser_watcher/watcher_metrics_provider_win_unittest.cc b/components/browser_watcher/watcher_metrics_provider_win_unittest.cc
index fbce251..af78d5d 100644
--- a/components/browser_watcher/watcher_metrics_provider_win_unittest.cc
+++ b/components/browser_watcher/watcher_metrics_provider_win_unittest.cc
@@ -13,8 +13,8 @@
 #include "base/strings/string16.h"
 #include "base/strings/stringprintf.h"
 #include "base/test/histogram_tester.h"
+#include "base/test/scoped_task_environment.h"
 #include "base/test/test_reg_util_win.h"
-#include "base/test/test_simple_task_runner.h"
 #include "base/win/registry.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
@@ -36,7 +36,6 @@
 
     ASSERT_NO_FATAL_FAILURE(
         override_manager_.OverrideRegistry(HKEY_CURRENT_USER));
-    test_task_runner_ = new base::TestSimpleTaskRunner();
   }
 
   void AddProcessExitCode(bool use_own_pid, int exit_code) {
@@ -66,9 +65,9 @@
   }
 
  protected:
+  base::test::ScopedTaskEnvironment scoped_task_environment_;
   registry_util::RegistryOverrideManager override_manager_;
   base::HistogramTester histogram_tester_;
-  scoped_refptr<base::TestSimpleTaskRunner> test_task_runner_;
 };
 
 }  // namespace
@@ -81,9 +80,9 @@
   // Record a single failure.
   AddProcessExitCode(false, 100);
 
-  WatcherMetricsProviderWin provider(
-      kRegistryPath, base::FilePath(), base::FilePath(),
-      GetExecutableDetailsCallback(), test_task_runner_.get());
+  WatcherMetricsProviderWin provider(kRegistryPath, base::FilePath(),
+                                     base::FilePath(),
+                                     GetExecutableDetailsCallback());
 
   provider.ProvideStabilityMetrics(NULL);
   histogram_tester_.ExpectBucketCount(
@@ -105,9 +104,9 @@
   // Record own process as STILL_ACTIVE.
   AddProcessExitCode(true, STILL_ACTIVE);
 
-  WatcherMetricsProviderWin provider(
-      kRegistryPath, base::FilePath(), base::FilePath(),
-      GetExecutableDetailsCallback(), test_task_runner_.get());
+  WatcherMetricsProviderWin provider(kRegistryPath, base::FilePath(),
+                                     base::FilePath(),
+                                     GetExecutableDetailsCallback());
 
   provider.ProvideStabilityMetrics(NULL);
   histogram_tester_.ExpectUniqueSample(
@@ -127,22 +126,19 @@
   // Record a single failure.
   AddProcessExitCode(false, 100);
 
+  // Verify that the key exists prior to deletion.
+  base::win::RegKey key;
+  ASSERT_EQ(ERROR_SUCCESS,
+            key.Open(HKEY_CURRENT_USER, kRegistryPath, KEY_READ));
+
   // Make like the user is opted out of reporting.
-  WatcherMetricsProviderWin provider(
-      kRegistryPath, base::FilePath(), base::FilePath(),
-      GetExecutableDetailsCallback(), test_task_runner_.get());
+  WatcherMetricsProviderWin provider(kRegistryPath, base::FilePath(),
+                                     base::FilePath(),
+                                     GetExecutableDetailsCallback());
   provider.OnRecordingDisabled();
 
-  base::win::RegKey key;
-  {
-    // The deletion should be scheduled to the test_task_runner, and not happen
-    // immediately.
-    ASSERT_EQ(ERROR_SUCCESS,
-              key.Open(HKEY_CURRENT_USER, kRegistryPath, KEY_READ));
-  }
-
   // Flush the task(s).
-  test_task_runner_->RunPendingTasks();
+  scoped_task_environment_.RunUntilIdle();
 
   // Make sure the subkey for the pseudo process has been deleted on reporting.
   ASSERT_EQ(ERROR_FILE_NOT_FOUND,
diff --git a/components/ntp_snippets/content_suggestions_metrics.cc b/components/ntp_snippets/content_suggestions_metrics.cc
index 8d8e7b2..3be66f2a 100644
--- a/components/ntp_snippets/content_suggestions_metrics.cc
+++ b/components/ntp_snippets/content_suggestions_metrics.cc
@@ -23,8 +23,8 @@
 const int kMaxSuggestionsTotal = 50;
 const int kMaxCategories = 10;
 
-const char kHistogramCountOnNtpOpened[] =
-    "NewTabPage.ContentSuggestions.CountOnNtpOpened";
+const char kHistogramCountOnNtpOpenedIfVisible[] =
+    "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible";
 const char kHistogramSectionCountOnNtpOpened[] =
     "NewTabPage.ContentSuggestions.SectionCountOnNtpOpened";
 const char kHistogramShown[] = "NewTabPage.ContentSuggestions.Shown";
@@ -218,17 +218,24 @@
 
 }  // namespace
 
-void OnPageShown(
-    const std::vector<std::pair<Category, int>>& suggestions_per_category,
-    int visible_categories_count) {
+void OnPageShown(const std::vector<Category>& categories,
+                 const std::vector<int>& suggestions_per_category,
+                 const std::vector<bool>& is_category_visible) {
+  DCHECK_EQ(categories.size(), suggestions_per_category.size());
+  DCHECK_EQ(categories.size(), is_category_visible.size());
   int suggestions_total = 0;
-  for (const std::pair<Category, int>& item : suggestions_per_category) {
-    LogCategoryHistogramPosition(kHistogramCountOnNtpOpened, item.first,
-                                 item.second, kMaxSuggestionsPerCategory);
-    suggestions_total += item.second;
+  int visible_categories_count = 0;
+  for (size_t i = 0; i < categories.size(); ++i) {
+    if (is_category_visible[i]) {
+      LogCategoryHistogramPosition(kHistogramCountOnNtpOpenedIfVisible,
+                                   categories[i], suggestions_per_category[i],
+                                   kMaxSuggestionsPerCategory);
+      suggestions_total += suggestions_per_category[i];
+      ++visible_categories_count;
+    }
   }
-  UMA_HISTOGRAM_EXACT_LINEAR(kHistogramCountOnNtpOpened, suggestions_total,
-                             kMaxSuggestionsTotal);
+  UMA_HISTOGRAM_EXACT_LINEAR(kHistogramCountOnNtpOpenedIfVisible,
+                             suggestions_total, kMaxSuggestionsTotal);
   UMA_HISTOGRAM_EXACT_LINEAR(kHistogramSectionCountOnNtpOpened,
                              visible_categories_count, kMaxCategories);
 }
diff --git a/components/ntp_snippets/content_suggestions_metrics.h b/components/ntp_snippets/content_suggestions_metrics.h
index e31b771..160242a 100644
--- a/components/ntp_snippets/content_suggestions_metrics.h
+++ b/components/ntp_snippets/content_suggestions_metrics.h
@@ -15,9 +15,12 @@
 namespace ntp_snippets {
 namespace metrics {
 
-void OnPageShown(
-    const std::vector<std::pair<Category, int>>& suggestions_per_category,
-    int visible_categories_count);
+// |is_category_visible| contains true iff the corresponding category can be
+// seen by the user on this page (even if it is empty). It does not depend on
+// whether the user actually saw the category.
+void OnPageShown(const std::vector<Category>& categories,
+                 const std::vector<int>& suggestions_per_category,
+                 const std::vector<bool>& is_category_visible);
 
 // Should only be called once per NTP for each suggestion.
 void OnSuggestionShown(int global_position,
diff --git a/components/ntp_snippets/content_suggestions_metrics_unittest.cc b/components/ntp_snippets/content_suggestions_metrics_unittest.cc
index fe8193e3..fd636e4b 100644
--- a/components/ntp_snippets/content_suggestions_metrics_unittest.cc
+++ b/components/ntp_snippets/content_suggestions_metrics_unittest.cc
@@ -15,6 +15,7 @@
 namespace {
 
 using testing::ElementsAre;
+using testing::IsEmpty;
 
 TEST(ContentSuggestionsMetricsTest, ShouldLogOnSuggestionsShown) {
   base::HistogramTester histogram_tester;
@@ -45,6 +46,87 @@
                   base::Bucket(/*min=*/11, /*count=*/1)));
 }
 
+TEST(ContentSuggestionsMetricsTest,
+     ShouldNotLogNotShownCategoriesWhenPageShown) {
+  base::HistogramTester histogram_tester;
+  OnPageShown(std::vector<Category>(
+                  {Category::FromKnownCategory(KnownCategories::ARTICLES)}),
+              /*suggestions_per_category=*/{0},
+              /*is_category_visible=*/{false});
+  EXPECT_THAT(
+      histogram_tester.GetAllSamples(
+          "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible.Articles"),
+      IsEmpty());
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible"),
+              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.SectionCountOnNtpOpened"),
+              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
+}
+
+TEST(ContentSuggestionsMetricsTest,
+     ShouldLogEmptyShownCategoriesWhenPageShown) {
+  base::HistogramTester histogram_tester;
+  OnPageShown(std::vector<Category>(
+                  {Category::FromKnownCategory(KnownCategories::ARTICLES)}),
+              /*suggestions_per_category=*/{0},
+              /*is_category_visible=*/{true});
+  EXPECT_THAT(
+      histogram_tester.GetAllSamples(
+          "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible.Articles"),
+      ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible"),
+              ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.SectionCountOnNtpOpened"),
+              ElementsAre(base::Bucket(/*min=*/1, /*count=*/1)));
+}
+
+TEST(ContentSuggestionsMetricsTest,
+     ShouldLogNonEmptyShownCategoryWhenPageShown) {
+  base::HistogramTester histogram_tester;
+  OnPageShown(std::vector<Category>(
+                  {Category::FromKnownCategory(KnownCategories::ARTICLES)}),
+              /*suggestions_per_category=*/{10},
+              /*is_category_visible=*/{true});
+  EXPECT_THAT(
+      histogram_tester.GetAllSamples(
+          "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible.Articles"),
+      ElementsAre(base::Bucket(/*min=*/10, /*count=*/1)));
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible"),
+              ElementsAre(base::Bucket(/*min=*/10, /*count=*/1)));
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.SectionCountOnNtpOpened"),
+              ElementsAre(base::Bucket(/*min=*/1, /*count=*/1)));
+}
+
+TEST(ContentSuggestionsMetricsTest,
+     ShouldLogMultipleNonEmptyShownCategoriesWhenPageShown) {
+  base::HistogramTester histogram_tester;
+  OnPageShown(std::vector<Category>(
+                  {Category::FromKnownCategory(KnownCategories::ARTICLES),
+                   Category::FromKnownCategory(KnownCategories::BOOKMARKS)}),
+              /*suggestions_per_category=*/{10, 5},
+              /*is_category_visible=*/{true, true});
+  EXPECT_THAT(
+      histogram_tester.GetAllSamples(
+          "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible.Articles"),
+      ElementsAre(base::Bucket(/*min=*/10, /*count=*/1)));
+  EXPECT_THAT(
+      histogram_tester.GetAllSamples(
+          "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible.Bookmarks"),
+      ElementsAre(base::Bucket(/*min=*/5, /*count=*/1)));
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible"),
+              ElementsAre(base::Bucket(/*min=*/15, /*count=*/1)));
+  EXPECT_THAT(histogram_tester.GetAllSamples(
+                  "NewTabPage.ContentSuggestions.SectionCountOnNtpOpened"),
+              ElementsAre(base::Bucket(/*min=*/2, /*count=*/1)));
+}
+
 }  // namespace
 }  // namespace metrics
 }  // namespace ntp_snippets
diff --git a/content/browser/service_worker/embedded_worker_instance.cc b/content/browser/service_worker/embedded_worker_instance.cc
index a7c473cf..f8df38c9 100644
--- a/content/browser/service_worker/embedded_worker_instance.cc
+++ b/content/browser/service_worker/embedded_worker_instance.cc
@@ -25,6 +25,7 @@
 #include "content/public/browser/content_browser_client.h"
 #include "content/public/browser/render_process_host.h"
 #include "content/public/common/child_process_host.h"
+#include "content/public/common/content_client.h"
 #include "content/public/common/content_switches.h"
 #include "ipc/ipc_message.h"
 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
@@ -73,8 +74,7 @@
     ServiceWorkerStatusCode,
     std::unique_ptr<EmbeddedWorkerStartParams>,
     std::unique_ptr<ServiceWorkerProcessManager::AllocatedProcessInfo>,
-    std::unique_ptr<EmbeddedWorkerInstance::DevToolsProxy> devtools_proxy,
-    bool wait_for_debugger)>;
+    std::unique_ptr<EmbeddedWorkerInstance::DevToolsProxy> devtools_proxy)>;
 
 // Allocates a renderer process for starting a worker and does setup like
 // registering with DevTools. Called on the UI thread. Calls |callback| on the
@@ -91,13 +91,12 @@
   auto process_info =
       base::MakeUnique<ServiceWorkerProcessManager::AllocatedProcessInfo>();
   std::unique_ptr<EmbeddedWorkerInstance::DevToolsProxy> devtools_proxy;
-  bool wait_for_debugger = false;
   if (!process_manager) {
     BrowserThread::PostTask(
         BrowserThread::IO, FROM_HERE,
         base::BindOnce(std::move(callback), SERVICE_WORKER_ERROR_ABORT,
                        std::move(params), std::move(process_info),
-                       std::move(devtools_proxy), wait_for_debugger));
+                       std::move(devtools_proxy)));
     return;
   }
 
@@ -109,8 +108,7 @@
     BrowserThread::PostTask(
         BrowserThread::IO, FROM_HERE,
         base::BindOnce(std::move(callback), status, std::move(params),
-                       std::move(process_info), std::move(devtools_proxy),
-                       wait_for_debugger));
+                       std::move(process_info), std::move(devtools_proxy)));
     return;
   }
   const int process_id = process_info->process_id;
@@ -125,23 +123,34 @@
   if (request.is_pending())
     BindInterface(rph, std::move(request));
 
-  // Register to DevTools.
-  const int worker_devtools_agent_route_id = rph->GetNextRoutingID();
-  wait_for_debugger =
+  // Register to DevTools and update params accordingly.
+  const int routing_id = rph->GetNextRoutingID();
+  params->wait_for_debugger =
       ServiceWorkerDevToolsManager::GetInstance()->WorkerCreated(
-          process_id, worker_devtools_agent_route_id,
+          process_id, routing_id,
           ServiceWorkerDevToolsManager::ServiceWorkerIdentifier(
               context, weak_context, params->service_worker_version_id,
               params->script_url, params->scope),
           params->is_installed);
+  params->worker_devtools_agent_route_id = routing_id;
+  // Create DevToolsProxy here to ensure that the WorkerCreated() call is
+  // balanced by DevToolsProxy's destructor calling WorkerDestroyed().
   devtools_proxy = base::MakeUnique<EmbeddedWorkerInstance::DevToolsProxy>(
-      process_id, worker_devtools_agent_route_id);
+      process_id, routing_id);
 
+  // Set EmbeddedWorkerSettings for content settings only readable from the UI
+  // thread.
+  // TODO(bengr): Support changes to the data saver setting while the worker is
+  // running.
+  params->settings.data_saver_enabled =
+      GetContentClient()->browser()->IsDataSaverEnabled(
+          process_manager->browser_context());
+
+  // Continue on the IO thread.
   BrowserThread::PostTask(
       BrowserThread::IO, FROM_HERE,
       base::BindOnce(std::move(callback), status, std::move(params),
-                     std::move(process_info), std::move(devtools_proxy),
-                     wait_for_debugger));
+                     std::move(process_info), std::move(devtools_proxy)));
 }
 
 void CallDetach(EmbeddedWorkerInstance* instance) {
@@ -167,7 +176,6 @@
     case EmbeddedWorkerInstance::SCRIPT_EVALUATED:
     case EmbeddedWorkerInstance::THREAD_STARTED:
       return true;
-    case EmbeddedWorkerInstance::REGISTERING_TO_DEVTOOLS:  // Obsolete
     case EmbeddedWorkerInstance::STARTING_PHASE_MAX_VALUE:
       NOTREACHED();
   }
@@ -374,18 +382,12 @@
       std::unique_ptr<EmbeddedWorkerStartParams> params,
       std::unique_ptr<ServiceWorkerProcessManager::AllocatedProcessInfo>
           process_info,
-      std::unique_ptr<EmbeddedWorkerInstance::DevToolsProxy> devtools_proxy,
-      bool wait_for_debugger) {
+      std::unique_ptr<EmbeddedWorkerInstance::DevToolsProxy> devtools_proxy) {
     DCHECK_CURRENTLY_ON(BrowserThread::IO);
-
-    int process_id = process_info->process_id;
-    bool is_new_process = process_info->is_new_process;
-    const EmbeddedWorkerSettings& settings = process_info->settings;
     if (status != SERVICE_WORKER_OK) {
       TRACE_EVENT_NESTABLE_ASYNC_END1("ServiceWorker", "ALLOCATING_PROCESS",
                                       instance_, "Error",
                                       ServiceWorkerStatusToString(status));
-      DCHECK_EQ(ChildProcessHost::kInvalidUniqueID, process_id);
       StatusCallback callback = start_callback_;
       start_callback_.Reset();
       instance_->OnStartFailed(callback, status);
@@ -393,6 +395,7 @@
       return;
     }
 
+    const bool is_new_process = process_info->is_new_process;
     TRACE_EVENT_NESTABLE_ASYNC_END1("ServiceWorker", "ALLOCATING_PROCESS",
                                     instance_, "Is New Process",
                                     is_new_process);
@@ -411,22 +414,14 @@
     // Notify the instance that a process is allocated.
     state_ = ProcessAllocationState::ALLOCATED;
     instance_->OnProcessAllocated(
-        base::MakeUnique<WorkerProcessHandle>(instance_->context_,
-                                              instance_->embedded_worker_id(),
-                                              process_id, is_new_process),
+        base::MakeUnique<WorkerProcessHandle>(
+            instance_->context_, instance_->embedded_worker_id(),
+            process_info->process_id, is_new_process),
         start_situation);
 
-    // TODO(bengr): Support changes to this setting while the worker
-    // is running.
-    params->settings.data_saver_enabled = settings.data_saver_enabled;
-
-    // Update params with info from DevTools.
-    params->worker_devtools_agent_route_id = devtools_proxy->agent_route_id();
-    params->wait_for_debugger = wait_for_debugger;
-
-    // Notify the instance that it is registered to the devtools manager.
+    // Notify the instance that it is registered to the DevTools manager.
     instance_->OnRegisteredToDevToolsManager(
-        is_new_process, std::move(devtools_proxy), wait_for_debugger);
+        is_new_process, std::move(devtools_proxy), params->wait_for_debugger);
 
     status = instance_->SendStartWorker(std::move(params));
     if (status != SERVICE_WORKER_OK) {
@@ -1037,7 +1032,6 @@
       return "Script read finished";
     case SCRIPT_STREAMING:
       return "Script streaming";
-    case REGISTERING_TO_DEVTOOLS:  // Obsolete
     case STARTING_PHASE_MAX_VALUE:
       NOTREACHED();
   }
diff --git a/content/browser/service_worker/embedded_worker_instance.h b/content/browser/service_worker/embedded_worker_instance.h
index 41e3329e..b99d435 100644
--- a/content/browser/service_worker/embedded_worker_instance.h
+++ b/content/browser/service_worker/embedded_worker_instance.h
@@ -55,19 +55,20 @@
 
   // This enum is used in UMA histograms. Append-only.
   enum StartingPhase {
-    NOT_STARTING,
-    ALLOCATING_PROCESS,
-    REGISTERING_TO_DEVTOOLS,  // Obsolete
-    SENT_START_WORKER,
-    SCRIPT_DOWNLOADING,
-    SCRIPT_LOADED,
-    SCRIPT_EVALUATED,
-    THREAD_STARTED,  // Happens after SCRIPT_LOADED and before SCRIPT_EVALUATED
+    NOT_STARTING = 0,
+    ALLOCATING_PROCESS = 1,
+    // REGISTERING_TO_DEVTOOLS = 2,  // Obsolete
+    SENT_START_WORKER = 3,
+    SCRIPT_DOWNLOADING = 4,
+    SCRIPT_LOADED = 5,
+    SCRIPT_EVALUATED = 6,
+    // THREAD_STARTED happens after SCRIPT_LOADED and before SCRIPT_EVALUATED
+    THREAD_STARTED = 7,
     // Script read happens after SENT_START_WORKER and before SCRIPT_LOADED
     // (installed scripts only)
-    SCRIPT_READ_STARTED,
-    SCRIPT_READ_FINISHED,
-    SCRIPT_STREAMING,
+    SCRIPT_READ_STARTED = 8,
+    SCRIPT_READ_FINISHED = 9,
+    SCRIPT_STREAMING = 10,
     // Add new values here.
     STARTING_PHASE_MAX_VALUE,
   };
diff --git a/content/browser/service_worker/service_worker_process_manager.cc b/content/browser/service_worker/service_worker_process_manager.cc
index e79658c..4cf0da9 100644
--- a/content/browser/service_worker/service_worker_process_manager.cc
+++ b/content/browser/service_worker/service_worker_process_manager.cc
@@ -13,10 +13,8 @@
 #include "content/browser/service_worker/service_worker_context_wrapper.h"
 #include "content/browser/site_instance_impl.h"
 #include "content/public/browser/browser_thread.h"
-#include "content/public/browser/content_browser_client.h"
 #include "content/public/browser/site_instance.h"
 #include "content/public/common/child_process_host.h"
-#include "content/public/common/content_client.h"
 #include "url/gurl.h"
 
 namespace content {
@@ -70,6 +68,13 @@
   CHECK(instance_info_.empty());
 }
 
+BrowserContext* ServiceWorkerProcessManager::browser_context() {
+  DCHECK_CURRENTLY_ON(BrowserThread::UI);
+  // This is safe because reading |browser_context_| on the UI thread doesn't
+  // need locking (while modifying does).
+  return browser_context_;
+}
+
 void ServiceWorkerProcessManager::Shutdown() {
   DCHECK_CURRENTLY_ON(BrowserThread::UI);
   {
@@ -163,11 +168,6 @@
 
   out_info->process_id = ChildProcessHost::kInvalidUniqueID;
   out_info->is_new_process = false;
-  // Only populate |data_saver_enabled|. In general, this function will populate
-  // settings from prefs, while the caller will be responsible for populating
-  // settings from other sources, such as command line switches.
-  out_info->settings.data_saver_enabled =
-      GetContentClient()->browser()->IsDataSaverEnabled(browser_context_);
 
   if (process_id_for_test_ != ChildProcessHost::kInvalidUniqueID) {
     // Let tests specify the returned process ID. Note: We may need to be able
diff --git a/content/browser/service_worker/service_worker_process_manager.h b/content/browser/service_worker/service_worker_process_manager.h
index b3d7106..606164f 100644
--- a/content/browser/service_worker/service_worker_process_manager.h
+++ b/content/browser/service_worker/service_worker_process_manager.h
@@ -13,7 +13,6 @@
 #include "base/gtest_prod_util.h"
 #include "base/memory/weak_ptr.h"
 #include "base/synchronization/lock.h"
-#include "content/common/service_worker/embedded_worker_settings.h"
 #include "content/common/service_worker/service_worker_status_code.h"
 
 class GURL;
@@ -21,7 +20,6 @@
 namespace content {
 
 class BrowserContext;
-struct EmbeddedWorkerSettings;
 class SiteInstance;
 
 // Interacts with the UI thread to keep RenderProcessHosts alive while the
@@ -40,10 +38,6 @@
     // ServiceWorkerProcessManager's list of known processes.
     // TODO(falken): Fix this.
     bool is_new_process;
-    // Contains known settings for this worker. Currently the caller
-    // should only use |data_saver_enabled| since |v8_cache_options|
-    // remains uninitialized.
-    EmbeddedWorkerSettings settings;
   };
 
   // |*this| must be owned by a ServiceWorkerContextWrapper in a
@@ -53,6 +47,9 @@
   // Shutdown must be called before the ProcessManager is destroyed.
   ~ServiceWorkerProcessManager();
 
+  // Called on the UI thread.
+  BrowserContext* browser_context();
+
   // Synchronously prevents new processes from being allocated
   // and drops references to RenderProcessHosts. Called on the UI thread.
   void Shutdown();
diff --git a/content/renderer/gpu/render_widget_compositor.cc b/content/renderer/gpu/render_widget_compositor.cc
index d7ea7d6..46049eac 100644
--- a/content/renderer/gpu/render_widget_compositor.cc
+++ b/content/renderer/gpu/render_widget_compositor.cc
@@ -777,44 +777,39 @@
 }
 
 void RenderWidgetCompositor::RegisterViewportLayers(
-    const blink::WebLayer* overscroll_elasticity_layer,
-    const blink::WebLayer* page_scale_layer,
-    const blink::WebLayer* inner_viewport_container_layer,
-    const blink::WebLayer* outer_viewport_container_layer,
-    const blink::WebLayer* inner_viewport_scroll_layer,
-    const blink::WebLayer* outer_viewport_scroll_layer) {
+    const blink::WebLayerTreeView::ViewportLayers& layers) {
   cc::LayerTreeHost::ViewportLayers viewport_layers;
   // TODO(bokan): This check can probably be removed now, but it looks
   // like overscroll elasticity may still be nullptr until VisualViewport
   // registers its layers.
-  if (overscroll_elasticity_layer) {
+  if (layers.overscroll_elasticity) {
     viewport_layers.overscroll_elasticity =
-        static_cast<const cc_blink::WebLayerImpl*>(overscroll_elasticity_layer)
+        static_cast<const cc_blink::WebLayerImpl*>(layers.overscroll_elasticity)
             ->layer();
   }
   viewport_layers.page_scale =
-      static_cast<const cc_blink::WebLayerImpl*>(page_scale_layer)->layer();
-  if (inner_viewport_container_layer) {
+      static_cast<const cc_blink::WebLayerImpl*>(layers.page_scale)->layer();
+  if (layers.inner_viewport_container) {
     viewport_layers.inner_viewport_container =
         static_cast<const cc_blink::WebLayerImpl*>(
-            inner_viewport_container_layer)
+            layers.inner_viewport_container)
             ->layer();
   }
-  if (outer_viewport_container_layer) {
+  if (layers.outer_viewport_container) {
     viewport_layers.outer_viewport_container =
         static_cast<const cc_blink::WebLayerImpl*>(
-            outer_viewport_container_layer)
+            layers.outer_viewport_container)
             ->layer();
   }
   viewport_layers.inner_viewport_scroll =
-      static_cast<const cc_blink::WebLayerImpl*>(inner_viewport_scroll_layer)
+      static_cast<const cc_blink::WebLayerImpl*>(layers.inner_viewport_scroll)
           ->layer();
   // TODO(bokan): This check can probably be removed now, but it looks
   // like overscroll elasticity may still be nullptr until VisualViewport
   // registers its layers.
-  if (outer_viewport_scroll_layer) {
+  if (layers.outer_viewport_scroll) {
     viewport_layers.outer_viewport_scroll =
-        static_cast<const cc_blink::WebLayerImpl*>(outer_viewport_scroll_layer)
+        static_cast<const cc_blink::WebLayerImpl*>(layers.outer_viewport_scroll)
             ->layer();
   }
   layer_tree_host_->RegisterViewportLayers(viewport_layers);
diff --git a/content/renderer/gpu/render_widget_compositor.h b/content/renderer/gpu/render_widget_compositor.h
index 84e8a29..372ef4b8 100644
--- a/content/renderer/gpu/render_widget_compositor.h
+++ b/content/renderer/gpu/render_widget_compositor.h
@@ -146,14 +146,8 @@
   void CompositeAndReadbackAsync(
       blink::WebCompositeAndReadbackAsyncCallback* callback) override;
   void SetDeferCommits(bool defer_commits) override;
-  // TODO(pdr): Refactor to use a struct like LayerTreeHost::ViewportLayers.
   void RegisterViewportLayers(
-      const blink::WebLayer* overscrollElasticityLayer,
-      const blink::WebLayer* pageScaleLayer,
-      const blink::WebLayer* innerViewportContainerLayer,
-      const blink::WebLayer* outerViewportContainerLayer,
-      const blink::WebLayer* innerViewportScrollLayer,
-      const blink::WebLayer* outerViewportScrollLayer) override;
+      const blink::WebLayerTreeView::ViewportLayers& viewport_layers) override;
   void ClearViewportLayers() override;
   void RegisterSelection(const blink::WebSelection& selection) override;
   void ClearSelection() override;
diff --git a/content/renderer/media/webrtc/media_stream_remote_video_source.cc b/content/renderer/media/webrtc/media_stream_remote_video_source.cc
index bfadcb9f..3752e68 100644
--- a/content/renderer/media/webrtc/media_stream_remote_video_source.cc
+++ b/content/renderer/media/webrtc/media_stream_remote_video_source.cc
@@ -120,36 +120,36 @@
     video_frame = static_cast<WebRtcVideoFrameAdapter*>(buffer.get())
                       ->getMediaVideoFrame();
     video_frame->set_timestamp(elapsed_timestamp);
-    if (incoming_frame.rotation() != webrtc::kVideoRotation_0) {
-      video_frame->metadata()->SetRotation(
-          media::VideoFrameMetadata::ROTATION,
-          WebRTCToMediaVideoRotation(incoming_frame.rotation()));
-    }
   } else {
-    buffer = webrtc::I420Buffer::Rotate(*incoming_frame.video_frame_buffer(),
-                                        incoming_frame.rotation());
-
-    gfx::Size size(buffer->width(), buffer->height());
-
+    scoped_refptr<webrtc::PlanarYuvBuffer> yuv_buffer;
+    media::VideoPixelFormat pixel_format;
+    if (buffer->type() == webrtc::VideoFrameBuffer::Type::kI444) {
+      yuv_buffer = buffer->GetI444();
+      pixel_format = media::PIXEL_FORMAT_YV24;
+    } else {
+      yuv_buffer = buffer->ToI420();
+      pixel_format = media::PIXEL_FORMAT_YV12;
+    }
+    gfx::Size size(yuv_buffer->width(), yuv_buffer->height());
     // Make a shallow copy. Both |frame| and |video_frame| will share a single
     // reference counted frame buffer. Const cast and hope no one will overwrite
     // the data.
-    // TODO(magjed): Update media::VideoFrame to support const data so we don't
-    // need to const cast here.
-    rtc::scoped_refptr<const webrtc::I420BufferInterface> i420_buffer =
-        buffer->ToI420();
     video_frame = media::VideoFrame::WrapExternalYuvData(
-        media::PIXEL_FORMAT_YV12, size, gfx::Rect(size), size,
-        i420_buffer->StrideY(), i420_buffer->StrideU(), i420_buffer->StrideV(),
-        const_cast<uint8_t*>(i420_buffer->DataY()),
-        const_cast<uint8_t*>(i420_buffer->DataU()),
-        const_cast<uint8_t*>(i420_buffer->DataV()), elapsed_timestamp);
+        pixel_format, size, gfx::Rect(size), size, yuv_buffer->StrideY(),
+        yuv_buffer->StrideU(), yuv_buffer->StrideV(),
+        const_cast<uint8_t*>(yuv_buffer->DataY()),
+        const_cast<uint8_t*>(yuv_buffer->DataU()),
+        const_cast<uint8_t*>(yuv_buffer->DataV()), elapsed_timestamp);
     if (!video_frame)
       return;
     // The bind ensures that we keep a reference to the underlying buffer.
     video_frame->AddDestructionObserver(base::Bind(&DoNothing, buffer));
   }
-
+  if (incoming_frame.rotation() != webrtc::kVideoRotation_0) {
+    video_frame->metadata()->SetRotation(
+        media::VideoFrameMetadata::ROTATION,
+        WebRTCToMediaVideoRotation(incoming_frame.rotation()));
+  }
   video_frame->metadata()->SetTimeTicks(
       media::VideoFrameMetadata::REFERENCE_TIME, render_time);
 
diff --git a/gin/public/v8_platform.h b/gin/public/v8_platform.h
index 9bcc57894..e86f77d5 100644
--- a/gin/public/v8_platform.h
+++ b/gin/public/v8_platform.h
@@ -31,28 +31,6 @@
                                   v8::IdleTask* task) override;
   bool IdleTasksEnabled(v8::Isolate* isolate) override;
   double MonotonicallyIncreasingTime() override;
-  const uint8_t* GetCategoryGroupEnabled(const char* name) override;
-  const char* GetCategoryGroupName(
-      const uint8_t* category_enabled_flag) override;
-  uint64_t AddTraceEvent(
-      char phase,
-      const uint8_t* category_enabled_flag,
-      const char* name,
-      const char* scope,
-      uint64_t id,
-      uint64_t bind_id,
-      int32_t num_args,
-      const char** arg_names,
-      const uint8_t* arg_types,
-      const uint64_t* arg_values,
-      std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertibles,
-      unsigned int flags) override;
-  void UpdateTraceEventDuration(const uint8_t* category_enabled_flag,
-                                const char* name,
-                                uint64_t handle) override;
-
-  void AddTraceStateObserver(v8::Platform::TraceStateObserver*) override;
-  void RemoveTraceStateObserver(v8::Platform::TraceStateObserver*) override;
   StackTracePrinter GetStackTracePrinter() override;
   v8::TracingController* GetTracingController() override;
 
diff --git a/gin/v8_platform.cc b/gin/v8_platform.cc
index fd0ef94..f06e60c 100644
--- a/gin/v8_platform.cc
+++ b/gin/v8_platform.cc
@@ -261,51 +261,6 @@
   return tracing_controller_.get();
 }
 
-const uint8_t* V8Platform::GetCategoryGroupEnabled(const char* name) {
-  return tracing_controller_->GetCategoryGroupEnabled(name);
-}
-
-const char* V8Platform::GetCategoryGroupName(
-    const uint8_t* category_enabled_flag) {
-  return base::trace_event::TraceLog::GetCategoryGroupName(
-      category_enabled_flag);
-}
-
-uint64_t V8Platform::AddTraceEvent(
-    char phase,
-    const uint8_t* category_enabled_flag,
-    const char* name,
-    const char* scope,
-    uint64_t id,
-    uint64_t bind_id,
-    int32_t num_args,
-    const char** arg_names,
-    const uint8_t* arg_types,
-    const uint64_t* arg_values,
-    std::unique_ptr<v8::ConvertableToTraceFormat>* arg_convertables,
-    unsigned int flags) {
-  return tracing_controller_->AddTraceEvent(
-      phase, category_enabled_flag, name, scope, id, bind_id, num_args,
-      arg_names, arg_types, arg_values, arg_convertables, flags);
-}
-
-void V8Platform::UpdateTraceEventDuration(const uint8_t* category_enabled_flag,
-                                          const char* name,
-                                          uint64_t handle) {
-  tracing_controller_->UpdateTraceEventDuration(category_enabled_flag, name,
-                                                handle);
-}
-
-void V8Platform::AddTraceStateObserver(
-    v8::Platform::TraceStateObserver* observer) {
-  tracing_controller_->AddTraceStateObserver(observer);
-}
-
-void V8Platform::RemoveTraceStateObserver(
-    v8::Platform::TraceStateObserver* observer) {
-  tracing_controller_->RemoveTraceStateObserver(observer);
-}
-
 v8::Platform::StackTracePrinter V8Platform::GetStackTracePrinter() {
   return PrintStackTrace;
 }
diff --git a/gin/v8_platform_unittest.cc b/gin/v8_platform_unittest.cc
index 52d58624..e3643d3da 100644
--- a/gin/v8_platform_unittest.cc
+++ b/gin/v8_platform_unittest.cc
@@ -27,7 +27,8 @@
   ASSERT_EQ(0, test_observer->Enabled());
   ASSERT_EQ(0, test_observer->Disabled());
 
-  V8Platform::Get()->AddTraceStateObserver(test_observer);
+  V8Platform::Get()->GetTracingController()->AddTraceStateObserver(
+      test_observer);
   base::trace_event::TraceLog::GetInstance()->SetEnabled(
       base::trace_event::TraceConfig("*", ""),
       base::trace_event::TraceLog::RECORDING_MODE);
@@ -37,7 +38,8 @@
   ASSERT_EQ(1, test_observer->Enabled());
   ASSERT_EQ(1, test_observer->Disabled());
 
-  V8Platform::Get()->RemoveTraceStateObserver(test_observer);
+  V8Platform::Get()->GetTracingController()->RemoveTraceStateObserver(
+      test_observer);
   base::trace_event::TraceLog::GetInstance()->SetEnabled(
       base::trace_event::TraceConfig("*", ""),
       base::trace_event::TraceLog::RECORDING_MODE);
@@ -54,7 +56,8 @@
   base::trace_event::TraceLog::GetInstance()->SetEnabled(
       base::trace_event::TraceConfig("*", ""),
       base::trace_event::TraceLog::RECORDING_MODE);
-  V8Platform::Get()->AddTraceStateObserver(test_observer);
+  V8Platform::Get()->GetTracingController()->AddTraceStateObserver(
+      test_observer);
   ASSERT_EQ(1, test_observer->Enabled());
   ASSERT_EQ(0, test_observer->Disabled());
 }
diff --git a/ios/showcase/BUILD.gn b/ios/showcase/BUILD.gn
index 71212a2..e4f750da 100644
--- a/ios/showcase/BUILD.gn
+++ b/ios/showcase/BUILD.gn
@@ -14,6 +14,7 @@
   output_name = "Showcase"
   deps = [
     ":features",
+    ":packed_resources",
     "//ios/showcase/core:main",
 
     # All shared libraries must have the sanitizer deps to properly link in
diff --git a/media/blink/webcontentdecryptionmodule_impl.cc b/media/blink/webcontentdecryptionmodule_impl.cc
index 99e07cb..d5b872b 100644
--- a/media/blink/webcontentdecryptionmodule_impl.cc
+++ b/media/blink/webcontentdecryptionmodule_impl.cc
@@ -101,6 +101,15 @@
           new CdmResultPromise<>(result, std::string())));
 }
 
+void WebContentDecryptionModuleImpl::GetStatusForPolicy(
+    const blink::WebString& /* min_hdcp_version */,
+    blink::WebContentDecryptionModuleResult result) {
+  NOTIMPLEMENTED();
+  result.CompleteWithError(
+      blink::kWebContentDecryptionModuleExceptionNotSupportedError, 0,
+      "Not Implemented");
+}
+
 scoped_refptr<ContentDecryptionModule>
 WebContentDecryptionModuleImpl::GetCdm() {
   return adapter_->GetCdm();
diff --git a/media/blink/webcontentdecryptionmodule_impl.h b/media/blink/webcontentdecryptionmodule_impl.h
index ab9d111c..8152d95 100644
--- a/media/blink/webcontentdecryptionmodule_impl.h
+++ b/media/blink/webcontentdecryptionmodule_impl.h
@@ -48,6 +48,10 @@
       size_t server_certificate_length,
       blink::WebContentDecryptionModuleResult result) override;
 
+  void GetStatusForPolicy(
+      const blink::WebString& min_hdcp_version,
+      blink::WebContentDecryptionModuleResult result) override;
+
   // Returns a reference to the CDM used by |adapter_|.
   scoped_refptr<ContentDecryptionModule> GetCdm();
 
diff --git a/third_party/WebKit/LayoutTests/W3CImportExpectations b/third_party/WebKit/LayoutTests/W3CImportExpectations
index f65ac1f..3534e37 100644
--- a/third_party/WebKit/LayoutTests/W3CImportExpectations
+++ b/third_party/WebKit/LayoutTests/W3CImportExpectations
@@ -510,13 +510,6 @@
 external/wpt/html/semantics/embedded-content/the-video-element/video_dynamic_poster_relative.htm [ Skip ]
 external/wpt/html/semantics/embedded-content/the-video-element/video_initially_paused.html [ Skip ]
 
-# crbug.com/493537: Need to support SVG reference tests
-external/wpt/html/editing/the-hidden-attribute/hidden-2.svg [ Skip ]
-external/wpt/svg/shapes/rect-01.svg [ Skip ]
-external/wpt/svg/shapes/rect-02.svg [ Skip ]
-external/wpt/svg/shapes/rect-03.svg [ Skip ]
-external/wpt/svg/shapes/rect-04.svg [ Skip ]
-
 # The outputs of these tests contain random values generated by token()
 # in common/utils.js. These could be imported if the results for
 # testharness tests just had pass/fail but no console error messages.
diff --git a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
index cf4096c..91fc5cf 100644
--- a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
+++ b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
@@ -58451,6 +58451,18 @@
      {}
     ]
    ],
+   "html/editing/the-hidden-attribute/hidden-2.svg": [
+    [
+     "/html/editing/the-hidden-attribute/hidden-2.svg",
+     [
+      [
+       "/html/editing/the-hidden-attribute/hidden-2-ref.svg",
+       "=="
+      ]
+     ],
+     {}
+    ]
+   ],
    "html/rendering/bindings/the-button-element/button-type-menu-historical.html": [
     [
      "/html/rendering/bindings/the-button-element/button-type-menu-historical.html",
@@ -60215,6 +60227,54 @@
      {}
     ]
    ],
+   "svg/shapes/rect-01.svg": [
+    [
+     "/svg/shapes/rect-01.svg",
+     [
+      [
+       "/svg/shapes/rect-01-ref.html",
+       "=="
+      ]
+     ],
+     {}
+    ]
+   ],
+   "svg/shapes/rect-02.svg": [
+    [
+     "/svg/shapes/rect-02.svg",
+     [
+      [
+       "/svg/shapes/rect-02-ref.html",
+       "=="
+      ]
+     ],
+     {}
+    ]
+   ],
+   "svg/shapes/rect-03.svg": [
+    [
+     "/svg/shapes/rect-03.svg",
+     [
+      [
+       "/svg/shapes/rect-03-ref.html",
+       "=="
+      ]
+     ],
+     {}
+    ]
+   ],
+   "svg/shapes/rect-04.svg": [
+    [
+     "/svg/shapes/rect-04.svg",
+     [
+      [
+       "/svg/shapes/rect-04-ref.html",
+       "=="
+      ]
+     ],
+     {}
+    ]
+   ],
    "webvtt/rendering/cues-with-video/processing-model/2_cues_overlapping_completely_move_up.html": [
     [
      "/webvtt/rendering/cues-with-video/processing-model/2_cues_overlapping_completely_move_up.html",
@@ -232278,6 +232338,10 @@
    "156d89a99a6d53e519ecf339c5103fcccae153cc",
    "support"
   ],
+  "html/editing/the-hidden-attribute/hidden-2.svg": [
+   "175e662819cfcc1f528fd8c0e3ed149eeba02e70",
+   "reftest"
+  ],
   "html/iana/.gitkeep": [
    "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "support"
@@ -262034,18 +262098,34 @@
    "f22176bd9807ed4a8cb38ce8481e1aaaecd6bb9b",
    "support"
   ],
+  "svg/shapes/rect-01.svg": [
+   "45810896c5c9277a9819370556ab7182c8658db7",
+   "reftest"
+  ],
   "svg/shapes/rect-02-ref.html": [
    "8e75f5197a795d6e5bc2e4854e6f23aa74581c36",
    "support"
   ],
+  "svg/shapes/rect-02.svg": [
+   "a6e45779acfe8dd81e1f48361ec685776af8e267",
+   "reftest"
+  ],
   "svg/shapes/rect-03-ref.html": [
    "5b061cb67ee99b7e45719c150c118e50f1e8f6ae",
    "support"
   ],
+  "svg/shapes/rect-03.svg": [
+   "d938868c4bc93b7f6245c3ee97eaa85f84fa7f9d",
+   "reftest"
+  ],
   "svg/shapes/rect-04-ref.html": [
    "4ef700957bf1643511f66a9a8a57810fb2eadfed",
    "support"
   ],
+  "svg/shapes/rect-04.svg": [
+   "ad79ad2f821e30c3c016bb1e156c1fafb4a4decf",
+   "reftest"
+  ],
   "touch-events/OWNERS": [
    "a4fed30c25d50d5ce774e4e5b431efa99f73ecf3",
    "support"
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/editing/the-hidden-attribute/hidden-2.svg b/third_party/WebKit/LayoutTests/external/wpt/html/editing/the-hidden-attribute/hidden-2.svg
new file mode 100644
index 0000000..a5f08f6
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/external/wpt/html/editing/the-hidden-attribute/hidden-2.svg
@@ -0,0 +1,12 @@
+<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20">
+<metadata>
+  <link xmlns="http://www.w3.org/1999/xhtml" rel="match" href="hidden-2-ref.svg" />
+  <link xmlns="http://www.w3.org/1999/xhtml" rel="author" title="Ms2ger"
+        href="mailto:Ms2ger@gmail.com"/>
+  <link xmlns="http://www.w3.org/1999/xhtml" rel="help"
+        href="https://html.spec.whatwg.org/multipage/#the-hidden-attribute"/>
+  <link xmlns="http://www.w3.org/1999/xhtml" rel="help"
+        href="https://html.spec.whatwg.org/multipage/#hidden-elements"/>
+</metadata>
+<rect hidden="" height="20" width="20"/>
+</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-01.svg b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-01.svg
new file mode 100644
index 0000000..a580807
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-01.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+  <metadata>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="author" title="Cameron McCormack" href="mailto:cam@mcc.id.au"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="help" href="http://www.w3.org/TR/SVG2/shapes.html#RectElement"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="match" href="rect-01-ref.html"/>
+    <meta xmlns="http://www.w3.org/1999/xhtml" name="assert" content="rect element renders correctly."/>
+  </metadata>
+  <rect x="10" y="10" width="50" height="50" fill="blue"/>
+</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-02.svg b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-02.svg
new file mode 100644
index 0000000..123203e
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-02.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+  <metadata>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="author" title="Cameron McCormack" href="mailto:cam@mcc.id.au"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="help" href="http://www.w3.org/TR/SVG2/shapes.html#RectElement"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="match" href="rect-02-ref.html"/>
+    <meta xmlns="http://www.w3.org/1999/xhtml" name="assert" content="rect element with stroke renders correctly."/>
+  </metadata>
+  <rect x="10" y="10" width="50" height="50" fill="none" stroke="blue" stroke-width="4"/>
+</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-03.svg b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-03.svg
new file mode 100644
index 0000000..f4b59c91
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-03.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+  <metadata>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="author" title="Cameron McCormack" href="mailto:cam@mcc.id.au"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="help" href="http://www.w3.org/TR/SVG2/shapes.html#RectElement"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="match" href="rect-03-ref.html"/>
+    <meta xmlns="http://www.w3.org/1999/xhtml" name="assert" content="rect element with rounded corners renders correctly."/>
+  </metadata>
+  <rect x="10" y="10" width="50" height="50" rx="8" ry="8" fill="blue"/>
+</svg>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-04.svg b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-04.svg
new file mode 100644
index 0000000..37c4c9b
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/external/wpt/svg/shapes/rect-04.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg">
+  <metadata>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="author" title="Cameron McCormack" href="mailto:cam@mcc.id.au"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="help" href="http://www.w3.org/TR/SVG2/shapes.html#RectElement"/>
+    <link xmlns="http://www.w3.org/1999/xhtml" rel="match" href="rect-04-ref.html"/>
+    <meta xmlns="http://www.w3.org/1999/xhtml" name="assert" content="rect element with rounded corners and stroke renders correctly."/>
+  </metadata>
+  <rect x="10" y="10" width="50" height="50" rx="8" ry="8" fill="none" stroke="blue" stroke-width="4"/>
+</svg>
diff --git a/third_party/WebKit/LayoutTests/fast/forms/image/fallback-reattach-crash.html b/third_party/WebKit/LayoutTests/fast/forms/image/fallback-reattach-crash.html
new file mode 100644
index 0000000..46675469
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/fast/forms/image/fallback-reattach-crash.html
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<script src="dummy"></script>
+<input type="image" src="dummy">
+<script src="dummy"></script>
+<script src="../../../resources/testharness.js"></script>
+<script src="../../../resources/testharnessreport.js"></script>
+<script>
+  test(() => document.body.offsetTop, "Pass if test does not crash.");
+</script>
diff --git a/third_party/WebKit/LayoutTests/fast/sub-pixel/input-caret-on-subpixel-bound-expected.html b/third_party/WebKit/LayoutTests/fast/sub-pixel/input-caret-on-subpixel-bound-expected.html
index 4c24240..93a2148c 100644
--- a/third_party/WebKit/LayoutTests/fast/sub-pixel/input-caret-on-subpixel-bound-expected.html
+++ b/third_party/WebKit/LayoutTests/fast/sub-pixel/input-caret-on-subpixel-bound-expected.html
@@ -7,10 +7,10 @@
           font-family: sans-serif;
       }
       table {
-          padding: 2px 2px 2px 2px;
+          padding: 2px 3px 3px 2px;
       }
       input {
-          padding: 5px 6px 6px 5px;
+          padding: 6px 6px 5px 5px;
       }
     </style>
   </head>
diff --git a/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-expected.png b/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-expected.png
index 04272d5..78ba1ba 100644
--- a/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-expected.png
+++ b/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-quirks-mode-expected.png b/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-quirks-mode-expected.png
index 04272d5..78ba1ba 100644
--- a/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-quirks-mode-expected.png
+++ b/third_party/WebKit/LayoutTests/fast/table/table-in-table-percent-width-collapsing-border-quirks-mode-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/media/encrypted-media/encrypted-media-getstatusforpolicy.html b/third_party/WebKit/LayoutTests/media/encrypted-media/encrypted-media-getstatusforpolicy.html
new file mode 100644
index 0000000..9da47f6
--- /dev/null
+++ b/third_party/WebKit/LayoutTests/media/encrypted-media/encrypted-media-getstatusforpolicy.html
@@ -0,0 +1,62 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>MediaKeys.getStatusForPolicy</title>
+        <script src="encrypted-media-utils.js"></script>
+        <script src="../../resources/testharness.js"></script>
+        <script src="../../resources/testharnessreport.js"></script>
+    </head>
+    <body>
+        <script>
+            promise_test(function(test)
+            {
+                var hdcpVersionNone = "";
+                var hdcpVersion2_0 = "hdcp-2.0";
+                var mediaKeys;
+
+                function checkMediaKeysPolicyConstruction() {
+                  var policy = new MediaKeysPolicy({minHdcpVersion: hdcpVersionNone});
+                  assert_equals(policy.minHdcpVersion, hdcpVersionNone);
+
+                  policy = new MediaKeysPolicy({minHdcpVersion: hdcpVersion2_0});
+                  assert_equals(policy.minHdcpVersion, hdcpVersion2_0);
+
+                  policy = new MediaKeysPolicy({minHdcpVersion: hdcpVersion2_0, foo: "bar"});
+                  assert_equals(policy.minHdcpVersion, hdcpVersion2_0);
+                  assert_false('foo' in policy);
+
+                  policy = new MediaKeysPolicy({foo: "bar"});
+                  assert_equals(policy.minHdcpVersion, hdcpVersionNone);
+                  assert_false('foo' in policy);
+
+                  return Promise.resolve();
+                }
+
+                function getStatusForHdcpPolicy(hdcpVersion)
+                {
+                    var policy = new MediaKeysPolicy({minHdcpVersion: hdcpVersion});
+                    mediaKeys.getStatusForPolicy(policy).then(function(MediaKeyStatus) {
+                      // getStatusForPolicy() is not supported by Clear Key key
+                      // system and the promise should always be rejected with
+                      // NotSupportedError.
+                      return Promise.reject("Promise resolved unexpectedly");
+                    }, function(error) {
+                      assert_equals(error.name, "NotSupportedError");
+                      return Promise.resolve();
+                    });
+                }
+
+                return navigator.requestMediaKeySystemAccess('org.w3.clearkey', getSimpleConfiguration()).then(function(access) {
+                    return access.createMediaKeys();
+                }).then(function(result) {
+                    mediaKeys = result;
+                    return checkMediaKeysPolicyConstruction();
+                }).then(function() {
+                    return getStatusForHdcpPolicy(hdcpVersionNone);
+                }).then(function() {
+                    return getStatusForHdcpPolicy(hdcpVersion2_0);
+                });
+            }, 'MediaKeys.getStatusForPolicy');
+        </script>
+    </body>
+</html>
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
index b7a8662c..59f61c5 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
index 71d96ef..772f112e 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
@@ -3,103 +3,103 @@
 layer at (0,0) size 800x339
   LayoutBlockFlow {HTML} at (0,0) size 800x339.09
     LayoutBlockFlow {BODY} at (5.55,5.55) size 788.91x328
-      LayoutTable {TABLE} at (0,0) size 456x328
-        LayoutTableSection {TBODY} at (0,0) size 456x328
-          LayoutTableRow {TR} at (0,1) size 456x14
-            LayoutTableCell {TH} at (1,1) size 63x14 [bgcolor=#DDDD99] [r=0 c=0 rs=1 cs=1]
-              LayoutText {#text} at (5,0) size 53x14
-                text run at (5,0) width 53: "viewBox?"
-            LayoutTableCell {TH} at (65,1) size 110x14 [bgcolor=#DDDD99] [r=0 c=1 rs=1 cs=1]
-              LayoutText {#text} at (0,0) size 110x14
-                text run at (0,0) width 110: "preserve\x{AD}Aspect\x{AD}Ratio"
-            LayoutTableCell {TH} at (176,1) size 139x14 [bgcolor=#DDDD99] [r=0 c=2 rs=1 cs=1]
-              LayoutText {#text} at (53,0) size 33x14
-                text run at (53,0) width 33: "<img>"
-            LayoutTableCell {TH} at (316,1) size 139x14 [bgcolor=#DDDD99] [r=0 c=3 rs=1 cs=1]
-              LayoutText {#text} at (47,0) size 45x14
-                text run at (47,0) width 45: "<object>"
-          LayoutTableRow {TR} at (0,16) size 456x38
-            LayoutTableCell {TH} at (1,86) size 63x14 [bgcolor=#DDDD99] [r=1 c=0 rs=4 cs=1]
-              LayoutText {#text} at (0,0) size 63x14
-                text run at (0,0) width 63: "No viewBox"
-            LayoutTableCell {TH} at (65,35) size 110x0 [bgcolor=#DDDD99] [r=1 c=1 rs=1 cs=1]
-            LayoutTableCell {TD} at (176,16) size 139x38 [r=1 c=2 rs=1 cs=1]
+      LayoutTable {TABLE} at (0,0) size 460x328
+        LayoutTableSection {TBODY} at (0,0) size 460x328
+          LayoutTableRow {TR} at (0,1) size 460x14
+            LayoutTableCell {TH} at (1,1) size 64x14 [bgcolor=#DDDD99] [r=0 c=0 rs=1 cs=1]
+              LayoutText {#text} at (6,0) size 52x14
+                text run at (6,0) width 52: "viewBox?"
+            LayoutTableCell {TH} at (66,1) size 111x14 [bgcolor=#DDDD99] [r=0 c=1 rs=1 cs=1]
+              LayoutText {#text} at (0,0) size 111x14
+                text run at (0,0) width 111: "preserve\x{AD}Aspect\x{AD}Ratio"
+            LayoutTableCell {TH} at (178,1) size 140x14 [bgcolor=#DDDD99] [r=0 c=2 rs=1 cs=1]
+              LayoutText {#text} at (54,0) size 32x14
+                text run at (54,0) width 32: "<img>"
+            LayoutTableCell {TH} at (319,1) size 140x14 [bgcolor=#DDDD99] [r=0 c=3 rs=1 cs=1]
+              LayoutText {#text} at (47,0) size 46x14
+                text run at (47,0) width 46: "<object>"
+          LayoutTableRow {TR} at (0,16) size 460x38
+            LayoutTableCell {TH} at (1,86) size 64x14 [bgcolor=#DDDD99] [r=1 c=0 rs=4 cs=1]
+              LayoutText {#text} at (0,0) size 64x14
+                text run at (0,0) width 64: "No viewBox"
+            LayoutTableCell {TH} at (66,35) size 111x0 [bgcolor=#DDDD99] [r=1 c=1 rs=1 cs=1]
+            LayoutTableCell {TD} at (178,16) size 140x38 [r=1 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,16) size 139x38 [r=1 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,16) size 140x38 [r=1 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,55) size 456x38
-            LayoutTableCell {TH} at (65,67) size 110x14 [bgcolor=#DDDD99] [r=2 c=1 rs=1 cs=1]
-              LayoutText {#text} at (41,0) size 28x14
-                text run at (41,0) width 28: "none"
-            LayoutTableCell {TD} at (176,55) size 139x38 [r=2 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,55) size 460x38
+            LayoutTableCell {TH} at (66,67) size 111x14 [bgcolor=#DDDD99] [r=2 c=1 rs=1 cs=1]
+              LayoutText {#text} at (42,0) size 27x14
+                text run at (42,0) width 27: "none"
+            LayoutTableCell {TD} at (178,55) size 140x38 [r=2 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,55) size 139x38 [r=2 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,55) size 140x38 [r=2 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,94) size 456x38
-            LayoutTableCell {TH} at (65,106) size 110x14 [bgcolor=#DDDD99] [r=3 c=1 rs=1 cs=1]
-              LayoutText {#text} at (42,0) size 26x14
-                text run at (42,0) width 26: "meet"
-            LayoutTableCell {TD} at (176,94) size 139x38 [r=3 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,94) size 460x38
+            LayoutTableCell {TH} at (66,106) size 111x14 [bgcolor=#DDDD99] [r=3 c=1 rs=1 cs=1]
+              LayoutText {#text} at (42,0) size 27x14
+                text run at (42,0) width 27: "meet"
+            LayoutTableCell {TD} at (178,94) size 140x38 [r=3 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,94) size 139x38 [r=3 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,94) size 140x38 [r=3 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,133) size 456x38
-            LayoutTableCell {TH} at (65,145) size 110x14 [bgcolor=#DDDD99] [r=4 c=1 rs=1 cs=1]
-              LayoutText {#text} at (43,0) size 24x14
-                text run at (43,0) width 24: "slice"
-            LayoutTableCell {TD} at (176,133) size 139x38 [r=4 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,133) size 460x38
+            LayoutTableCell {TH} at (66,145) size 111x14 [bgcolor=#DDDD99] [r=4 c=1 rs=1 cs=1]
+              LayoutText {#text} at (43,0) size 25x14
+                text run at (43,0) width 25: "slice"
+            LayoutTableCell {TD} at (178,133) size 140x38 [r=4 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,133) size 139x38 [r=4 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,133) size 140x38 [r=4 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,172) size 456x38
-            LayoutTableCell {TH} at (1,242) size 63x14 [bgcolor=#DDDD99] [r=5 c=0 rs=4 cs=1]
-              LayoutText {#text} at (9,0) size 45x14
-                text run at (9,0) width 45: "viewBox"
-            LayoutTableCell {TH} at (65,191) size 110x0 [bgcolor=#DDDD99] [r=5 c=1 rs=1 cs=1]
-            LayoutTableCell {TD} at (176,172) size 139x38 [r=5 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,172) size 460x38
+            LayoutTableCell {TH} at (1,242) size 64x14 [bgcolor=#DDDD99] [r=5 c=0 rs=4 cs=1]
+              LayoutText {#text} at (9,0) size 46x14
+                text run at (9,0) width 46: "viewBox"
+            LayoutTableCell {TH} at (66,191) size 111x0 [bgcolor=#DDDD99] [r=5 c=1 rs=1 cs=1]
+            LayoutTableCell {TD} at (178,172) size 140x38 [r=5 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,172) size 139x38 [r=5 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,172) size 140x38 [r=5 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,211) size 456x38
-            LayoutTableCell {TH} at (65,223) size 110x14 [bgcolor=#DDDD99] [r=6 c=1 rs=1 cs=1]
-              LayoutText {#text} at (41,0) size 28x14
-                text run at (41,0) width 28: "none"
-            LayoutTableCell {TD} at (176,211) size 139x38 [r=6 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,211) size 460x38
+            LayoutTableCell {TH} at (66,223) size 111x14 [bgcolor=#DDDD99] [r=6 c=1 rs=1 cs=1]
+              LayoutText {#text} at (42,0) size 27x14
+                text run at (42,0) width 27: "none"
+            LayoutTableCell {TD} at (178,211) size 140x38 [r=6 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,211) size 139x38 [r=6 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,211) size 140x38 [r=6 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,250) size 456x38
-            LayoutTableCell {TH} at (65,262) size 110x14 [bgcolor=#DDDD99] [r=7 c=1 rs=1 cs=1]
-              LayoutText {#text} at (42,0) size 26x14
-                text run at (42,0) width 26: "meet"
-            LayoutTableCell {TD} at (176,250) size 139x38 [r=7 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,250) size 460x38
+            LayoutTableCell {TH} at (66,262) size 111x14 [bgcolor=#DDDD99] [r=7 c=1 rs=1 cs=1]
+              LayoutText {#text} at (42,0) size 27x14
+                text run at (42,0) width 27: "meet"
+            LayoutTableCell {TD} at (178,250) size 140x38 [r=7 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,250) size 139x38 [r=7 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,250) size 140x38 [r=7 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,289) size 456x38
-            LayoutTableCell {TH} at (65,301) size 110x14 [bgcolor=#DDDD99] [r=8 c=1 rs=1 cs=1]
-              LayoutText {#text} at (43,0) size 24x14
-                text run at (43,0) width 24: "slice"
-            LayoutTableCell {TD} at (176,289) size 139x38 [r=8 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,289) size 460x38
+            LayoutTableCell {TH} at (66,301) size 111x14 [bgcolor=#DDDD99] [r=8 c=1 rs=1 cs=1]
+              LayoutText {#text} at (43,0) size 25x14
+                text run at (43,0) width 25: "slice"
+            LayoutTableCell {TD} at (178,289) size 140x38 [r=8 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (316,289) size 139x38 [r=8 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (319,289) size 140x38 [r=8 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-layer at (322,22) size 139x35
+layer at (325,22) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
     layer at (0,0) size 133x29
       LayoutSVGRoot {svg} at (0,0) size 133x29
         LayoutSVGEllipse {circle} at (0,0) size 220x220 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [cx=110.00] [cy=110.00] [r=110.00]
-layer at (322,61) size 139x35
+layer at (325,61) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -108,7 +108,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (322,100) size 139x35
+layer at (325,100) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -117,7 +117,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (322,139) size 139x35
+layer at (325,139) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -126,7 +126,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (322,178) size 139x35
+layer at (325,178) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -135,7 +135,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (322,217) size 139x35
+layer at (325,217) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -144,7 +144,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (322,256) size 139x35
+layer at (325,256) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -153,7 +153,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (322,295) size 139x35
+layer at (325,295) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
index 79edb450..f1843ef 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
index a6523bb..7aae683 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x199
   LayoutBlockFlow {html} at (0,0) size 800x199.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x188
-      LayoutTable {table} at (143.45,0) size 502x188
-        LayoutTableSection (anonymous) at (0,0) size 502x188
-          LayoutTableRow {tr} at (0,0) size 502x188
-            LayoutTableCell {td} at (0,0) size 502x188 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 490x176
-                LayoutTableSection (anonymous) at (0,0) size 490x176
-                  LayoutTableRow {tr} at (0,1) size 490x66
-                    LayoutTableCell {td} at (1,1) size 488x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 478x26
-                        LayoutText {#text} at (0,0) size 478x25
-                          text run at (0,0) width 478: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 490x24
-                    LayoutTableCell {td} at (1,68) size 243x24 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (94,5) size 55x14
-                        text run at (94,5) width 55: "SVG Image"
-                    LayoutTableCell {td} at (245,68) size 244x24 [r=1 c=1 rs=1 cs=1]
+      LayoutTable {table} at (142.45,0) size 504x188
+        LayoutTableSection (anonymous) at (0,0) size 504x188
+          LayoutTableRow {tr} at (0,0) size 504x188
+            LayoutTableCell {td} at (0,0) size 504x188 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 491x176
+                LayoutTableSection (anonymous) at (0,0) size 491x176
+                  LayoutTableRow {tr} at (0,1) size 491x66
+                    LayoutTableCell {td} at (1,1) size 489x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 479x26
+                        LayoutText {#text} at (0,0) size 479x25
+                          text run at (0,0) width 479: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 491x24
+                    LayoutTableCell {td} at (1,68) size 244x24 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (95,5) size 54x14
+                        text run at (95,5) width 54: "SVG Image"
+                    LayoutTableCell {td} at (246,68) size 244x24 [r=1 c=1 rs=1 cs=1]
                       LayoutText {#text} at (95,5) size 54x14
                         text run at (95,5) width 54: "PNG Image"
-                  LayoutTableRow {tr} at (0,93) size 490x82
-                    LayoutTableCell {td} at (1,93) size 243x82 [r=2 c=0 rs=1 cs=1]
+                  LayoutTableRow {tr} at (0,93) size 491x82
+                    LayoutTableCell {td} at (1,93) size 244x82 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (245,93) size 244x82 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (246,93) size 244x82 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 138.88x69.44
                       LayoutText {#text} at (0,0) size 0x0
-layer at (255,110) size 139x69
-  LayoutEmbeddedObject {object} at (99.13,5) size 138.88x69.44
+layer at (257,110) size 139x69
+  LayoutEmbeddedObject {object} at (100.13,5) size 138.88x69.44
     layer at (0,0) size 139x69
       LayoutView at (0,0) size 139x69
     layer at (0,0) size 139x69
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
index 79edb450..f1843ef 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
index a6523bb..7aae683 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x199
   LayoutBlockFlow {html} at (0,0) size 800x199.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x188
-      LayoutTable {table} at (143.45,0) size 502x188
-        LayoutTableSection (anonymous) at (0,0) size 502x188
-          LayoutTableRow {tr} at (0,0) size 502x188
-            LayoutTableCell {td} at (0,0) size 502x188 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 490x176
-                LayoutTableSection (anonymous) at (0,0) size 490x176
-                  LayoutTableRow {tr} at (0,1) size 490x66
-                    LayoutTableCell {td} at (1,1) size 488x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 478x26
-                        LayoutText {#text} at (0,0) size 478x25
-                          text run at (0,0) width 478: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 490x24
-                    LayoutTableCell {td} at (1,68) size 243x24 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (94,5) size 55x14
-                        text run at (94,5) width 55: "SVG Image"
-                    LayoutTableCell {td} at (245,68) size 244x24 [r=1 c=1 rs=1 cs=1]
+      LayoutTable {table} at (142.45,0) size 504x188
+        LayoutTableSection (anonymous) at (0,0) size 504x188
+          LayoutTableRow {tr} at (0,0) size 504x188
+            LayoutTableCell {td} at (0,0) size 504x188 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 491x176
+                LayoutTableSection (anonymous) at (0,0) size 491x176
+                  LayoutTableRow {tr} at (0,1) size 491x66
+                    LayoutTableCell {td} at (1,1) size 489x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 479x26
+                        LayoutText {#text} at (0,0) size 479x25
+                          text run at (0,0) width 479: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 491x24
+                    LayoutTableCell {td} at (1,68) size 244x24 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (95,5) size 54x14
+                        text run at (95,5) width 54: "SVG Image"
+                    LayoutTableCell {td} at (246,68) size 244x24 [r=1 c=1 rs=1 cs=1]
                       LayoutText {#text} at (95,5) size 54x14
                         text run at (95,5) width 54: "PNG Image"
-                  LayoutTableRow {tr} at (0,93) size 490x82
-                    LayoutTableCell {td} at (1,93) size 243x82 [r=2 c=0 rs=1 cs=1]
+                  LayoutTableRow {tr} at (0,93) size 491x82
+                    LayoutTableCell {td} at (1,93) size 244x82 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (245,93) size 244x82 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (246,93) size 244x82 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 138.88x69.44
                       LayoutText {#text} at (0,0) size 0x0
-layer at (255,110) size 139x69
-  LayoutEmbeddedObject {object} at (99.13,5) size 138.88x69.44
+layer at (257,110) size 139x69
+  LayoutEmbeddedObject {object} at (100.13,5) size 138.88x69.44
     layer at (0,0) size 139x69
       LayoutView at (0,0) size 139x69
     layer at (0,0) size 139x69
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
index e392a14..c457613 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
index 1c465e5..3db7cd7 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/linux/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x380
   LayoutBlockFlow {html} at (0,0) size 800x380.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x369
-      LayoutTable {table} at (42.95,0) size 703x369
-        LayoutTableSection (anonymous) at (0,0) size 703x369
-          LayoutTableRow {tr} at (0,0) size 703x369
-            LayoutTableCell {td} at (0,0) size 703x369 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 691x357
-                LayoutTableSection (anonymous) at (0,0) size 691x357
-                  LayoutTableRow {tr} at (0,1) size 691x66
-                    LayoutTableCell {td} at (1,1) size 689x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 679x26
-                        LayoutText {#text} at (100,0) size 479x25
-                          text run at (100,0) width 479: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 691x24
-                    LayoutTableCell {td} at (1,68) size 344x24 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (145,5) size 54x14
-                        text run at (145,5) width 54: "SVG Image"
-                    LayoutTableCell {td} at (346,68) size 344x24 [r=1 c=1 rs=1 cs=1]
-                      LayoutText {#text} at (145,5) size 54x14
-                        text run at (145,5) width 54: "PNG Image"
-                  LayoutTableRow {tr} at (0,93) size 691x263
-                    LayoutTableCell {td} at (1,93) size 344x263 [r=2 c=0 rs=1 cs=1]
+      LayoutTable {table} at (41.45,0) size 706x369
+        LayoutTableSection (anonymous) at (0,0) size 706x369
+          LayoutTableRow {tr} at (0,0) size 706x369
+            LayoutTableCell {td} at (0,0) size 706x369 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 693x357
+                LayoutTableSection (anonymous) at (0,0) size 693x357
+                  LayoutTableRow {tr} at (0,1) size 693x66
+                    LayoutTableCell {td} at (1,1) size 691x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 681x26
+                        LayoutText {#text} at (101,0) size 479x25
+                          text run at (101,0) width 479: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 693x24
+                    LayoutTableCell {td} at (1,68) size 345x24 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (145,5) size 55x14
+                        text run at (145,5) width 55: "SVG Image"
+                    LayoutTableCell {td} at (347,68) size 345x24 [r=1 c=1 rs=1 cs=1]
+                      LayoutText {#text} at (145,5) size 55x14
+                        text run at (145,5) width 55: "PNG Image"
+                  LayoutTableRow {tr} at (0,93) size 693x263
+                    LayoutTableCell {td} at (1,93) size 345x263 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (346,93) size 344x263 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (347,93) size 345x263 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 333.33x249.97
                       LayoutText {#text} at (0,0) size 0x0
-layer at (61,110) size 333x250
-  LayoutEmbeddedObject {object} at (5.67,5) size 333.33x249.98
+layer at (62,110) size 333x250
+  LayoutEmbeddedObject {object} at (6.67,5) size 333.33x249.98
     layer at (0,0) size 333x250
       LayoutView at (0,0) size 333x250
     layer at (0,0) size 333x250
diff --git a/third_party/WebKit/LayoutTests/platform/linux/tables/mozilla_expected_failures/bugs/bug89315-expected.png b/third_party/WebKit/LayoutTests/platform/linux/tables/mozilla_expected_failures/bugs/bug89315-expected.png
index a5b7ca3..271c3887 100644
--- a/third_party/WebKit/LayoutTests/platform/linux/tables/mozilla_expected_failures/bugs/bug89315-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/linux/tables/mozilla_expected_failures/bugs/bug89315-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/tables/mozilla_expected_failures/bugs/bug89315-expected.png b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/tables/mozilla_expected_failures/bugs/bug89315-expected.png
index ab10411..df6d6a4 100644
--- a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/tables/mozilla_expected_failures/bugs/bug89315-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/tables/mozilla_expected_failures/bugs/bug89315-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
index ae6728a7..d02e5887 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
index 643b704..078d1e9 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
@@ -3,103 +3,103 @@
 layer at (0,0) size 800x339
   LayoutBlockFlow {HTML} at (0,0) size 800x339.09
     LayoutBlockFlow {BODY} at (5.55,5.55) size 788.91x328
-      LayoutTable {TABLE} at (0,0) size 458x328
-        LayoutTableSection {TBODY} at (0,0) size 458x328
-          LayoutTableRow {TR} at (0,1) size 458x14
-            LayoutTableCell {TH} at (1,1) size 63x14 [bgcolor=#DDDD99] [r=0 c=0 rs=1 cs=1]
-              LayoutText {#text} at (5,0) size 53x14
-                text run at (5,0) width 53: "viewBox?"
-            LayoutTableCell {TH} at (65,1) size 112x14 [bgcolor=#DDDD99] [r=0 c=1 rs=1 cs=1]
-              LayoutText {#text} at (0,0) size 112x14
-                text run at (0,0) width 112: "preserve\x{AD}Aspect\x{AD}Ratio"
-            LayoutTableCell {TH} at (178,1) size 139x14 [bgcolor=#DDDD99] [r=0 c=2 rs=1 cs=1]
-              LayoutText {#text} at (53,0) size 33x14
-                text run at (53,0) width 33: "<img>"
-            LayoutTableCell {TH} at (318,1) size 139x14 [bgcolor=#DDDD99] [r=0 c=3 rs=1 cs=1]
-              LayoutText {#text} at (46,0) size 47x14
-                text run at (46,0) width 47: "<object>"
-          LayoutTableRow {TR} at (0,16) size 458x38
-            LayoutTableCell {TH} at (1,86) size 63x14 [bgcolor=#DDDD99] [r=1 c=0 rs=4 cs=1]
-              LayoutText {#text} at (0,0) size 63x14
-                text run at (0,0) width 63: "No viewBox"
-            LayoutTableCell {TH} at (65,35) size 112x0 [bgcolor=#DDDD99] [r=1 c=1 rs=1 cs=1]
-            LayoutTableCell {TD} at (178,16) size 139x38 [r=1 c=2 rs=1 cs=1]
+      LayoutTable {TABLE} at (0,0) size 462x328
+        LayoutTableSection {TBODY} at (0,0) size 462x328
+          LayoutTableRow {TR} at (0,1) size 462x14
+            LayoutTableCell {TH} at (1,1) size 64x14 [bgcolor=#DDDD99] [r=0 c=0 rs=1 cs=1]
+              LayoutText {#text} at (6,0) size 52x14
+                text run at (6,0) width 52: "viewBox?"
+            LayoutTableCell {TH} at (66,1) size 113x14 [bgcolor=#DDDD99] [r=0 c=1 rs=1 cs=1]
+              LayoutText {#text} at (0,0) size 113x14
+                text run at (0,0) width 113: "preserve\x{AD}Aspect\x{AD}Ratio"
+            LayoutTableCell {TH} at (180,1) size 140x14 [bgcolor=#DDDD99] [r=0 c=2 rs=1 cs=1]
+              LayoutText {#text} at (53,0) size 34x14
+                text run at (53,0) width 34: "<img>"
+            LayoutTableCell {TH} at (321,1) size 140x14 [bgcolor=#DDDD99] [r=0 c=3 rs=1 cs=1]
+              LayoutText {#text} at (47,0) size 46x14
+                text run at (47,0) width 46: "<object>"
+          LayoutTableRow {TR} at (0,16) size 462x38
+            LayoutTableCell {TH} at (1,86) size 64x14 [bgcolor=#DDDD99] [r=1 c=0 rs=4 cs=1]
+              LayoutText {#text} at (0,0) size 64x14
+                text run at (0,0) width 64: "No viewBox"
+            LayoutTableCell {TH} at (66,35) size 113x0 [bgcolor=#DDDD99] [r=1 c=1 rs=1 cs=1]
+            LayoutTableCell {TD} at (180,16) size 140x38 [r=1 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,16) size 139x38 [r=1 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,16) size 140x38 [r=1 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,55) size 458x38
-            LayoutTableCell {TH} at (65,67) size 112x14 [bgcolor=#DDDD99] [r=2 c=1 rs=1 cs=1]
-              LayoutText {#text} at (42,0) size 28x14
-                text run at (42,0) width 28: "none"
-            LayoutTableCell {TD} at (178,55) size 139x38 [r=2 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,55) size 462x38
+            LayoutTableCell {TH} at (66,67) size 113x14 [bgcolor=#DDDD99] [r=2 c=1 rs=1 cs=1]
+              LayoutText {#text} at (43,0) size 27x14
+                text run at (43,0) width 27: "none"
+            LayoutTableCell {TD} at (180,55) size 140x38 [r=2 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,55) size 139x38 [r=2 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,55) size 140x38 [r=2 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,94) size 458x38
-            LayoutTableCell {TH} at (65,106) size 112x14 [bgcolor=#DDDD99] [r=3 c=1 rs=1 cs=1]
-              LayoutText {#text} at (43,0) size 26x14
-                text run at (43,0) width 26: "meet"
-            LayoutTableCell {TD} at (178,94) size 139x38 [r=3 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,94) size 462x38
+            LayoutTableCell {TH} at (66,106) size 113x14 [bgcolor=#DDDD99] [r=3 c=1 rs=1 cs=1]
+              LayoutText {#text} at (43,0) size 27x14
+                text run at (43,0) width 27: "meet"
+            LayoutTableCell {TD} at (180,94) size 140x38 [r=3 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,94) size 139x38 [r=3 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,94) size 140x38 [r=3 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,133) size 458x38
-            LayoutTableCell {TH} at (65,145) size 112x14 [bgcolor=#DDDD99] [r=4 c=1 rs=1 cs=1]
-              LayoutText {#text} at (43,0) size 26x14
-                text run at (43,0) width 26: "slice"
-            LayoutTableCell {TD} at (178,133) size 139x38 [r=4 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,133) size 462x38
+            LayoutTableCell {TH} at (66,145) size 113x14 [bgcolor=#DDDD99] [r=4 c=1 rs=1 cs=1]
+              LayoutText {#text} at (44,0) size 25x14
+                text run at (44,0) width 25: "slice"
+            LayoutTableCell {TD} at (180,133) size 140x38 [r=4 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,133) size 139x38 [r=4 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,133) size 140x38 [r=4 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,172) size 458x38
-            LayoutTableCell {TH} at (1,242) size 63x14 [bgcolor=#DDDD99] [r=5 c=0 rs=4 cs=1]
-              LayoutText {#text} at (8,0) size 47x14
-                text run at (8,0) width 47: "viewBox"
-            LayoutTableCell {TH} at (65,191) size 112x0 [bgcolor=#DDDD99] [r=5 c=1 rs=1 cs=1]
-            LayoutTableCell {TD} at (178,172) size 139x38 [r=5 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,172) size 462x38
+            LayoutTableCell {TH} at (1,242) size 64x14 [bgcolor=#DDDD99] [r=5 c=0 rs=4 cs=1]
+              LayoutText {#text} at (9,0) size 46x14
+                text run at (9,0) width 46: "viewBox"
+            LayoutTableCell {TH} at (66,191) size 113x0 [bgcolor=#DDDD99] [r=5 c=1 rs=1 cs=1]
+            LayoutTableCell {TD} at (180,172) size 140x38 [r=5 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,172) size 139x38 [r=5 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,172) size 140x38 [r=5 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,211) size 458x38
-            LayoutTableCell {TH} at (65,223) size 112x14 [bgcolor=#DDDD99] [r=6 c=1 rs=1 cs=1]
-              LayoutText {#text} at (42,0) size 28x14
-                text run at (42,0) width 28: "none"
-            LayoutTableCell {TD} at (178,211) size 139x38 [r=6 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,211) size 462x38
+            LayoutTableCell {TH} at (66,223) size 113x14 [bgcolor=#DDDD99] [r=6 c=1 rs=1 cs=1]
+              LayoutText {#text} at (43,0) size 27x14
+                text run at (43,0) width 27: "none"
+            LayoutTableCell {TD} at (180,211) size 140x38 [r=6 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,211) size 139x38 [r=6 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,211) size 140x38 [r=6 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,250) size 458x38
-            LayoutTableCell {TH} at (65,262) size 112x14 [bgcolor=#DDDD99] [r=7 c=1 rs=1 cs=1]
-              LayoutText {#text} at (43,0) size 26x14
-                text run at (43,0) width 26: "meet"
-            LayoutTableCell {TD} at (178,250) size 139x38 [r=7 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,250) size 462x38
+            LayoutTableCell {TH} at (66,262) size 113x14 [bgcolor=#DDDD99] [r=7 c=1 rs=1 cs=1]
+              LayoutText {#text} at (43,0) size 27x14
+                text run at (43,0) width 27: "meet"
+            LayoutTableCell {TD} at (180,250) size 140x38 [r=7 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,250) size 139x38 [r=7 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,250) size 140x38 [r=7 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,289) size 458x38
-            LayoutTableCell {TH} at (65,301) size 112x14 [bgcolor=#DDDD99] [r=8 c=1 rs=1 cs=1]
-              LayoutText {#text} at (43,0) size 26x14
-                text run at (43,0) width 26: "slice"
-            LayoutTableCell {TD} at (178,289) size 139x38 [r=8 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,289) size 462x38
+            LayoutTableCell {TH} at (66,301) size 113x14 [bgcolor=#DDDD99] [r=8 c=1 rs=1 cs=1]
+              LayoutText {#text} at (44,0) size 25x14
+                text run at (44,0) width 25: "slice"
+            LayoutTableCell {TD} at (180,289) size 140x38 [r=8 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (318,289) size 139x38 [r=8 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (321,289) size 140x38 [r=8 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-layer at (324,22) size 139x35
+layer at (327,22) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
     layer at (0,0) size 133x29
       LayoutSVGRoot {svg} at (0,0) size 133x29
         LayoutSVGEllipse {circle} at (0,0) size 220x220 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [cx=110.00] [cy=110.00] [r=110.00]
-layer at (324,61) size 139x35
+layer at (327,61) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -108,7 +108,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,375.72) size 362.86x390.92 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,375.72) size 362.86x390.92 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (324,100) size 139x35
+layer at (327,100) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -117,7 +117,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,375.72) size 362.86x390.92 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,375.72) size 362.86x390.92 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (324,139) size 139x35
+layer at (327,139) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -126,7 +126,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,375.72) size 362.86x390.92 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,375.72) size 362.86x390.92 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (324,178) size 139x35
+layer at (327,178) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -135,7 +135,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,375.72) size 362.86x390.92 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,375.72) size 362.86x390.92 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (324,217) size 139x35
+layer at (327,217) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -144,7 +144,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,375.72) size 362.86x390.92 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,375.72) size 362.86x390.92 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (324,256) size 139x35
+layer at (327,256) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -153,7 +153,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,375.72) size 362.86x390.92 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,375.72) size 362.86x390.92 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (324,295) size 139x35
+layer at (327,295) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
index 3edf887..517875e4 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
index 0a0a440..69630f41 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x198
   LayoutBlockFlow {html} at (0,0) size 800x198.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x187
-      LayoutTable {table} at (142.45,0) size 504x187
-        LayoutTableSection (anonymous) at (0,0) size 504x187
-          LayoutTableRow {tr} at (0,0) size 504x187
-            LayoutTableCell {td} at (0,0) size 504x187 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 492x175
-                LayoutTableSection (anonymous) at (0,0) size 492x175
-                  LayoutTableRow {tr} at (0,1) size 492x66
-                    LayoutTableCell {td} at (1,1) size 490x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 480x26
-                        LayoutText {#text} at (0,0) size 480x26
-                          text run at (0,0) width 480: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 492x23
-                    LayoutTableCell {td} at (1,68) size 244x23 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (95,5) size 54x13
-                        text run at (95,5) width 54: "SVG Image"
-                    LayoutTableCell {td} at (246,68) size 245x23 [r=1 c=1 rs=1 cs=1]
+      LayoutTable {table} at (141.45,0) size 506x187
+        LayoutTableSection (anonymous) at (0,0) size 506x187
+          LayoutTableRow {tr} at (0,0) size 506x187
+            LayoutTableCell {td} at (0,0) size 506x187 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 493x175
+                LayoutTableSection (anonymous) at (0,0) size 493x175
+                  LayoutTableRow {tr} at (0,1) size 493x66
+                    LayoutTableCell {td} at (1,1) size 491x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 481x26
+                        LayoutText {#text} at (0,0) size 481x26
+                          text run at (0,0) width 481: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 493x23
+                    LayoutTableCell {td} at (1,68) size 245x23 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (96,5) size 53x13
+                        text run at (96,5) width 53: "SVG Image"
+                    LayoutTableCell {td} at (247,68) size 245x23 [r=1 c=1 rs=1 cs=1]
                       LayoutText {#text} at (96,5) size 53x13
                         text run at (96,5) width 53: "PNG Image"
-                  LayoutTableRow {tr} at (0,92) size 492x82
-                    LayoutTableCell {td} at (1,92) size 244x82 [r=2 c=0 rs=1 cs=1]
+                  LayoutTableRow {tr} at (0,92) size 493x82
+                    LayoutTableCell {td} at (1,92) size 245x82 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (246,92) size 245x82 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (247,92) size 245x82 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 138.88x69.44
                       LayoutText {#text} at (0,0) size 0x0
-layer at (255,109) size 139x69
-  LayoutEmbeddedObject {object} at (100.13,5) size 138.88x69.44
+layer at (257,109) size 139x69
+  LayoutEmbeddedObject {object} at (101.13,5) size 138.88x69.44
     layer at (0,0) size 139x69
       LayoutView at (0,0) size 139x69
     layer at (0,0) size 139x69
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
index 3edf887..517875e4 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
index 0a0a440..69630f41 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x198
   LayoutBlockFlow {html} at (0,0) size 800x198.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x187
-      LayoutTable {table} at (142.45,0) size 504x187
-        LayoutTableSection (anonymous) at (0,0) size 504x187
-          LayoutTableRow {tr} at (0,0) size 504x187
-            LayoutTableCell {td} at (0,0) size 504x187 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 492x175
-                LayoutTableSection (anonymous) at (0,0) size 492x175
-                  LayoutTableRow {tr} at (0,1) size 492x66
-                    LayoutTableCell {td} at (1,1) size 490x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 480x26
-                        LayoutText {#text} at (0,0) size 480x26
-                          text run at (0,0) width 480: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 492x23
-                    LayoutTableCell {td} at (1,68) size 244x23 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (95,5) size 54x13
-                        text run at (95,5) width 54: "SVG Image"
-                    LayoutTableCell {td} at (246,68) size 245x23 [r=1 c=1 rs=1 cs=1]
+      LayoutTable {table} at (141.45,0) size 506x187
+        LayoutTableSection (anonymous) at (0,0) size 506x187
+          LayoutTableRow {tr} at (0,0) size 506x187
+            LayoutTableCell {td} at (0,0) size 506x187 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 493x175
+                LayoutTableSection (anonymous) at (0,0) size 493x175
+                  LayoutTableRow {tr} at (0,1) size 493x66
+                    LayoutTableCell {td} at (1,1) size 491x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 481x26
+                        LayoutText {#text} at (0,0) size 481x26
+                          text run at (0,0) width 481: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 493x23
+                    LayoutTableCell {td} at (1,68) size 245x23 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (96,5) size 53x13
+                        text run at (96,5) width 53: "SVG Image"
+                    LayoutTableCell {td} at (247,68) size 245x23 [r=1 c=1 rs=1 cs=1]
                       LayoutText {#text} at (96,5) size 53x13
                         text run at (96,5) width 53: "PNG Image"
-                  LayoutTableRow {tr} at (0,92) size 492x82
-                    LayoutTableCell {td} at (1,92) size 244x82 [r=2 c=0 rs=1 cs=1]
+                  LayoutTableRow {tr} at (0,92) size 493x82
+                    LayoutTableCell {td} at (1,92) size 245x82 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (246,92) size 245x82 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (247,92) size 245x82 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 138.88x69.44
                       LayoutText {#text} at (0,0) size 0x0
-layer at (255,109) size 139x69
-  LayoutEmbeddedObject {object} at (100.13,5) size 138.88x69.44
+layer at (257,109) size 139x69
+  LayoutEmbeddedObject {object} at (101.13,5) size 138.88x69.44
     layer at (0,0) size 139x69
       LayoutView at (0,0) size 139x69
     layer at (0,0) size 139x69
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
index 9f1a7f4..3dcc236 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
index 62c9787..410b49f 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/mac/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x379
   LayoutBlockFlow {html} at (0,0) size 800x379.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x368
-      LayoutTable {table} at (42.95,0) size 703x368
-        LayoutTableSection (anonymous) at (0,0) size 703x368
-          LayoutTableRow {tr} at (0,0) size 703x368
-            LayoutTableCell {td} at (0,0) size 703x368 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 691x356
-                LayoutTableSection (anonymous) at (0,0) size 691x356
-                  LayoutTableRow {tr} at (0,1) size 691x66
-                    LayoutTableCell {td} at (1,1) size 689x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 679x26
-                        LayoutText {#text} at (99,0) size 481x26
-                          text run at (99,0) width 481: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 691x23
-                    LayoutTableCell {td} at (1,68) size 344x23 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (145,5) size 54x13
-                        text run at (145,5) width 54: "SVG Image"
-                    LayoutTableCell {td} at (346,68) size 344x23 [r=1 c=1 rs=1 cs=1]
-                      LayoutText {#text} at (145,5) size 54x13
-                        text run at (145,5) width 54: "PNG Image"
-                  LayoutTableRow {tr} at (0,92) size 691x263
-                    LayoutTableCell {td} at (1,92) size 344x263 [r=2 c=0 rs=1 cs=1]
+      LayoutTable {table} at (41.45,0) size 706x368
+        LayoutTableSection (anonymous) at (0,0) size 706x368
+          LayoutTableRow {tr} at (0,0) size 706x368
+            LayoutTableCell {td} at (0,0) size 706x368 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 693x356
+                LayoutTableSection (anonymous) at (0,0) size 693x356
+                  LayoutTableRow {tr} at (0,1) size 693x66
+                    LayoutTableCell {td} at (1,1) size 691x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 681x26
+                        LayoutText {#text} at (100,0) size 481x26
+                          text run at (100,0) width 481: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 693x23
+                    LayoutTableCell {td} at (1,68) size 345x23 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (146,5) size 53x13
+                        text run at (146,5) width 53: "SVG Image"
+                    LayoutTableCell {td} at (347,68) size 345x23 [r=1 c=1 rs=1 cs=1]
+                      LayoutText {#text} at (146,5) size 53x13
+                        text run at (146,5) width 53: "PNG Image"
+                  LayoutTableRow {tr} at (0,92) size 693x263
+                    LayoutTableCell {td} at (1,92) size 345x263 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (346,92) size 344x263 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (347,92) size 345x263 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 333.33x249.97
                       LayoutText {#text} at (0,0) size 0x0
-layer at (61,109) size 333x250
-  LayoutEmbeddedObject {object} at (5.67,5) size 333.33x249.98
+layer at (62,109) size 333x250
+  LayoutEmbeddedObject {object} at (6.67,5) size 333.33x249.98
     layer at (0,0) size 333x250
       LayoutView at (0,0) size 333x250
     layer at (0,0) size 333x250
diff --git a/third_party/WebKit/LayoutTests/platform/mac/tables/mozilla_expected_failures/bugs/bug89315-expected.png b/third_party/WebKit/LayoutTests/platform/mac/tables/mozilla_expected_failures/bugs/bug89315-expected.png
index 25ce0999..e4bd464 100644
--- a/third_party/WebKit/LayoutTests/platform/mac/tables/mozilla_expected_failures/bugs/bug89315-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/mac/tables/mozilla_expected_failures/bugs/bug89315-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
index 66066ae..8498b7f 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
index 46f326b..b03fc463 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-img-preserveAspectRatio-support-1-expected.txt
@@ -3,103 +3,103 @@
 layer at (0,0) size 800x339
   LayoutBlockFlow {HTML} at (0,0) size 800x339.09
     LayoutBlockFlow {BODY} at (5.55,5.55) size 788.91x328
-      LayoutTable {TABLE} at (0,0) size 463x328
-        LayoutTableSection {TBODY} at (0,0) size 463x328
-          LayoutTableRow {TR} at (0,1) size 463x14
-            LayoutTableCell {TH} at (1,1) size 63x14 [bgcolor=#DDDD99] [r=0 c=0 rs=1 cs=1]
-              LayoutText {#text} at (5,0) size 53x14
-                text run at (5,0) width 53: "viewBox?"
-            LayoutTableCell {TH} at (65,1) size 117x14 [bgcolor=#DDDD99] [r=0 c=1 rs=1 cs=1]
-              LayoutText {#text} at (0,0) size 117x14
-                text run at (0,0) width 117: "preserve\x{AD}Aspect\x{AD}Ratio"
-            LayoutTableCell {TH} at (183,1) size 139x14 [bgcolor=#DDDD99] [r=0 c=2 rs=1 cs=1]
-              LayoutText {#text} at (53,0) size 33x14
-                text run at (53,0) width 33: "<img>"
-            LayoutTableCell {TH} at (323,1) size 139x14 [bgcolor=#DDDD99] [r=0 c=3 rs=1 cs=1]
-              LayoutText {#text} at (46,0) size 47x14
-                text run at (46,0) width 47: "<object>"
-          LayoutTableRow {TR} at (0,16) size 463x38
-            LayoutTableCell {TH} at (1,86) size 63x14 [bgcolor=#DDDD99] [r=1 c=0 rs=4 cs=1]
-              LayoutText {#text} at (0,0) size 63x14
-                text run at (0,0) width 63: "No viewBox"
-            LayoutTableCell {TH} at (65,35) size 117x0 [bgcolor=#DDDD99] [r=1 c=1 rs=1 cs=1]
-            LayoutTableCell {TD} at (183,16) size 139x38 [r=1 c=2 rs=1 cs=1]
+      LayoutTable {TABLE} at (0,0) size 467x328
+        LayoutTableSection {TBODY} at (0,0) size 467x328
+          LayoutTableRow {TR} at (0,1) size 467x14
+            LayoutTableCell {TH} at (1,1) size 64x14 [bgcolor=#DDDD99] [r=0 c=0 rs=1 cs=1]
+              LayoutText {#text} at (5,0) size 54x14
+                text run at (5,0) width 54: "viewBox?"
+            LayoutTableCell {TH} at (66,1) size 118x14 [bgcolor=#DDDD99] [r=0 c=1 rs=1 cs=1]
+              LayoutText {#text} at (0,0) size 118x14
+                text run at (0,0) width 118: "preserve\x{AD}Aspect\x{AD}Ratio"
+            LayoutTableCell {TH} at (185,1) size 140x14 [bgcolor=#DDDD99] [r=0 c=2 rs=1 cs=1]
+              LayoutText {#text} at (53,0) size 34x14
+                text run at (53,0) width 34: "<img>"
+            LayoutTableCell {TH} at (326,1) size 140x14 [bgcolor=#DDDD99] [r=0 c=3 rs=1 cs=1]
+              LayoutText {#text} at (47,0) size 46x14
+                text run at (47,0) width 46: "<object>"
+          LayoutTableRow {TR} at (0,16) size 467x38
+            LayoutTableCell {TH} at (1,86) size 64x14 [bgcolor=#DDDD99] [r=1 c=0 rs=4 cs=1]
+              LayoutText {#text} at (0,0) size 64x14
+                text run at (0,0) width 64: "No viewBox"
+            LayoutTableCell {TH} at (66,35) size 118x0 [bgcolor=#DDDD99] [r=1 c=1 rs=1 cs=1]
+            LayoutTableCell {TD} at (185,16) size 140x38 [r=1 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,16) size 139x38 [r=1 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,16) size 140x38 [r=1 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,55) size 463x38
-            LayoutTableCell {TH} at (65,67) size 117x14 [bgcolor=#DDDD99] [r=2 c=1 rs=1 cs=1]
-              LayoutText {#text} at (44,0) size 29x14
-                text run at (44,0) width 29: "none"
-            LayoutTableCell {TD} at (183,55) size 139x38 [r=2 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,55) size 467x38
+            LayoutTableCell {TH} at (66,67) size 118x14 [bgcolor=#DDDD99] [r=2 c=1 rs=1 cs=1]
+              LayoutText {#text} at (45,0) size 28x14
+                text run at (45,0) width 28: "none"
+            LayoutTableCell {TD} at (185,55) size 140x38 [r=2 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,55) size 139x38 [r=2 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,55) size 140x38 [r=2 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,94) size 463x38
-            LayoutTableCell {TH} at (65,106) size 117x14 [bgcolor=#DDDD99] [r=3 c=1 rs=1 cs=1]
-              LayoutText {#text} at (44,0) size 29x14
-                text run at (44,0) width 29: "meet"
-            LayoutTableCell {TD} at (183,94) size 139x38 [r=3 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,94) size 467x38
+            LayoutTableCell {TH} at (66,106) size 118x14 [bgcolor=#DDDD99] [r=3 c=1 rs=1 cs=1]
+              LayoutText {#text} at (44,0) size 30x14
+                text run at (44,0) width 30: "meet"
+            LayoutTableCell {TD} at (185,94) size 140x38 [r=3 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,94) size 139x38 [r=3 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,94) size 140x38 [r=3 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,133) size 463x38
-            LayoutTableCell {TH} at (65,145) size 117x14 [bgcolor=#DDDD99] [r=4 c=1 rs=1 cs=1]
-              LayoutText {#text} at (45,0) size 27x14
-                text run at (45,0) width 27: "slice"
-            LayoutTableCell {TD} at (183,133) size 139x38 [r=4 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,133) size 467x38
+            LayoutTableCell {TH} at (66,145) size 118x14 [bgcolor=#DDDD99] [r=4 c=1 rs=1 cs=1]
+              LayoutText {#text} at (46,0) size 26x14
+                text run at (46,0) width 26: "slice"
+            LayoutTableCell {TD} at (185,133) size 140x38 [r=4 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,133) size 139x38 [r=4 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,133) size 140x38 [r=4 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,172) size 463x38
-            LayoutTableCell {TH} at (1,242) size 63x14 [bgcolor=#DDDD99] [r=5 c=0 rs=4 cs=1]
-              LayoutText {#text} at (8,0) size 47x14
-                text run at (8,0) width 47: "viewBox"
-            LayoutTableCell {TH} at (65,191) size 117x0 [bgcolor=#DDDD99] [r=5 c=1 rs=1 cs=1]
-            LayoutTableCell {TD} at (183,172) size 139x38 [r=5 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,172) size 467x38
+            LayoutTableCell {TH} at (1,242) size 64x14 [bgcolor=#DDDD99] [r=5 c=0 rs=4 cs=1]
+              LayoutText {#text} at (9,0) size 46x14
+                text run at (9,0) width 46: "viewBox"
+            LayoutTableCell {TH} at (66,191) size 118x0 [bgcolor=#DDDD99] [r=5 c=1 rs=1 cs=1]
+            LayoutTableCell {TD} at (185,172) size 140x38 [r=5 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,172) size 139x38 [r=5 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,172) size 140x38 [r=5 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,211) size 463x38
-            LayoutTableCell {TH} at (65,223) size 117x14 [bgcolor=#DDDD99] [r=6 c=1 rs=1 cs=1]
-              LayoutText {#text} at (44,0) size 29x14
-                text run at (44,0) width 29: "none"
-            LayoutTableCell {TD} at (183,211) size 139x38 [r=6 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,211) size 467x38
+            LayoutTableCell {TH} at (66,223) size 118x14 [bgcolor=#DDDD99] [r=6 c=1 rs=1 cs=1]
+              LayoutText {#text} at (45,0) size 28x14
+                text run at (45,0) width 28: "none"
+            LayoutTableCell {TD} at (185,211) size 140x38 [r=6 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,211) size 139x38 [r=6 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,211) size 140x38 [r=6 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,250) size 463x38
-            LayoutTableCell {TH} at (65,262) size 117x14 [bgcolor=#DDDD99] [r=7 c=1 rs=1 cs=1]
-              LayoutText {#text} at (44,0) size 29x14
-                text run at (44,0) width 29: "meet"
-            LayoutTableCell {TD} at (183,250) size 139x38 [r=7 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,250) size 467x38
+            LayoutTableCell {TH} at (66,262) size 118x14 [bgcolor=#DDDD99] [r=7 c=1 rs=1 cs=1]
+              LayoutText {#text} at (44,0) size 30x14
+                text run at (44,0) width 30: "meet"
+            LayoutTableCell {TD} at (185,250) size 140x38 [r=7 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,250) size 139x38 [r=7 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,250) size 140x38 [r=7 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-          LayoutTableRow {TR} at (0,289) size 463x38
-            LayoutTableCell {TH} at (65,301) size 117x14 [bgcolor=#DDDD99] [r=8 c=1 rs=1 cs=1]
-              LayoutText {#text} at (45,0) size 27x14
-                text run at (45,0) width 27: "slice"
-            LayoutTableCell {TD} at (183,289) size 139x38 [r=8 c=2 rs=1 cs=1]
+          LayoutTableRow {TR} at (0,289) size 467x38
+            LayoutTableCell {TH} at (66,301) size 118x14 [bgcolor=#DDDD99] [r=8 c=1 rs=1 cs=1]
+              LayoutText {#text} at (46,0) size 26x14
+                text run at (46,0) width 26: "slice"
+            LayoutTableCell {TD} at (185,289) size 140x38 [r=8 c=2 rs=1 cs=1]
               LayoutImage {IMG} at (0,0) size 138.88x34.72 [border: (1.38px dashed #800000)]
               LayoutText {#text} at (0,0) size 0x0
-            LayoutTableCell {TD} at (323,289) size 139x38 [r=8 c=3 rs=1 cs=1]
+            LayoutTableCell {TD} at (326,289) size 140x38 [r=8 c=3 rs=1 cs=1]
               LayoutText {#text} at (0,0) size 0x0
-layer at (329,22) size 139x35
+layer at (332,22) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
     layer at (0,0) size 133x29
       LayoutSVGRoot {svg} at (0,0) size 133x29
         LayoutSVGEllipse {circle} at (0,0) size 220x220 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [cx=110.00] [cy=110.00] [r=110.00]
-layer at (329,61) size 139x35
+layer at (332,61) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -108,7 +108,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (329,100) size 139x35
+layer at (332,100) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -117,7 +117,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (329,139) size 139x35
+layer at (332,139) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -126,7 +126,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (329,178) size 139x35
+layer at (332,178) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -135,7 +135,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (329,217) size 139x35
+layer at (332,217) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -144,7 +144,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (329,256) size 139x35
+layer at (332,256) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
@@ -153,7 +153,7 @@
         LayoutSVGHiddenContainer {defs} at (0,0) size 0x0
         LayoutSVGContainer {g} at (162.86,403.79) size 362.86x362.86 [transform={m=((1.00,0.00)(0.00,1.00)) t=(-162.36,-403.29)}]
           LayoutSVGPath {path} at (162.86,403.79) size 362.86x362.86 [stroke={[type=SOLID] [color=#000000]}] [fill={[type=SOLID] [color=#D9BB7A] [fill rule=EVEN-ODD]}] [data="M 525.714 585.219 A 181.429 181.429 0 1 1 162.857 585.219 A 181.429 181.429 0 1 1 525.714 585.219 Z"]
-layer at (329,295) size 139x35
+layer at (332,295) size 139x35
   LayoutEmbeddedObject {OBJECT} at (0,0) size 138.88x34.72 [border: (0.69px dashed #008000)]
     layer at (0,0) size 133x29
       LayoutView at (0,0) size 133x29
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
index 8c86f65..809cddc 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
index d2b6c58..061d399 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-2-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x199
   LayoutBlockFlow {html} at (0,0) size 800x199.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x188
-      LayoutTable {table} at (144.45,0) size 500x188
-        LayoutTableSection (anonymous) at (0,0) size 500x188
-          LayoutTableRow {tr} at (0,0) size 500x188
-            LayoutTableCell {td} at (0,0) size 500x188 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 488x176
-                LayoutTableSection (anonymous) at (0,0) size 488x176
-                  LayoutTableRow {tr} at (0,1) size 488x66
-                    LayoutTableCell {td} at (1,1) size 486x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 476x26
-                        LayoutText {#text} at (0,0) size 476x25
-                          text run at (0,0) width 476: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 488x24
-                    LayoutTableCell {td} at (1,68) size 242x24 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (96,5) size 50x14
-                        text run at (96,5) width 50: "SVG Image"
-                    LayoutTableCell {td} at (244,68) size 243x24 [r=1 c=1 rs=1 cs=1]
+      LayoutTable {table} at (143.45,0) size 502x188
+        LayoutTableSection (anonymous) at (0,0) size 502x188
+          LayoutTableRow {tr} at (0,0) size 502x188
+            LayoutTableCell {td} at (0,0) size 502x188 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 489x176
+                LayoutTableSection (anonymous) at (0,0) size 489x176
+                  LayoutTableRow {tr} at (0,1) size 489x66
+                    LayoutTableCell {td} at (1,1) size 487x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 477x26
+                        LayoutText {#text} at (0,0) size 477x25
+                          text run at (0,0) width 477: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 489x24
+                    LayoutTableCell {td} at (1,68) size 243x24 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (96,5) size 51x14
+                        text run at (96,5) width 51: "SVG Image"
+                    LayoutTableCell {td} at (245,68) size 243x24 [r=1 c=1 rs=1 cs=1]
                       LayoutText {#text} at (95,5) size 53x14
                         text run at (95,5) width 53: "PNG Image"
-                  LayoutTableRow {tr} at (0,93) size 488x82
-                    LayoutTableCell {td} at (1,93) size 242x82 [r=2 c=0 rs=1 cs=1]
+                  LayoutTableRow {tr} at (0,93) size 489x82
+                    LayoutTableCell {td} at (1,93) size 243x82 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (244,93) size 243x82 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (245,93) size 243x82 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 138.88x69.44
                       LayoutText {#text} at (0,0) size 0x0
-layer at (255,110) size 139x69
-  LayoutEmbeddedObject {object} at (98.13,5) size 138.88x69.44
+layer at (257,110) size 139x69
+  LayoutEmbeddedObject {object} at (99.13,5) size 138.88x69.44
     layer at (0,0) size 139x69
       LayoutView at (0,0) size 139x69
     layer at (0,0) size 139x69
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
index 8c86f65..809cddc 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
index d2b6c58..061d399 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-absolute-size-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x199
   LayoutBlockFlow {html} at (0,0) size 800x199.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x188
-      LayoutTable {table} at (144.45,0) size 500x188
-        LayoutTableSection (anonymous) at (0,0) size 500x188
-          LayoutTableRow {tr} at (0,0) size 500x188
-            LayoutTableCell {td} at (0,0) size 500x188 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 488x176
-                LayoutTableSection (anonymous) at (0,0) size 488x176
-                  LayoutTableRow {tr} at (0,1) size 488x66
-                    LayoutTableCell {td} at (1,1) size 486x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 476x26
-                        LayoutText {#text} at (0,0) size 476x25
-                          text run at (0,0) width 476: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 488x24
-                    LayoutTableCell {td} at (1,68) size 242x24 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (96,5) size 50x14
-                        text run at (96,5) width 50: "SVG Image"
-                    LayoutTableCell {td} at (244,68) size 243x24 [r=1 c=1 rs=1 cs=1]
+      LayoutTable {table} at (143.45,0) size 502x188
+        LayoutTableSection (anonymous) at (0,0) size 502x188
+          LayoutTableRow {tr} at (0,0) size 502x188
+            LayoutTableCell {td} at (0,0) size 502x188 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 489x176
+                LayoutTableSection (anonymous) at (0,0) size 489x176
+                  LayoutTableRow {tr} at (0,1) size 489x66
+                    LayoutTableCell {td} at (1,1) size 487x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 477x26
+                        LayoutText {#text} at (0,0) size 477x25
+                          text run at (0,0) width 477: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 489x24
+                    LayoutTableCell {td} at (1,68) size 243x24 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (96,5) size 51x14
+                        text run at (96,5) width 51: "SVG Image"
+                    LayoutTableCell {td} at (245,68) size 243x24 [r=1 c=1 rs=1 cs=1]
                       LayoutText {#text} at (95,5) size 53x14
                         text run at (95,5) width 53: "PNG Image"
-                  LayoutTableRow {tr} at (0,93) size 488x82
-                    LayoutTableCell {td} at (1,93) size 242x82 [r=2 c=0 rs=1 cs=1]
+                  LayoutTableRow {tr} at (0,93) size 489x82
+                    LayoutTableCell {td} at (1,93) size 243x82 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (244,93) size 243x82 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (245,93) size 243x82 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 138.88x69.44
                       LayoutText {#text} at (0,0) size 0x0
-layer at (255,110) size 139x69
-  LayoutEmbeddedObject {object} at (98.13,5) size 138.88x69.44
+layer at (257,110) size 139x69
+  LayoutEmbeddedObject {object} at (99.13,5) size 138.88x69.44
     layer at (0,0) size 139x69
       LayoutView at (0,0) size 139x69
     layer at (0,0) size 139x69
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
index f31ff92b..8655d45 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
index c33d0b2..9ce1c95 100644
--- a/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
+++ b/third_party/WebKit/LayoutTests/platform/win/svg/zoom/page/zoom-svg-through-object-with-percentage-size-expected.txt
@@ -3,32 +3,32 @@
 layer at (0,0) size 800x380
   LayoutBlockFlow {html} at (0,0) size 800x380.09
     LayoutBlockFlow {body} at (5.55,5.55) size 788.91x369
-      LayoutTable {table} at (42.95,0) size 703x369
-        LayoutTableSection (anonymous) at (0,0) size 703x369
-          LayoutTableRow {tr} at (0,0) size 703x369
-            LayoutTableCell {td} at (0,0) size 703x369 [r=0 c=0 rs=1 cs=3]
-              LayoutTable {table} at (6,6) size 691x357
-                LayoutTableSection (anonymous) at (0,0) size 691x357
-                  LayoutTableRow {tr} at (0,1) size 691x66
-                    LayoutTableCell {td} at (1,1) size 689x65.75 [r=0 c=0 rs=1 cs=2]
-                      LayoutBlockFlow {h1} at (5,19.88) size 679x26
-                        LayoutText {#text} at (101,0) size 477x25
-                          text run at (101,0) width 477: "Both sides should have identical size after zooming"
-                  LayoutTableRow {tr} at (0,68) size 691x24
-                    LayoutTableCell {td} at (1,68) size 344x24 [r=1 c=0 rs=1 cs=1]
-                      LayoutText {#text} at (147,5) size 50x14
-                        text run at (147,5) width 50: "SVG Image"
-                    LayoutTableCell {td} at (346,68) size 344x24 [r=1 c=1 rs=1 cs=1]
-                      LayoutText {#text} at (145,5) size 54x14
-                        text run at (145,5) width 54: "PNG Image"
-                  LayoutTableRow {tr} at (0,93) size 691x263
-                    LayoutTableCell {td} at (1,93) size 344x263 [r=2 c=0 rs=1 cs=1]
+      LayoutTable {table} at (41.45,0) size 706x369
+        LayoutTableSection (anonymous) at (0,0) size 706x369
+          LayoutTableRow {tr} at (0,0) size 706x369
+            LayoutTableCell {td} at (0,0) size 706x369 [r=0 c=0 rs=1 cs=3]
+              LayoutTable {table} at (7.44,6) size 693x357
+                LayoutTableSection (anonymous) at (0,0) size 693x357
+                  LayoutTableRow {tr} at (0,1) size 693x66
+                    LayoutTableCell {td} at (1,1) size 691x65.75 [r=0 c=0 rs=1 cs=2]
+                      LayoutBlockFlow {h1} at (5.55,19.88) size 681x26
+                        LayoutText {#text} at (102,0) size 477x25
+                          text run at (102,0) width 477: "Both sides should have identical size after zooming"
+                  LayoutTableRow {tr} at (0,68) size 693x24
+                    LayoutTableCell {td} at (1,68) size 345x24 [r=1 c=0 rs=1 cs=1]
+                      LayoutText {#text} at (147,5) size 51x14
+                        text run at (147,5) width 51: "SVG Image"
+                    LayoutTableCell {td} at (347,68) size 345x24 [r=1 c=1 rs=1 cs=1]
+                      LayoutText {#text} at (146,5) size 53x14
+                        text run at (146,5) width 53: "PNG Image"
+                  LayoutTableRow {tr} at (0,93) size 693x263
+                    LayoutTableCell {td} at (1,93) size 345x263 [r=2 c=0 rs=1 cs=1]
                       LayoutText {#text} at (0,0) size 0x0
-                    LayoutTableCell {td} at (346,93) size 344x263 [r=2 c=1 rs=1 cs=1]
+                    LayoutTableCell {td} at (347,93) size 345x263 [r=2 c=1 rs=1 cs=1]
                       LayoutImage {img} at (5,5) size 333.33x249.97
                       LayoutText {#text} at (0,0) size 0x0
-layer at (61,110) size 333x250
-  LayoutEmbeddedObject {object} at (5.67,5) size 333.33x249.98
+layer at (62,110) size 333x250
+  LayoutEmbeddedObject {object} at (6.67,5) size 333.33x249.98
     layer at (0,0) size 333x250
       LayoutView at (0,0) size 333x250
     layer at (0,0) size 333x250
diff --git a/third_party/WebKit/LayoutTests/platform/win/tables/mozilla_expected_failures/bugs/bug89315-expected.png b/third_party/WebKit/LayoutTests/platform/win/tables/mozilla_expected_failures/bugs/bug89315-expected.png
index 68319184..cf2d15d9 100644
--- a/third_party/WebKit/LayoutTests/platform/win/tables/mozilla_expected_failures/bugs/bug89315-expected.png
+++ b/third_party/WebKit/LayoutTests/platform/win/tables/mozilla_expected_failures/bugs/bug89315-expected.png
Binary files differ
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt
index 1de64a0d..260dc1d 100644
--- a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt
+++ b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt
@@ -4053,7 +4053,12 @@
     attribute @@toStringTag
     method constructor
     method createSession
+    method getStatusForPolicy
     method setServerCertificate
+interface MediaKeysPolicy
+    attribute @@toStringTag
+    getter minHdcpVersion
+    method constructor
 interface MediaList
     attribute @@toStringTag
     getter length
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
index db7e33587..8563df7a 100644
--- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
+++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -4053,7 +4053,12 @@
     attribute @@toStringTag
     method constructor
     method createSession
+    method getStatusForPolicy
     method setServerCertificate
+interface MediaKeysPolicy
+    attribute @@toStringTag
+    getter minHdcpVersion
+    method constructor
 interface MediaList
     attribute @@toStringTag
     getter length
diff --git a/third_party/WebKit/PRESUBMIT.py b/third_party/WebKit/PRESUBMIT.py
index 4ca8cca..62d0866 100644
--- a/third_party/WebKit/PRESUBMIT.py
+++ b/third_party/WebKit/PRESUBMIT.py
@@ -77,7 +77,6 @@
         maxlen=800, license_header=license_header))
     results.extend(_CheckForNonBlinkVariantMojomIncludes(input_api, output_api))
     results.extend(_CheckTestExpectations(input_api, output_api))
-    results.extend(_CheckWtfOsMacros(input_api, output_api))
     results.extend(_CheckWatchlist(input_api, output_api))
     return results
 
@@ -131,20 +130,6 @@
     return results
 
 
-def _CheckWtfOsMacros(input_api, output_api):
-    """Ensures that Blink code uses no WTF's OS macros."""
-    os_macro_re = input_api.re.compile(r'^\s*#(el)?if.*\bOS\(')
-    errors = input_api.canned_checks._FindNewViolationsOfRule(
-        lambda _, x: not os_macro_re.search(x),
-        input_api, None)
-    errors = ['Found deprecated OS() macro in %s. Include build/build_config.h '
-              'and use defined(OS_*) instead.'
-              % violation for violation in errors]
-    if errors:
-        return [output_api.PresubmitPromptWarning('\n'.join(errors))]
-    return []
-
-
 def _CheckForPrintfDebugging(input_api, output_api):
     """Generally speaking, we'd prefer not to land patches that printf
     debug output."""
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8GCForContextDispose.cpp b/third_party/WebKit/Source/bindings/core/v8/V8GCForContextDispose.cpp
index 000898de..a6343ca 100644
--- a/third_party/WebKit/Source/bindings/core/v8/V8GCForContextDispose.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/V8GCForContextDispose.cpp
@@ -30,6 +30,7 @@
 
 #include "bindings/core/v8/V8GCForContextDispose.h"
 
+#include "build/build_config.h"
 #include "platform/Histogram.h"
 #include "platform/MemoryCoordinator.h"
 #include "platform/bindings/V8PerIsolateData.h"
@@ -62,7 +63,7 @@
     WindowProxy::FrameReuseStatus frame_reuse_status) {
   did_dispose_context_for_main_frame_ = is_main_frame;
   last_context_disposal_time_ = WTF::CurrentTime();
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   // When a low end device is in a low memory situation we should prioritize
   // memory use and trigger a V8+Blink GC. However, on Android, if the frame
   // will not be reused, the process will likely to be killed soon so skip this.
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8ScriptRunner.cpp b/third_party/WebKit/Source/bindings/core/v8/V8ScriptRunner.cpp
index 3688407..3b1a8df 100644
--- a/third_party/WebKit/Source/bindings/core/v8/V8ScriptRunner.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/V8ScriptRunner.cpp
@@ -30,6 +30,7 @@
 #include "bindings/core/v8/ScriptStreamer.h"
 #include "bindings/core/v8/V8BindingForCore.h"
 #include "bindings/core/v8/V8GCController.h"
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExecutionContext.h"
 #include "core/frame/LocalDOMWindow.h"
@@ -46,7 +47,7 @@
 #include "platform/wtf/CurrentTime.h"
 #include "public/platform/Platform.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <malloc.h>
 #else
 #include <alloca.h>
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8DevToolsHostCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8DevToolsHostCustom.cpp
index d97f7eac..5941c22 100644
--- a/third_party/WebKit/Source/bindings/core/v8/custom/V8DevToolsHostCustom.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8DevToolsHostCustom.cpp
@@ -34,6 +34,7 @@
 #include "bindings/core/v8/V8HTMLDocument.h"
 #include "bindings/core/v8/V8MouseEvent.h"
 #include "bindings/core/v8/V8Window.h"
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/frame/LocalDOMWindow.h"
 #include "core/inspector/DevToolsHost.h"
@@ -46,9 +47,9 @@
 
 void V8DevToolsHost::platformMethodCustom(
     const v8::FunctionCallbackInfo<v8::Value>& info) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   V8SetReturnValue(info, V8AtomicString(info.GetIsolate(), "mac"));
-#elif OS(WIN)
+#elif defined(OS_WIN)
   V8SetReturnValue(info, V8AtomicString(info.GetIsolate(), "windows"));
 #else  // Unix-like systems
   V8SetReturnValue(info, V8AtomicString(info.GetIsolate(), "linux"));
diff --git a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp
index 7d2c3a9..52848148 100644
--- a/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp
+++ b/third_party/WebKit/Source/bindings/core/v8/serialization/V8ScriptValueSerializerTest.cpp
@@ -27,6 +27,7 @@
 #include "bindings/core/v8/V8StringResource.h"
 #include "bindings/core/v8/serialization/UnpackedSerializedScriptValue.h"
 #include "bindings/core/v8/serialization/V8ScriptValueDeserializer.h"
+#include "build/build_config.h"
 #include "core/dom/MessagePort.h"
 #include "core/fileapi/Blob.h"
 #include "core/fileapi/File.h"
@@ -952,7 +953,7 @@
 // this test intends to ensure that a platform can decode images it has
 // previously written. At format version 9, Android writes RGBA and every
 // other platform writes BGRA.
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   RefPtr<SerializedScriptValue> input =
       SerializedValue({0xff, 0x09, 0x3f, 0x00, 0x67, 0x01, 0x01, 0x02, 0x01,
                        0x08, 0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff});
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn
index f803a5e..123b123 100644
--- a/third_party/WebKit/Source/core/BUILD.gn
+++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -586,6 +586,7 @@
     "$blink_core_output_dir/css/properties/CSSPropertyAPIZoom.h",
     "$blink_core_output_dir/css/properties/CSSPropertyDescriptor.cpp",
     "$blink_core_output_dir/css/properties/CSSPropertyDescriptor.h",
+    "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIBorderImage.h",
     "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIBorderRadius.h",
     "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIBorderSpacing.h",
     "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIColumns.h",
@@ -596,6 +597,7 @@
     "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIOffset.h",
     "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPITextDecoration.h",
     "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIWebkitMarginCollapse.h",
+    "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIWebkitMaskBoxImage.h",
   ]
 }
 
diff --git a/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp b/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp
index fc51051f..6d48eec 100644
--- a/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp
+++ b/third_party/WebKit/Source/core/clipboard/DataTransfer.cpp
@@ -26,6 +26,8 @@
 #include "core/clipboard/DataTransfer.h"
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/clipboard/DataObject.h"
 #include "core/clipboard/DataTransferItem.h"
@@ -495,7 +497,7 @@
   }
 
   String str = selection.SelectedTextForClipboard();
-#if OS(WIN)
+#if defined(OS_WIN)
   ReplaceNewlinesWithWindowsStyleNewlines(str);
 #endif
   ReplaceNBSPWithSpace(str);
diff --git a/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp b/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp
index a706221..33cabf1 100644
--- a/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp
+++ b/third_party/WebKit/Source/core/clipboard/Pasteboard.cpp
@@ -30,6 +30,7 @@
 
 #include "core/clipboard/Pasteboard.h"
 
+#include "build/build_config.h"
 #include "core/clipboard/DataObject.h"
 #include "platform/clipboard/ClipboardUtilities.h"
 #include "platform/graphics/Image.h"
@@ -61,7 +62,7 @@
 
 void Pasteboard::WritePlainText(const String& text, SmartReplaceOption) {
 // FIXME: add support for smart replace
-#if OS(WIN)
+#if defined(OS_WIN)
   String plain_text(text);
   ReplaceNewlinesWithWindowsStyleNewlines(plain_text);
   Platform::Current()->Clipboard()->WritePlainText(plain_text);
@@ -124,7 +125,7 @@
                            const String& plain_text,
                            bool can_smart_copy_or_delete) {
   String text = plain_text;
-#if OS(WIN)
+#if defined(OS_WIN)
   ReplaceNewlinesWithWindowsStyleNewlines(text);
 #endif
   ReplaceNBSPWithSpace(text);
diff --git a/third_party/WebKit/Source/core/css/BUILD.gn b/third_party/WebKit/Source/core/css/BUILD.gn
index 61763c6..ca13f0d 100644
--- a/third_party/WebKit/Source/core/css/BUILD.gn
+++ b/third_party/WebKit/Source/core/css/BUILD.gn
@@ -533,6 +533,7 @@
     "properties/CSSPropertyTransitionPropertyUtils.h",
     "properties/CSSPropertyWebkitBorderWidthUtils.cpp",
     "properties/CSSPropertyWebkitBorderWidthUtils.h",
+    "properties/CSSShorthandPropertyAPIBorderImage.cpp",
     "properties/CSSShorthandPropertyAPIBorderRadius.cpp",
     "properties/CSSShorthandPropertyAPIBorderSpacing.cpp",
     "properties/CSSShorthandPropertyAPIColumns.cpp",
@@ -543,6 +544,7 @@
     "properties/CSSShorthandPropertyAPIOverflow.cpp",
     "properties/CSSShorthandPropertyAPITextDecoration.cpp",
     "properties/CSSShorthandPropertyAPIWebkitMarginCollapse.cpp",
+    "properties/CSSShorthandPropertyAPIWebkitMaskBoxImage.cpp",
     "resolver/AnimatedStyleBuilder.cpp",
     "resolver/AnimatedStyleBuilder.h",
     "resolver/CSSPropertyPriority.h",
diff --git a/third_party/WebKit/Source/core/css/CSSFontSelector.cpp b/third_party/WebKit/Source/core/css/CSSFontSelector.cpp
index 9b0c557..70e6268 100644
--- a/third_party/WebKit/Source/core/css/CSSFontSelector.cpp
+++ b/third_party/WebKit/Source/core/css/CSSFontSelector.cpp
@@ -26,6 +26,7 @@
 
 #include "core/css/CSSFontSelector.h"
 
+#include "build/build_config.h"
 #include "core/css/CSSFontSelectorClient.h"
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/CSSValueList.h"
@@ -90,7 +91,7 @@
     const GenericFontFamilySettings& settings,
     const FontDescription& font_description,
     const AtomicString& generic_family_name) {
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   if (font_description.GenericFamily() == FontDescription::kStandardFamily)
     return FontCache::GetGenericFamilyNameForScript(
         FontFamilyNames::webkit_standard, font_description);
diff --git a/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp b/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
index ab81d394..442e6fc 100644
--- a/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
+++ b/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
@@ -21,6 +21,7 @@
 
 #include "core/css/CSSPrimitiveValue.h"
 
+#include "build/build_config.h"
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSHelper.h"
 #include "core/css/CSSMarkup.h"
@@ -509,11 +510,11 @@
 }
 
 static String FormatNumber(double number, const char* suffix) {
-#if OS(WIN) && _MSC_VER < 1900
+#if defined(OS_WIN) && _MSC_VER < 1900
   unsigned oldFormat = _set_output_format(_TWO_DIGIT_EXPONENT);
 #endif
   String result = String::Format("%.6g%s", number, suffix);
-#if OS(WIN) && _MSC_VER < 1900
+#if defined(OS_WIN) && _MSC_VER < 1900
   _set_output_format(oldFormat);
 #endif
   return result;
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.json5 b/third_party/WebKit/Source/core/css/CSSProperties.json5
index a664428..6ad074c4 100644
--- a/third_party/WebKit/Source/core/css/CSSProperties.json5
+++ b/third_party/WebKit/Source/core/css/CSSProperties.json5
@@ -3668,6 +3668,8 @@
     {
       name: "border-image",
       longhands: ["border-image-source", "border-image-slice", "border-image-width", "border-image-outset", "border-image-repeat"],
+      api_class: true,
+      api_methods: ["parseShorthand"],
     },
     {
       name: "border-left",
@@ -3900,6 +3902,8 @@
     {
       name: "-webkit-mask-box-image",
       longhands: ["-webkit-mask-box-image-source", "-webkit-mask-box-image-slice", "-webkit-mask-box-image-width", "-webkit-mask-box-image-outset", "-webkit-mask-box-image-repeat"],
+      api_class: true,
+      api_methods: ["parseShorthand"],
     },
     {
       name: "-webkit-mask-position",
diff --git a/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp b/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp
index 4588ef58..d4d57bb 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSParserFastPaths.cpp
@@ -4,6 +4,7 @@
 
 #include "core/css/parser/CSSParserFastPaths.h"
 
+#include "build/build_config.h"
 #include "core/StylePropertyShorthand.h"
 #include "core/css/CSSColorValue.h"
 #include "core/css/CSSFunctionValue.h"
@@ -785,7 +786,7 @@
       return value_id == CSSValueNowrap || value_id == CSSValueWrap ||
              value_id == CSSValueWrapReverse;
     case CSSPropertyHyphens:
-#if OS(ANDROID) || OS(MACOSX)
+#if defined(OS_ANDROID) || defined(OS_MACOSX)
       return value_id == CSSValueAuto || value_id == CSSValueNone ||
              value_id == CSSValueManual;
 #else
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
index d69df9f..f968a92 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
+++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -1789,62 +1789,6 @@
   return range_.AtEnd();
 }
 
-// TODO(crbug.com/668012): refactor out property specific logic from this method
-// and remove CSSPropetyID argument
-bool CSSPropertyParser::ConsumeBorderImage(CSSPropertyID property,
-                                           bool default_fill,
-                                           bool important) {
-  CSSValue* source = nullptr;
-  CSSValue* slice = nullptr;
-  CSSValue* width = nullptr;
-  CSSValue* outset = nullptr;
-  CSSValue* repeat = nullptr;
-  if (CSSPropertyBorderImageUtils::ConsumeBorderImageComponents(
-          range_, context_, source, slice, width, outset, repeat,
-          default_fill)) {
-    switch (property) {
-      case CSSPropertyWebkitMaskBoxImage:
-        AddParsedProperty(
-            CSSPropertyWebkitMaskBoxImageSource, CSSPropertyWebkitMaskBoxImage,
-            source ? *source : *CSSInitialValue::Create(), important);
-        AddParsedProperty(
-            CSSPropertyWebkitMaskBoxImageSlice, CSSPropertyWebkitMaskBoxImage,
-            slice ? *slice : *CSSInitialValue::Create(), important);
-        AddParsedProperty(
-            CSSPropertyWebkitMaskBoxImageWidth, CSSPropertyWebkitMaskBoxImage,
-            width ? *width : *CSSInitialValue::Create(), important);
-        AddParsedProperty(
-            CSSPropertyWebkitMaskBoxImageOutset, CSSPropertyWebkitMaskBoxImage,
-            outset ? *outset : *CSSInitialValue::Create(), important);
-        AddParsedProperty(
-            CSSPropertyWebkitMaskBoxImageRepeat, CSSPropertyWebkitMaskBoxImage,
-            repeat ? *repeat : *CSSInitialValue::Create(), important);
-        return true;
-      case CSSPropertyBorderImage:
-        AddParsedProperty(CSSPropertyBorderImageSource, CSSPropertyBorderImage,
-                          source ? *source : *CSSInitialValue::Create(),
-                          important);
-        AddParsedProperty(CSSPropertyBorderImageSlice, CSSPropertyBorderImage,
-                          slice ? *slice : *CSSInitialValue::Create(),
-                          important);
-        AddParsedProperty(CSSPropertyBorderImageWidth, CSSPropertyBorderImage,
-                          width ? *width : *CSSInitialValue::Create(),
-                          important);
-        AddParsedProperty(CSSPropertyBorderImageOutset, CSSPropertyBorderImage,
-                          outset ? *outset : *CSSInitialValue::Create(),
-                          important);
-        AddParsedProperty(CSSPropertyBorderImageRepeat, CSSPropertyBorderImage,
-                          repeat ? *repeat : *CSSInitialValue::Create(),
-                          important);
-        return true;
-      default:
-        NOTREACHED();
-        return false;
-    }
-  }
-  return false;
-}
-
 static inline CSSValueID MapFromPageBreakBetween(CSSValueID value) {
   if (value == CSSValueAlways)
     return CSSValuePage;
@@ -2551,10 +2495,6 @@
       return ConsumeShorthandGreedily(borderLeftShorthand(), important);
     case CSSPropertyBorder:
       return ConsumeBorder(important);
-    case CSSPropertyBorderImage:
-      return ConsumeBorderImage(property, false /* default_fill */, important);
-    case CSSPropertyWebkitMaskBoxImage:
-      return ConsumeBorderImage(property, true /* default_fill */, important);
     case CSSPropertyPageBreakAfter:
     case CSSPropertyPageBreakBefore:
     case CSSPropertyPageBreakInside:
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
index 57ced9e..f7a662c4 100644
--- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
+++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
@@ -105,9 +105,6 @@
   bool ConsumePlaceItemsShorthand(bool important);
   bool ConsumePlaceSelfShorthand(bool important);
 
-  // CSS3 Parsing Routines (for properties specific to CSS3)
-  bool ConsumeBorderImage(CSSPropertyID, bool default_fill, bool important);
-
   bool ConsumeLegacyBreakProperty(CSSPropertyID, bool important);
 
  private:
diff --git a/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIBorderImage.cpp b/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIBorderImage.cpp
new file mode 100644
index 0000000..9a52cc8
--- /dev/null
+++ b/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIBorderImage.cpp
@@ -0,0 +1,55 @@
+// Copyright 2017 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 "core/css/properties/CSSShorthandPropertyAPIBorderImage.h"
+
+#include "core/css/CSSInitialValue.h"
+#include "core/css/parser/CSSParserContext.h"
+#include "core/css/parser/CSSPropertyParserHelpers.h"
+#include "core/css/properties/CSSPropertyBorderImageUtils.h"
+
+namespace blink {
+
+bool CSSShorthandPropertyAPIBorderImage::parseShorthand(
+    bool important,
+    CSSParserTokenRange& range,
+    const CSSParserContext& context,
+    const CSSParserLocalContext&,
+    HeapVector<CSSProperty, 256>& properties) {
+  CSSValue* source = nullptr;
+  CSSValue* slice = nullptr;
+  CSSValue* width = nullptr;
+  CSSValue* outset = nullptr;
+  CSSValue* repeat = nullptr;
+
+  if (!CSSPropertyBorderImageUtils::ConsumeBorderImageComponents(
+          range, &context, source, slice, width, outset, repeat, false)) {
+    return false;
+  }
+
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyBorderImageSource, CSSPropertyBorderImage,
+      source ? *source : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyBorderImageSlice, CSSPropertyBorderImage,
+      slice ? *slice : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyBorderImageWidth, CSSPropertyBorderImage,
+      width ? *width : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyBorderImageOutset, CSSPropertyBorderImage,
+      outset ? *outset : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyBorderImageRepeat, CSSPropertyBorderImage,
+      repeat ? *repeat : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+
+  return true;
+}
+
+}  // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIWebkitMaskBoxImage.cpp b/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIWebkitMaskBoxImage.cpp
new file mode 100644
index 0000000..2c7d2d0
--- /dev/null
+++ b/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIWebkitMaskBoxImage.cpp
@@ -0,0 +1,55 @@
+// Copyright 2017 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 "core/css/properties/CSSShorthandPropertyAPIWebkitMaskBoxImage.h"
+
+#include "core/css/CSSInitialValue.h"
+#include "core/css/parser/CSSParserContext.h"
+#include "core/css/parser/CSSPropertyParserHelpers.h"
+#include "core/css/properties/CSSPropertyBorderImageUtils.h"
+
+namespace blink {
+
+bool CSSShorthandPropertyAPIWebkitMaskBoxImage::parseShorthand(
+    bool important,
+    CSSParserTokenRange& range,
+    const CSSParserContext& context,
+    const CSSParserLocalContext&,
+    HeapVector<CSSProperty, 256>& properties) {
+  CSSValue* source = nullptr;
+  CSSValue* slice = nullptr;
+  CSSValue* width = nullptr;
+  CSSValue* outset = nullptr;
+  CSSValue* repeat = nullptr;
+
+  if (!CSSPropertyBorderImageUtils::ConsumeBorderImageComponents(
+          range, &context, source, slice, width, outset, repeat, true)) {
+    return false;
+  }
+
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyWebkitMaskBoxImageSource, CSSPropertyWebkitMaskBoxImage,
+      source ? *source : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyWebkitMaskBoxImageSlice, CSSPropertyWebkitMaskBoxImage,
+      slice ? *slice : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyWebkitMaskBoxImageWidth, CSSPropertyWebkitMaskBoxImage,
+      width ? *width : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyWebkitMaskBoxImageOutset, CSSPropertyWebkitMaskBoxImage,
+      outset ? *outset : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+  CSSPropertyParserHelpers::AddProperty(
+      CSSPropertyWebkitMaskBoxImageRepeat, CSSPropertyWebkitMaskBoxImage,
+      repeat ? *repeat : *CSSInitialValue::Create(), important,
+      CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties);
+
+  return true;
+}
+
+}  // namespace blink
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
index 5f7cd64..9ca88a8b 100644
--- a/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
+++ b/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
@@ -27,6 +27,8 @@
 #include "core/css/resolver/StyleBuilderConverter.h"
 
 #include <algorithm>
+
+#include "build/build_config.h"
 #include "core/css/BasicShapeFunctions.h"
 #include "core/css/CSSBasicShapeValues.h"
 #include "core/css/CSSColorValue.h"
@@ -194,7 +196,7 @@
   if (value.IsFontFamilyValue()) {
     generic_family = FontDescription::kNoFamily;
     family_name = AtomicString(ToCSSFontFamilyValue(value).Value());
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     if (family_name == FontCache::LegacySystemFontFamily()) {
       UseCounter::Count(*document_for_count, WebFeature::kBlinkMacSystemFont);
       family_name = FontFamilyNames::system_ui;
diff --git a/third_party/WebKit/Source/core/dom/BUILD.gn b/third_party/WebKit/Source/core/dom/BUILD.gn
index 687e822..be72fd34 100644
--- a/third_party/WebKit/Source/core/dom/BUILD.gn
+++ b/third_party/WebKit/Source/core/dom/BUILD.gn
@@ -329,6 +329,8 @@
     "StyleSheetCollection.h",
     "SuspendableObject.cpp",
     "SuspendableObject.h",
+    "SyncReattachContext.cpp",
+    "SyncReattachContext.h",
     "SynchronousMutationNotifier.cpp",
     "SynchronousMutationNotifier.h",
     "SynchronousMutationObserver.cpp",
diff --git a/third_party/WebKit/Source/core/dom/SyncReattachContext.cpp b/third_party/WebKit/Source/core/dom/SyncReattachContext.cpp
new file mode 100644
index 0000000..5fb9480
--- /dev/null
+++ b/third_party/WebKit/Source/core/dom/SyncReattachContext.cpp
@@ -0,0 +1,11 @@
+// Copyright 2017 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 "core/dom/SyncReattachContext.h"
+
+namespace blink {
+
+SyncReattachContext* SyncReattachContext::current_context_ = nullptr;
+
+}  // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/SyncReattachContext.h b/third_party/WebKit/Source/core/dom/SyncReattachContext.h
new file mode 100644
index 0000000..4f872f7a
--- /dev/null
+++ b/third_party/WebKit/Source/core/dom/SyncReattachContext.h
@@ -0,0 +1,43 @@
+// Copyright 2017 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 SyncReattachContext_h
+#define SyncReattachContext_h
+
+#include "core/dom/Node.h"
+
+namespace blink {
+
+class SyncReattachContext {
+  STACK_ALLOCATED();
+
+ public:
+  static Node::AttachContext& CurrentAttachContext() {
+    DCHECK(current_context_);
+    return current_context_->AttachContextForReattach();
+  }
+  SyncReattachContext(Node::AttachContext& attach_context)
+      : parent_context_(current_context_),
+        previous_in_flow_(attach_context.previous_in_flow),
+        attach_context_(attach_context) {
+    current_context_ = this;
+  }
+  ~SyncReattachContext() { current_context_ = parent_context_; }
+
+ private:
+  Node::AttachContext& AttachContextForReattach() {
+    attach_context_.previous_in_flow = previous_in_flow_;
+    return attach_context_;
+  }
+
+  static SyncReattachContext* current_context_;
+
+  SyncReattachContext* parent_context_ = nullptr;
+  LayoutObject* previous_in_flow_;
+  Node::AttachContext& attach_context_;
+};
+
+}  // namespace blink
+
+#endif  // SyncReattachContext_h
diff --git a/third_party/WebKit/Source/core/dom/ViewportDescription.cpp b/third_party/WebKit/Source/core/dom/ViewportDescription.cpp
index 970037c4..018eda0 100644
--- a/third_party/WebKit/Source/core/dom/ViewportDescription.cpp
+++ b/third_party/WebKit/Source/core/dom/ViewportDescription.cpp
@@ -29,6 +29,7 @@
 
 #include "core/dom/ViewportDescription.h"
 
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/frame/LocalFrame.h"
 #include "core/frame/LocalFrameView.h"
@@ -238,7 +239,7 @@
 
 void ViewportDescription::ReportMobilePageStats(
     const LocalFrame* main_frame) const {
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   enum ViewportUMAType {
     kNoViewportTag,
     kDeviceWidth,
diff --git a/third_party/WebKit/Source/core/editing/EditingBehavior.cpp b/third_party/WebKit/Source/core/editing/EditingBehavior.cpp
index f9febd1..659069be 100644
--- a/third_party/WebKit/Source/core/editing/EditingBehavior.cpp
+++ b/third_party/WebKit/Source/core/editing/EditingBehavior.cpp
@@ -26,6 +26,7 @@
 
 #include "core/editing/EditingBehavior.h"
 
+#include "build/build_config.h"
 #include "core/events/KeyboardEvent.h"
 #include "platform/KeyboardCodes.h"
 #include "public/platform/WebInputEvent.h"
@@ -42,7 +43,7 @@
 const unsigned kAltKey = WebInputEvent::kAltKey;
 const unsigned kShiftKey = WebInputEvent::kShiftKey;
 const unsigned kMetaKey = WebInputEvent::kMetaKey;
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 // Aliases for the generic key defintions to make kbd shortcuts definitions more
 // readable on OS X.
 const unsigned kOptionKey = kAltKey;
@@ -85,7 +86,7 @@
 const KeyboardCodeKeyDownEntry kKeyboardCodeKeyDownEntries[] = {
     {VKEY_LEFT, 0, "MoveLeft"},
     {VKEY_LEFT, kShiftKey, "MoveLeftAndModifySelection"},
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     {VKEY_LEFT, kOptionKey, "MoveWordLeft"},
     {VKEY_LEFT, kOptionKey | kShiftKey, "MoveWordLeftAndModifySelection"},
 #else
@@ -94,7 +95,7 @@
 #endif
     {VKEY_RIGHT, 0, "MoveRight"},
     {VKEY_RIGHT, kShiftKey, "MoveRightAndModifySelection"},
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     {VKEY_RIGHT, kOptionKey, "MoveWordRight"},
     {VKEY_RIGHT, kOptionKey | kShiftKey, "MoveWordRightAndModifySelection"},
 #else
@@ -107,7 +108,7 @@
     {VKEY_DOWN, 0, "MoveDown"},
     {VKEY_DOWN, kShiftKey, "MoveDownAndModifySelection"},
     {VKEY_NEXT, kShiftKey, "MovePageDownAndModifySelection"},
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
     {VKEY_UP, kCtrlKey, "MoveParagraphBackward"},
     {VKEY_UP, kCtrlKey | kShiftKey, "MoveParagraphBackwardAndModifySelection"},
     {VKEY_DOWN, kCtrlKey, "MoveParagraphForward"},
@@ -117,32 +118,32 @@
 #endif
     {VKEY_HOME, 0, "MoveToBeginningOfLine"},
     {VKEY_HOME, kShiftKey, "MoveToBeginningOfLineAndModifySelection"},
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     {VKEY_PRIOR, kOptionKey, "MovePageUp"},
     {VKEY_NEXT, kOptionKey, "MovePageDown"},
 #endif
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
     {VKEY_HOME, kCtrlKey, "MoveToBeginningOfDocument"},
     {VKEY_HOME, kCtrlKey | kShiftKey,
      "MoveToBeginningOfDocumentAndModifySelection"},
 #endif
     {VKEY_END, 0, "MoveToEndOfLine"},
     {VKEY_END, kShiftKey, "MoveToEndOfLineAndModifySelection"},
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
     {VKEY_END, kCtrlKey, "MoveToEndOfDocument"},
     {VKEY_END, kCtrlKey | kShiftKey, "MoveToEndOfDocumentAndModifySelection"},
 #endif
     {VKEY_BACK, 0, "DeleteBackward"},
     {VKEY_BACK, kShiftKey, "DeleteBackward"},
     {VKEY_DELETE, 0, "DeleteForward"},
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     {VKEY_BACK, kOptionKey, "DeleteWordBackward"},
     {VKEY_DELETE, kOptionKey, "DeleteWordForward"},
 #else
     {VKEY_BACK, kCtrlKey, "DeleteWordBackward"},
     {VKEY_DELETE, kCtrlKey, "DeleteWordForward"},
 #endif
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     {'B', kCommandKey, "ToggleBold"},
     {'I', kCommandKey, "ToggleItalic"},
 #else
@@ -162,7 +163,7 @@
     {VKEY_INSERT, kCtrlKey, "Copy"},
     {VKEY_INSERT, kShiftKey, "Paste"},
     {VKEY_DELETE, kShiftKey, "Cut"},
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
     // On OS X, we pipe these back to the browser, so that it can do menu item
     // blinking.
     {'C', kCtrlKey, "Copy"},
@@ -267,19 +268,19 @@
   // unexpected behaviour
   if (ch < ' ')
     return false;
-#if OS(LINUX)
+#if defined(OS_LINUX)
   // According to XKB map no keyboard combinations with ctrl key are mapped to
   // printable characters, however we need the filter as the DomKey/text could
   // contain printable characters.
   if (event.ctrlKey())
     return false;
-#elif !OS(WIN)
+#elif !defined(OS_WIN)
   // Don't insert ASCII character if ctrl w/o alt or meta is on.
   // On Mac, we should ignore events when meta is on (Command-<x>).
   if (ch < 0x80) {
     if (event.ctrlKey() && !event.altKey())
       return false;
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     if (event.metaKey())
       return false;
 #endif
diff --git a/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp b/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp
index 6f72856..d5d633a 100644
--- a/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp
+++ b/third_party/WebKit/Source/core/editing/EditingStyleUtilities.cpp
@@ -26,6 +26,7 @@
 
 #include "EditingStyleUtilities.h"
 
+#include "core/CSSPropertyNames.h"
 #include "core/css/CSSColorValue.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
 #include "core/css/CSSIdentifierValue.h"
diff --git a/third_party/WebKit/Source/core/editing/EditingStyleUtilities.h b/third_party/WebKit/Source/core/editing/EditingStyleUtilities.h
index f73ddc5..204c6ff 100644
--- a/third_party/WebKit/Source/core/editing/EditingStyleUtilities.h
+++ b/third_party/WebKit/Source/core/editing/EditingStyleUtilities.h
@@ -32,10 +32,8 @@
 #ifndef EditingStyleUtilities_h
 #define EditingStyleUtilities_h
 
-#include "core/CSSPropertyNames.h"
 #include "core/CSSValueKeywords.h"
 #include "core/editing/VisibleSelection.h"
-#include "core/editing/WritingDirection.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/core/editing/Editor.cpp b/third_party/WebKit/Source/core/editing/Editor.cpp
index e31a15b..a733b51 100644
--- a/third_party/WebKit/Source/core/editing/Editor.cpp
+++ b/third_party/WebKit/Source/core/editing/Editor.cpp
@@ -57,6 +57,7 @@
 #include "core/editing/commands/TypingCommand.h"
 #include "core/editing/commands/UndoStack.h"
 #include "core/editing/iterators/SearchBuffer.h"
+#include "core/editing/markers/DocumentMarker.h"
 #include "core/editing/markers/DocumentMarkerController.h"
 #include "core/editing/serializers/Serialization.h"
 #include "core/editing/spellcheck/SpellChecker.h"
diff --git a/third_party/WebKit/Source/core/editing/Editor.h b/third_party/WebKit/Source/core/editing/Editor.h
index aadb065..59174a1 100644
--- a/third_party/WebKit/Source/core/editing/Editor.h
+++ b/third_party/WebKit/Source/core/editing/Editor.h
@@ -35,8 +35,6 @@
 #include "core/editing/FrameSelection.h"
 #include "core/editing/VisibleSelection.h"
 #include "core/editing/WritingDirection.h"
-#include "core/editing/iterators/TextIterator.h"
-#include "core/editing/markers/DocumentMarker.h"
 #include "core/events/InputEvent.h"
 #include "platform/PasteMode.h"
 #include "platform/heap/Handle.h"
diff --git a/third_party/WebKit/Source/core/editing/FrameSelection.h b/third_party/WebKit/Source/core/editing/FrameSelection.h
index 76a70500..cccc742e 100644
--- a/third_party/WebKit/Source/core/editing/FrameSelection.h
+++ b/third_party/WebKit/Source/core/editing/FrameSelection.h
@@ -29,17 +29,13 @@
 
 #include <memory>
 #include "core/CoreExport.h"
-#include "core/dom/Range.h"
 #include "core/dom/SynchronousMutationObserver.h"
 #include "core/editing/EphemeralRange.h"
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleSelection.h"
-#include "core/editing/iterators/TextIteratorBehavior.h"
 #include "core/layout/ScrollAlignment.h"
-#include "platform/Timer.h"
 #include "platform/geometry/IntRect.h"
 #include "platform/geometry/LayoutRect.h"
-#include "platform/graphics/PaintInvalidationReason.h"
 #include "platform/heap/Handle.h"
 #include "platform/wtf/Noncopyable.h"
 
@@ -51,6 +47,7 @@
 class FrameCaret;
 class GranularityStrategy;
 class GraphicsContext;
+class Range;
 class SelectionEditor;
 class LayoutSelection;
 class TextIteratorBehavior;
diff --git a/third_party/WebKit/Source/core/editing/InputMethodController.cpp b/third_party/WebKit/Source/core/editing/InputMethodController.cpp
index c4e039d5..dbd7f98 100644
--- a/third_party/WebKit/Source/core/editing/InputMethodController.cpp
+++ b/third_party/WebKit/Source/core/editing/InputMethodController.cpp
@@ -30,6 +30,7 @@
 #include "core/InputTypeNames.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
+#include "core/dom/Range.h"
 #include "core/dom/Text.h"
 #include "core/editing/EditingUtilities.h"
 #include "core/editing/Editor.h"
diff --git a/third_party/WebKit/Source/core/editing/InputMethodController.h b/third_party/WebKit/Source/core/editing/InputMethodController.h
index 4d97dd4f..ebb1fab1 100644
--- a/third_party/WebKit/Source/core/editing/InputMethodController.h
+++ b/third_party/WebKit/Source/core/editing/InputMethodController.h
@@ -27,7 +27,6 @@
 #define InputMethodController_h
 
 #include "core/CoreExport.h"
-#include "core/dom/Range.h"
 #include "core/dom/SynchronousMutationObserver.h"
 #include "core/editing/CompositionUnderline.h"
 #include "core/editing/EphemeralRange.h"
diff --git a/third_party/WebKit/Source/core/editing/KeyboardTest.cpp b/third_party/WebKit/Source/core/editing/KeyboardTest.cpp
index 63dbfa79..4e567bb 100644
--- a/third_party/WebKit/Source/core/editing/KeyboardTest.cpp
+++ b/third_party/WebKit/Source/core/editing/KeyboardTest.cpp
@@ -28,8 +28,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include <memory>
 #include "core/editing/EditingBehavior.h"
+
+#include <memory>
+
+#include "build/build_config.h"
 #include "core/editing/Editor.h"
 #include "core/events/EventTarget.h"
 #include "core/events/KeyboardEvent.h"
@@ -70,7 +73,7 @@
   // OSModifier is the platform's standard modifier key: control on most
   // platforms, but meta (command) on Mac.
   const char* InterpretOSModifierKeyPress(char key_code) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     WebInputEvent::Modifiers os_modifier = WebInputEvent::kMetaKey;
 #else
     WebInputEvent::Modifiers os_modifier = WebInputEvent::kControlKey;
@@ -111,37 +114,37 @@
 }
 
 TEST_F(KeyboardTest, TestOSModifierZ) {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   EXPECT_STREQ("Undo", InterpretOSModifierKeyPress('Z'));
 #endif
 }
 
 TEST_F(KeyboardTest, TestOSModifierY) {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   EXPECT_STREQ("Redo", InterpretOSModifierKeyPress('Y'));
 #endif
 }
 
 TEST_F(KeyboardTest, TestOSModifierA) {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   EXPECT_STREQ("SelectAll", InterpretOSModifierKeyPress('A'));
 #endif
 }
 
 TEST_F(KeyboardTest, TestOSModifierX) {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   EXPECT_STREQ("Cut", InterpretOSModifierKeyPress('X'));
 #endif
 }
 
 TEST_F(KeyboardTest, TestOSModifierC) {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   EXPECT_STREQ("Copy", InterpretOSModifierKeyPress('C'));
 #endif
 }
 
 TEST_F(KeyboardTest, TestOSModifierV) {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   EXPECT_STREQ("Paste", InterpretOSModifierKeyPress('V'));
 #endif
 }
diff --git a/third_party/WebKit/Source/core/editing/PlainTextRange.h b/third_party/WebKit/Source/core/editing/PlainTextRange.h
index 93505b78..fdb03851 100644
--- a/third_party/WebKit/Source/core/editing/PlainTextRange.h
+++ b/third_party/WebKit/Source/core/editing/PlainTextRange.h
@@ -31,7 +31,6 @@
 #include "platform/heap/Handle.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/NotFound.h"
-#include "platform/wtf/PassRefPtr.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/core/editing/Position.h b/third_party/WebKit/Source/core/editing/Position.h
index 325359f..2d3df83 100644
--- a/third_party/WebKit/Source/core/editing/Position.h
+++ b/third_party/WebKit/Source/core/editing/Position.h
@@ -27,14 +27,9 @@
 #define Position_h
 
 #include "core/CoreExport.h"
-#include "core/dom/ContainerNode.h"
-#include "core/editing/EditingBoundary.h"
 #include "core/editing/EditingStrategy.h"
 #include "platform/heap/Handle.h"
-#include "platform/text/TextDirection.h"
 #include "platform/wtf/Assertions.h"
-#include "platform/wtf/PassRefPtr.h"
-#include "platform/wtf/RefPtr.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/core/editing/PositionIterator.h b/third_party/WebKit/Source/core/editing/PositionIterator.h
index a4d966f..c6e235c118 100644
--- a/third_party/WebKit/Source/core/editing/PositionIterator.h
+++ b/third_party/WebKit/Source/core/editing/PositionIterator.h
@@ -29,8 +29,7 @@
 #include "core/CoreExport.h"
 #include "core/dom/Node.h"
 #include "core/editing/EditingStrategy.h"
-#include "core/editing/EditingUtilities.h"
-#include "core/html/HTMLHtmlElement.h"
+#include "core/editing/Position.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/core/editing/TextFinder.cpp b/third_party/WebKit/Source/core/editing/TextFinder.cpp
index 8fba271..2f7fe28 100644
--- a/third_party/WebKit/Source/core/editing/TextFinder.cpp
+++ b/third_party/WebKit/Source/core/editing/TextFinder.cpp
@@ -36,6 +36,7 @@
 #include "core/dom/TaskRunnerHelper.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FindInPageCoordinates.h"
+#include "core/editing/FindOptions.h"
 #include "core/editing/VisibleSelection.h"
 #include "core/editing/iterators/SearchBuffer.h"
 #include "core/editing/markers/DocumentMarker.h"
@@ -46,11 +47,10 @@
 #include "core/layout/LayoutObject.h"
 #include "core/layout/TextAutosizer.h"
 #include "core/page/Page.h"
-#include "platform/RuntimeEnabledFeatures.h"
 #include "platform/Timer.h"
 #include "platform/wtf/CurrentTime.h"
+#include "public/platform/WebFloatRect.h"
 #include "public/platform/WebVector.h"
-#include "public/web/WebAXObject.h"
 #include "public/web/WebFindOptions.h"
 #include "public/web/WebFrameClient.h"
 #include "public/web/WebViewClient.h"
diff --git a/third_party/WebKit/Source/core/editing/TextFinder.h b/third_party/WebKit/Source/core/editing/TextFinder.h
index 6ba38a9..055ee958 100644
--- a/third_party/WebKit/Source/core/editing/TextFinder.h
+++ b/third_party/WebKit/Source/core/editing/TextFinder.h
@@ -32,23 +32,23 @@
 #define TextFinder_h
 
 #include "core/CoreExport.h"
-#include "core/editing/FindOptions.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/heap/Handle.h"
 #include "platform/wtf/Noncopyable.h"
-#include "platform/wtf/PassRefPtr.h"
 #include "platform/wtf/Vector.h"
 #include "platform/wtf/text/WTFString.h"
 #include "public/platform/WebFloatPoint.h"
-#include "public/platform/WebFloatRect.h"
-#include "public/platform/WebRect.h"
-#include "public/web/WebFindOptions.h"
 
 namespace blink {
 
 class LocalFrame;
 class Range;
 class WebLocalFrameBase;
+class WebString;
+struct WebFindOptions;
+struct WebFloatPoint;
+struct WebFloatRect;
+struct WebRect;
 
 template <typename T>
 class WebVector;
diff --git a/third_party/WebKit/Source/core/editing/TextFinderTest.cpp b/third_party/WebKit/Source/core/editing/TextFinderTest.cpp
index 89243ac..8da59e81 100644
--- a/third_party/WebKit/Source/core/editing/TextFinderTest.cpp
+++ b/third_party/WebKit/Source/core/editing/TextFinderTest.cpp
@@ -20,7 +20,9 @@
 #include "platform/testing/TestingPlatformSupport.h"
 #include "platform/testing/UnitTestHelpers.h"
 #include "public/platform/Platform.h"
+#include "public/platform/WebFloatRect.h"
 #include "public/web/WebDocument.h"
+#include "public/web/WebFindOptions.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
 using blink::testing::RunPendingTasks;
diff --git a/third_party/WebKit/Source/core/editing/VisiblePosition.cpp b/third_party/WebKit/Source/core/editing/VisiblePosition.cpp
index 6344913..3afa6984 100644
--- a/third_party/WebKit/Source/core/editing/VisiblePosition.cpp
+++ b/third_party/WebKit/Source/core/editing/VisiblePosition.cpp
@@ -31,7 +31,6 @@
 #include "bindings/core/v8/ExceptionState.h"
 #include "core/HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/dom/Range.h"
 #include "core/dom/Text.h"
 #include "core/editing/EditingUtilities.h"
 #include "core/editing/TextAffinity.h"
diff --git a/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm b/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm
index f60a06c..0e4116e9 100644
--- a/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm
+++ b/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm
@@ -37,7 +37,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/Node.h"
-#include "core/dom/Range.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/PlainTextRange.h"
 #include "core/editing/VisibleUnits.h"
@@ -58,7 +57,6 @@
 #include "public/web/WebFrameWidget.h"
 #include "public/web/WebHitTestResult.h"
 #include "public/web/WebLocalFrame.h"
-#include "public/web/WebRange.h"
 
 using namespace blink;
 
diff --git a/third_party/WebKit/Source/core/editing/commands/SmartReplaceICU.cpp b/third_party/WebKit/Source/core/editing/commands/SmartReplaceICU.cpp
index 6cd6f6d9..0cad70a 100644
--- a/third_party/WebKit/Source/core/editing/commands/SmartReplaceICU.cpp
+++ b/third_party/WebKit/Source/core/editing/commands/SmartReplaceICU.cpp
@@ -29,7 +29,9 @@
 
 #include "core/editing/commands/SmartReplace.h"
 
-#if !OS(MACOSX)
+#include "build/build_config.h"
+
+#if !defined(OS_MACOSX)
 #include <unicode/uset.h>
 #include "platform/wtf/Assertions.h"
 #include "platform/wtf/text/WTFString.h"
@@ -110,4 +112,4 @@
 }
 }
 
-#endif  // !OS(MACOSX)
+#endif  // !defined(OS_MACOSX)
diff --git a/third_party/WebKit/Source/core/events/KeyboardEvent.cpp b/third_party/WebKit/Source/core/events/KeyboardEvent.cpp
index e95396cc..e562bf8 100644
--- a/third_party/WebKit/Source/core/events/KeyboardEvent.cpp
+++ b/third_party/WebKit/Source/core/events/KeyboardEvent.cpp
@@ -22,6 +22,7 @@
 
 #include "core/events/KeyboardEvent.h"
 
+#include "build/build_config.h"
 #include "core/editing/InputMethodController.h"
 #include "core/input/InputDeviceCapabilities.h"
 #include "platform/WindowsKeyboardCodes.h"
@@ -156,7 +157,7 @@
   if (!key_event_)
     return 0;
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   // FIXME: Check to see if this applies to other OS.
   // If the key event belongs to IME composition then propagate to JS.
   if (key_event_->native_key_code == 0xE5)  // VKEY_PROCESSKEY
diff --git a/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp b/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp
index 231d3ca..ec44750 100644
--- a/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp
+++ b/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp
@@ -20,6 +20,8 @@
 
 #include "core/events/UIEventWithKeyState.h"
 
+#include "build/build_config.h"
+
 namespace blink {
 
 UIEventWithKeyState::UIEventWithKeyState(
@@ -73,7 +75,7 @@
                                                         bool shift_key,
                                                         bool alt_key,
                                                         bool meta_key) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   const bool new_tab_modifier_set = meta_key;
 #else
   const bool new_tab_modifier_set = ctrl_key;
@@ -118,7 +120,7 @@
       {"Meta", WebInputEvent::kMetaKey},
       {"AltGraph", WebInputEvent::kAltGrKey},
       {"Accel",
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
        WebInputEvent::kMetaKey
 #else
        WebInputEvent::kControlKey
diff --git a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp
index 826963c4..a846785 100644
--- a/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp
+++ b/third_party/WebKit/Source/core/exported/WebAssociatedURLLoaderImplTest.cpp
@@ -31,6 +31,8 @@
 #include "public/web/WebAssociatedURLLoader.h"
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "core/frame/FrameTestHelpers.h"
 #include "core/frame/WebLocalFrameBase.h"
 #include "platform/testing/URLTestHelpers.h"
@@ -589,7 +591,7 @@
 }
 
 // This test is flaky on Windows and Android. See <http://crbug.com/471645>.
-#if OS(WIN) || OS(ANDROID)
+#if defined(OS_WIN) || defined(OS_ANDROID)
 #define MAYBE_UntrustedCheckHeaders DISABLED_UntrustedCheckHeaders
 #else
 #define MAYBE_UntrustedCheckHeaders UntrustedCheckHeaders
diff --git a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp
index 0526bb6b..e134664 100644
--- a/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp
+++ b/third_party/WebKit/Source/core/exported/WebPluginContainerImpl.cpp
@@ -35,6 +35,7 @@
 #include "bindings/core/v8/ScriptSourceCode.h"
 #include "bindings/core/v8/V8BindingForCore.h"
 #include "bindings/core/v8/V8Element.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/clipboard/DataObject.h"
 #include "core/clipboard/DataTransfer.h"
@@ -816,7 +817,7 @@
     return;
 
   if (web_event.GetType() == WebInputEvent::kKeyDown) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     if ((web_event.GetModifiers() & WebInputEvent::kInputModifiers) ==
             WebInputEvent::kMetaKey
 #else
diff --git a/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp b/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp
index 9d371e4..e9279b0 100644
--- a/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp
+++ b/third_party/WebKit/Source/core/exported/WebPluginContainerTest.cpp
@@ -32,6 +32,8 @@
 
 #include <memory>
 #include <string>
+
+#include "build/build_config.h"
 #include "core/dom/Element.h"
 #include "core/events/KeyboardEvent.h"
 #include "core/exported/FakeWebPlugin.h"
@@ -426,7 +428,7 @@
   WebInputEvent::Modifiers modifier_key = static_cast<WebInputEvent::Modifiers>(
       WebInputEvent::kControlKey | WebInputEvent::kNumLockOn |
       WebInputEvent::kIsLeft);
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   modifier_key = static_cast<WebInputEvent::Modifiers>(
       WebInputEvent::kMetaKey | WebInputEvent::kNumLockOn |
       WebInputEvent::kIsLeft);
diff --git a/third_party/WebKit/Source/core/exported/WebViewTest.cpp b/third_party/WebKit/Source/core/exported/WebViewTest.cpp
index 51d27e36..b02e3b2 100644
--- a/third_party/WebKit/Source/core/exported/WebViewTest.cpp
+++ b/third_party/WebKit/Source/core/exported/WebViewTest.cpp
@@ -35,6 +35,7 @@
 #include <string>
 
 #include "bindings/core/v8/V8Document.h"
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/Fullscreen.h"
@@ -114,7 +115,7 @@
 #include "third_party/skia/include/core/SkBitmap.h"
 #include "third_party/skia/include/core/SkCanvas.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include "public/web/mac/WebSubstringUtil.h"
 #endif
 
@@ -696,7 +697,7 @@
   EXPECT_EQ(expected_height, client.GetTestData().Height());
 
 // Android disables main frame scrollbars.
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
   EXPECT_EQ(expected_horizontal_state,
             client.GetTestData().GetHorizontalScrollbarState());
   EXPECT_EQ(expected_vertical_state,
@@ -2353,7 +2354,7 @@
   EXPECT_TRUE(frame->GetFrame()->Selection().IsHandleVisible());
 }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 TEST_P(WebViewTest, TouchDoesntSelectEmptyTextarea) {
   RegisterMockedHttpURLLoad("longpress_textarea.html");
 
@@ -2984,7 +2985,7 @@
 }
 
 // TODO(crbug.com/605112) This test is crashing on Android (Nexus 4) bot.
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 TEST_P(WebViewTest, DISABLED_ChooseValueFromDateTimeChooser) {
 #else
 TEST_P(WebViewTest, ChooseValueFromDateTimeChooser) {
@@ -3880,7 +3881,7 @@
   EXPECT_FALSE(document->GetFrame()->IsLoading());
 }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 TEST_P(WebViewTest, WebSubstringUtil) {
   RegisterMockedHttpURLLoad("content_editable_populated.html");
   WebViewBase* web_view = web_view_helper_.InitializeAndLoad(
diff --git a/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp b/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp
index 0f6cf9d..851852e 100644
--- a/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp
+++ b/third_party/WebKit/Source/core/frame/BrowserControlsTest.cpp
@@ -29,6 +29,7 @@
  */
 #include "core/frame/BrowserControls.h"
 
+#include "build/build_config.h"
 #include "core/dom/ClientRect.h"
 #include "core/frame/FrameTestHelpers.h"
 #include "core/frame/LocalFrame.h"
@@ -149,7 +150,7 @@
 // Disable these tests on Mac OSX until further investigation.
 // Local build on Mac is OK but the bot fails. This is not an issue as
 // Browser Controls are currently only used on Android.
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #define MAYBE(test) DISABLED_##test
 #else
 #define MAYBE(test) test
diff --git a/third_party/WebKit/Source/core/frame/MHTMLTest.cpp b/third_party/WebKit/Source/core/frame/MHTMLTest.cpp
index 3a7c535..66f34b5e 100644
--- a/third_party/WebKit/Source/core/frame/MHTMLTest.cpp
+++ b/third_party/WebKit/Source/core/frame/MHTMLTest.cpp
@@ -28,6 +28,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/ElementShadow.h"
@@ -264,7 +265,7 @@
   // MHTMLArchives can only be initialized from local schemes, http/https
   // schemes, and content scheme(Android specific).
   EXPECT_NE(nullptr, MHTMLArchive::Create(http_url, data.Get()));
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   EXPECT_NE(nullptr, MHTMLArchive::Create(content_url, data.Get()));
 #else
   EXPECT_EQ(nullptr, MHTMLArchive::Create(content_url, data.Get()));
diff --git a/third_party/WebKit/Source/core/frame/NavigatorID.cpp b/third_party/WebKit/Source/core/frame/NavigatorID.cpp
index c4d2334..0bd1d9d9 100644
--- a/third_party/WebKit/Source/core/frame/NavigatorID.cpp
+++ b/third_party/WebKit/Source/core/frame/NavigatorID.cpp
@@ -31,7 +31,9 @@
 
 #include "core/frame/NavigatorID.h"
 
-#if !OS(MACOSX) && !OS(WIN)
+#include "build/build_config.h"
+
+#if !defined(OS_MACOSX) && !defined(OS_WIN)
 #include <sys/utsname.h>
 #include "platform/wtf/ThreadSpecific.h"
 #include "platform/wtf/Threading.h"
@@ -54,10 +56,10 @@
 }
 
 String NavigatorID::platform() {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // Match Safari and Mozilla on Mac x86.
   return "MacIntel";
-#elif OS(WIN)
+#elif defined(OS_WIN)
   // Match Safari and Mozilla on Windows.
   return "Win32";
 #else  // Unix-like systems
diff --git a/third_party/WebKit/Source/core/frame/Settings.cpp b/third_party/WebKit/Source/core/frame/Settings.cpp
index 17debdf..1291d0e 100644
--- a/third_party/WebKit/Source/core/frame/Settings.cpp
+++ b/third_party/WebKit/Source/core/frame/Settings.cpp
@@ -27,6 +27,8 @@
 #include "core/frame/Settings.h"
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/RuntimeEnabledFeatures.h"
 #include "platform/scroll/ScrollbarTheme.h"
 #include "platform/wtf/PtrUtil.h"
@@ -42,11 +44,11 @@
 // 99) MacEditingBehavior is used a fallback.
 static EditingBehaviorType EditingBehaviorTypeForPlatform() {
   return
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
       kEditingMacBehavior
-#elif OS(WIN)
+#elif defined(OS_WIN)
       kEditingWindowsBehavior
-#elif OS(ANDROID)
+#elif defined(OS_ANDROID)
       kEditingAndroidBehavior
 #else  // Rest of the UNIX-like systems
       kEditingUnixBehavior
@@ -54,7 +56,7 @@
       ;
 }
 
-#if OS(WIN)
+#if defined(OS_WIN)
 static const bool kDefaultSelectTrailingWhitespaceEnabled = true;
 #else
 static const bool kDefaultSelectTrailingWhitespaceEnabled = false;
diff --git a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
index eb2b86b..444ad89 100644
--- a/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
@@ -34,6 +34,7 @@
 #include "bindings/core/v8/ExceptionMessages.h"
 #include "bindings/core/v8/ExceptionState.h"
 #include "bindings/core/v8/ScriptController.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/InputTypeNames.h"
 #include "core/dom/Document.h"
@@ -95,7 +96,7 @@
 const int kDefaultWidth = 300;
 const int kDefaultHeight = 150;
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 // We estimate that the max limit for android phones is a quarter of that for
 // desktops based on local experimental results on Android One.
 const int kMaxGlobalAcceleratedImageBufferCount = 25;
diff --git a/third_party/WebKit/Source/core/html/HTMLElement.h b/third_party/WebKit/Source/core/html/HTMLElement.h
index 5f32c96..df14759 100644
--- a/third_party/WebKit/Source/core/html/HTMLElement.h
+++ b/third_party/WebKit/Source/core/html/HTMLElement.h
@@ -25,7 +25,6 @@
 
 #include "core/CoreExport.h"
 #include "core/dom/Element.h"
-#include "platform/text/TextDirection.h"
 
 namespace blink {
 
diff --git a/third_party/WebKit/Source/core/html/HTMLImageElement.cpp b/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
index a20db27..fbc251c3 100644
--- a/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
@@ -34,6 +34,7 @@
 #include "core/dom/DOMException.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/ShadowRoot.h"
+#include "core/dom/SyncReattachContext.h"
 #include "core/frame/Deprecation.h"
 #include "core/frame/LocalDOMWindow.h"
 #include "core/html/FormAssociated.h"
@@ -415,6 +416,7 @@
 }
 
 void HTMLImageElement::AttachLayoutTree(AttachContext& context) {
+  SyncReattachContext reattach_context(context);
   HTMLElement::AttachLayoutTree(context);
   if (GetLayoutObject() && GetLayoutObject()->IsImage()) {
     LayoutImage* layout_image = ToLayoutImage(GetLayoutObject());
@@ -853,10 +855,10 @@
 
   layout_disposition_ = layout_disposition;
 
-  // This can happen inside of attachLayoutTree() in the middle of a recalcStyle
-  // so we need to reattach synchronously here.
   if (GetDocument().InStyleRecalc()) {
-    ReattachLayoutTree();
+    // This can happen inside of AttachLayoutTree() in the middle of a
+    // RebuildLayoutTree, so we need to reattach synchronously here.
+    ReattachLayoutTree(SyncReattachContext::CurrentAttachContext());
   } else {
     if (layout_disposition_ == LayoutDisposition::kFallbackContent) {
       EventDispatchForbiddenScope::AllowUserAgentEvents allow_events;
diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
index 1f62bc8..1784443 100644
--- a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
@@ -41,6 +41,7 @@
 #include "core/dom/IdTargetObserver.h"
 #include "core/dom/ShadowRoot.h"
 #include "core/dom/StyleChangeReason.h"
+#include "core/dom/SyncReattachContext.h"
 #include "core/dom/TaskRunnerHelper.h"
 #include "core/dom/V0InsertionPoint.h"
 #include "core/editing/FrameSelection.h"
@@ -840,6 +841,7 @@
 }
 
 void HTMLInputElement::AttachLayoutTree(AttachContext& context) {
+  SyncReattachContext reattach_context(context);
   TextControlElement::AttachLayoutTree(context);
   if (GetLayoutObject()) {
     input_type_->OnAttachWithLayoutObject();
diff --git a/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp b/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
index b7348a4..7f873bfc 100644
--- a/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
@@ -30,6 +30,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/ShadowRoot.h"
+#include "core/dom/SyncReattachContext.h"
 #include "core/dom/TagCollection.h"
 #include "core/dom/Text.h"
 #include "core/frame/LocalFrame.h"
@@ -347,12 +348,13 @@
 
 // TODO(schenney): crbug.com/572908 Remove this hack.
 void HTMLObjectElement::ReattachFallbackContent() {
-  // This can happen inside of attachLayoutTree() in the middle of a recalcStyle
-  // so we need to reattach synchronously here.
-  if (GetDocument().InStyleRecalc())
-    ReattachLayoutTree();
-  else
+  if (GetDocument().InStyleRecalc()) {
+    // This can happen inside of AttachLayoutTree() in the middle of a
+    // RebuildLayoutTree, so we need to reattach synchronously here.
+    ReattachLayoutTree(SyncReattachContext::CurrentAttachContext());
+  } else {
     LazyReattachIfAttached();
+  }
 }
 
 void HTMLObjectElement::RenderFallbackContent() {
@@ -441,6 +443,11 @@
 
 void HTMLObjectElement::AssociateWith(HTMLFormElement* form) {
   AssociateByParser(form);
-};
+}
+
+void HTMLObjectElement::AttachLayoutTree(AttachContext& context) {
+  SyncReattachContext reattach_context(context);
+  HTMLPlugInElement::AttachLayoutTree(context);
+}
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLObjectElement.h b/third_party/WebKit/Source/core/html/HTMLObjectElement.h
index ee887df..2b86ba1 100644
--- a/third_party/WebKit/Source/core/html/HTMLObjectElement.h
+++ b/third_party/WebKit/Source/core/html/HTMLObjectElement.h
@@ -78,6 +78,7 @@
 
   FormAssociated* ToFormAssociatedOrNull() override { return this; };
   void AssociateWith(HTMLFormElement*) override;
+  void AttachLayoutTree(AttachContext&) final;
 
  private:
   HTMLObjectElement(Document&, bool created_by_parser);
diff --git a/third_party/WebKit/Source/core/html/HTMLPlugInElement.h b/third_party/WebKit/Source/core/html/HTMLPlugInElement.h
index 4c40f48..5458b29 100644
--- a/third_party/WebKit/Source/core/html/HTMLPlugInElement.h
+++ b/third_party/WebKit/Source/core/html/HTMLPlugInElement.h
@@ -95,6 +95,7 @@
   // Node functions:
   void RemovedFrom(ContainerNode* insertion_point) override;
   void DidMoveToNewDocument(Document& old_document) override;
+  void AttachLayoutTree(AttachContext&) override;
 
   // Element functions:
   bool IsPresentationAttribute(const QualifiedName&) const override;
@@ -133,7 +134,6 @@
   bool CanStartSelection() const override;
   bool WillRespondToMouseClickEvents() final;
   void DefaultEventHandler(Event*) final;
-  void AttachLayoutTree(AttachContext&) final;
   void DetachLayoutTree(const AttachContext& = AttachContext()) final;
   void FinishParsingChildren() final;
 
diff --git a/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp b/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
index a29322b..2362ce5 100644
--- a/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
+++ b/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
@@ -33,6 +33,7 @@
 #include "bindings/core/v8/ExceptionState.h"
 #include "bindings/core/v8/HTMLElementOrLong.h"
 #include "bindings/core/v8/HTMLOptionElementOrHTMLOptGroupElement.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/dom/AXObjectCache.h"
 #include "core/dom/Attribute.h"
@@ -1509,7 +1510,7 @@
     MouseEvent* mouse_event = ToMouseEvent(event);
     if (HTMLOptionElement* option = EventTargetOption(*mouse_event)) {
       if (!option->IsDisabledFormControl()) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
         UpdateSelectedState(option, mouse_event->metaKey(),
                             mouse_event->shiftKey());
 #else
diff --git a/third_party/WebKit/Source/core/html/canvas/CanvasAsyncBlobCreator.cpp b/third_party/WebKit/Source/core/html/canvas/CanvasAsyncBlobCreator.cpp
index 5b0b0a9..d5f468d 100644
--- a/third_party/WebKit/Source/core/html/canvas/CanvasAsyncBlobCreator.cpp
+++ b/third_party/WebKit/Source/core/html/canvas/CanvasAsyncBlobCreator.cpp
@@ -4,6 +4,7 @@
 
 #include "core/html/canvas/CanvasAsyncBlobCreator.h"
 
+#include "build/build_config.h"
 #include "core/dom/DOMException.h"
 #include "core/dom/Document.h"
 #include "core/dom/TaskRunnerHelper.h"
@@ -36,7 +37,7 @@
 const double kIdleTaskStartTimeoutDelay = 200.0;
 // We should be more lenient on completion timeout delay to ensure that the
 // switch from idle to main thread only happens to a minority of toBlob calls
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
 // Png image encoding on 4k by 4k canvas on Mac HDD takes 5.7+ seconds
 const double kIdleTaskCompleteTimeoutDelay = 6700.0;
 #else
diff --git a/third_party/WebKit/Source/core/html/forms/ExternalPopupMenu.cpp b/third_party/WebKit/Source/core/html/forms/ExternalPopupMenu.cpp
index 89ccf0b..fbadaac 100644
--- a/third_party/WebKit/Source/core/html/forms/ExternalPopupMenu.cpp
+++ b/third_party/WebKit/Source/core/html/forms/ExternalPopupMenu.cpp
@@ -30,6 +30,7 @@
 
 #include "core/html/forms/ExternalPopupMenu.h"
 
+#include "build/build_config.h"
 #include "core/dom/NodeComputedStyle.h"
 #include "core/dom/TaskRunnerHelper.h"
 #include "core/exported/WebViewBase.h"
@@ -53,7 +54,7 @@
 #include "public/web/WebMenuItemInfo.h"
 #include "public/web/WebPopupMenuInfo.h"
 #include "public/web/WebView.h"
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include "core/page/ChromeClient.h"
 #endif
 
@@ -117,7 +118,7 @@
 void ExternalPopupMenu::Show() {
   if (!ShowInternal())
     return;
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // TODO(sashab): Change this back to WebViewBase::CurrentInputEvent() once
   // WebViewImpl is in core/.
   const WebInputEvent* current_event =
diff --git a/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp b/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp
index 438d0b84..d19e0490 100644
--- a/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp
+++ b/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp
@@ -26,6 +26,7 @@
 #include "core/HTMLNames.h"
 #include "core/InputTypeNames.h"
 #include "core/dom/ShadowRoot.h"
+#include "core/dom/SyncReattachContext.h"
 #include "core/events/MouseEvent.h"
 #include "core/html/FormData.h"
 #include "core/html/HTMLFormElement.h"
@@ -251,12 +252,14 @@
 }
 
 void ImageInputType::ReattachFallbackContent() {
-  // This can happen inside of attachLayoutTree() in the middle of a recalcStyle
-  // so we need to reattach synchronously here.
-  if (GetElement().GetDocument().InStyleRecalc())
-    GetElement().ReattachLayoutTree();
-  else
+  if (GetElement().GetDocument().InStyleRecalc()) {
+    // This can happen inside of AttachLayoutTree() in the middle of a
+    // RebuildLayoutTree, so we need to reattach synchronously here.
+    GetElement().ReattachLayoutTree(
+        SyncReattachContext::CurrentAttachContext());
+  } else {
     GetElement().LazyReattachIfAttached();
+  }
 }
 
 void ImageInputType::CreateShadowSubtree() {
diff --git a/third_party/WebKit/Source/core/html/forms/InternalPopupMenu.cpp b/third_party/WebKit/Source/core/html/forms/InternalPopupMenu.cpp
index cc21e74..e5738f3 100644
--- a/third_party/WebKit/Source/core/html/forms/InternalPopupMenu.cpp
+++ b/third_party/WebKit/Source/core/html/forms/InternalPopupMenu.cpp
@@ -4,6 +4,7 @@
 
 #include "core/html/forms/InternalPopupMenu.h"
 
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/dom/ElementTraversal.h"
@@ -156,7 +157,7 @@
         is_in_group_(false),
         buffer_(buffer) {
     DCHECK(buffer_);
-#if OS(LINUX)
+#if defined(OS_LINUX)
     // On other platforms, the <option> background color is the same as the
     // <select> background color. On Linux, that makes the <option>
     // background color very dark, so by default, try to use a lighter
diff --git a/third_party/WebKit/Source/core/html/forms/SpinButtonElement.cpp b/third_party/WebKit/Source/core/html/forms/SpinButtonElement.cpp
index f5a2558a..04c9aa8 100644
--- a/third_party/WebKit/Source/core/html/forms/SpinButtonElement.cpp
+++ b/third_party/WebKit/Source/core/html/forms/SpinButtonElement.cpp
@@ -26,6 +26,7 @@
 
 #include "core/html/forms/SpinButtonElement.h"
 
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/dom/TaskRunnerHelper.h"
 #include "core/events/MouseEvent.h"
@@ -224,7 +225,7 @@
 // On Mac OS, NSStepper updates the value for the button under the mouse
 // cursor regardless of the button pressed at the beginning. So the
 // following check is not needed for Mac OS.
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   if (up_down_state_ != press_starting_state_)
     return;
 #endif
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp
index cb15ddc72..44d782b 100644
--- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp
+++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapTest.cpp
@@ -31,6 +31,8 @@
 #include "core/imagebitmap/ImageBitmap.h"
 
 #include "SkPixelRef.h"  // FIXME: qualify this skia header file.
+
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/frame/LocalFrameView.h"
 #include "core/html/HTMLCanvasElement.h"
@@ -226,7 +228,7 @@
 
 // This test is failing on Android Arm 64 Official Test Bot.
 // See <http://crbug.com/721819>.
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_ImageBitmapColorSpaceConversionHTMLImageElement \
   DISABLED_ImageBitmapColorSpaceConversionHTMLImageElement
 #else
@@ -353,7 +355,7 @@
 
 // This test is failing on Android Arm 64 Official Test Bot.
 // See <http://crbug.com/721819>.
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_ImageBitmapColorSpaceConversionImageBitmap \
   DISABLED_ImageBitmapColorSpaceConversionImageBitmap
 #else
@@ -477,7 +479,7 @@
 
 // This test is failing on Android Arm 64 Official Test Bot.
 // See <http://crbug.com/721819>.
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_ImageBitmapColorSpaceConversionStaticBitmapImage \
   DISABLED_ImageBitmapColorSpaceConversionStaticBitmapImage
 #else
diff --git a/third_party/WebKit/Source/core/input/EventHandler.cpp b/third_party/WebKit/Source/core/input/EventHandler.cpp
index 89cbf41..37f0424 100644
--- a/third_party/WebKit/Source/core/input/EventHandler.cpp
+++ b/third_party/WebKit/Source/core/input/EventHandler.cpp
@@ -29,7 +29,9 @@
 #include "core/input/EventHandler.h"
 
 #include <memory>
+
 #include "bindings/core/v8/ExceptionState.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/InputTypeNames.h"
 #include "core/clipboard/DataTransfer.h"
@@ -1796,7 +1798,7 @@
 
   static const int kContextMenuMargin = 1;
 
-#if OS(WIN)
+#if defined(OS_WIN)
   int right_aligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
 #else
   int right_aligned = 0;
diff --git a/third_party/WebKit/Source/core/input/GestureManager.cpp b/third_party/WebKit/Source/core/input/GestureManager.cpp
index a1324f0..3a8a26ac 100644
--- a/third_party/WebKit/Source/core/input/GestureManager.cpp
+++ b/third_party/WebKit/Source/core/input/GestureManager.cpp
@@ -4,6 +4,7 @@
 
 #include "core/input/GestureManager.h"
 
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/dom/UserGestureIndicator.h"
 #include "core/editing/SelectionController.h"
@@ -340,7 +341,7 @@
 
 WebInputEventResult GestureManager::HandleGestureLongTap(
     const GestureEventWithHitTestResults& targeted_event) {
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
   if (long_tap_should_invoke_context_menu_) {
     long_tap_should_invoke_context_menu_ = false;
     Node* inner_node = targeted_event.GetHitTestResult().InnerNode();
diff --git a/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp b/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp
index 6ce5ab71..4d7e534 100644
--- a/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp
+++ b/third_party/WebKit/Source/core/input/KeyboardEventManager.cpp
@@ -6,6 +6,7 @@
 
 #include <memory>
 
+#include "build/build_config.h"
 #include "core/dom/Element.h"
 #include "core/dom/UserGestureIndicator.h"
 #include "core/editing/Editor.h"
@@ -27,9 +28,9 @@
 #include "public/platform/Platform.h"
 #include "public/platform/WebInputEvent.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
 #import <Carbon/Carbon.h>
 #endif
 
@@ -37,7 +38,7 @@
 
 namespace {
 
-#if OS(WIN)
+#if defined(OS_WIN)
 static const unsigned short kHIGHBITMASKSHORT = 0x8000;
 #endif
 
@@ -257,7 +258,7 @@
   if (!node)
     return WebInputEventResult::kNotHandled;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // According to NSEvents.h, OpenStep reserves the range 0xF700-0xF8FF for
   // function keys. However, some actual private use characters happen to be
   // in this range, e.g. the Apple logo (Option+Shift+K). 0xF7FF is an
@@ -383,7 +384,7 @@
   if (event->ctrlKey() || event->metaKey())
     return;
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   // Option-Tab is a shortcut based on a system-wide preference on Mac but
   // should be ignored on all other platforms.
   if (event->altKey())
@@ -426,10 +427,10 @@
 bool KeyboardEventManager::CurrentCapsLockState() {
   switch (g_override_caps_lock_state) {
     case OverrideCapsLockState::kDefault:
-#if OS(WIN)
+#if defined(OS_WIN)
       // FIXME: Does this even work inside the sandbox?
       return GetKeyState(VK_CAPITAL) & 1;
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
       return GetCurrentKeyModifiers() & alphaLock;
 #else
       // Caps lock state use is limited to Mac password input
@@ -446,14 +447,14 @@
 
 WebInputEvent::Modifiers KeyboardEventManager::GetCurrentModifierState() {
   unsigned modifiers = 0;
-#if OS(WIN)
+#if defined(OS_WIN)
   if (GetKeyState(VK_SHIFT) & kHIGHBITMASKSHORT)
     modifiers |= WebInputEvent::kShiftKey;
   if (GetKeyState(VK_CONTROL) & kHIGHBITMASKSHORT)
     modifiers |= WebInputEvent::kControlKey;
   if (GetKeyState(VK_MENU) & kHIGHBITMASKSHORT)
     modifiers |= WebInputEvent::kAltKey;
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
   UInt32 current_modifiers = GetCurrentKeyModifiers();
   if (current_modifiers & ::shiftKey)
     modifiers |= WebInputEvent::kShiftKey;
diff --git a/third_party/WebKit/Source/core/input/KeyboardEventManager.h b/third_party/WebKit/Source/core/input/KeyboardEventManager.h
index 7b148bb..9934b1c 100644
--- a/third_party/WebKit/Source/core/input/KeyboardEventManager.h
+++ b/third_party/WebKit/Source/core/input/KeyboardEventManager.h
@@ -5,6 +5,7 @@
 #ifndef KeyboardEventManager_h
 #define KeyboardEventManager_h
 
+#include "build/build_config.h"
 #include "core/CoreExport.h"
 #include "platform/heap/Handle.h"
 #include "platform/heap/Visitor.h"
@@ -29,7 +30,7 @@
  public:
   static const int kAccessKeyModifiers =
 // TODO(crbug.com/618397): Add a settings to control this behavior.
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
       WebInputEvent::kControlKey | WebInputEvent::kAltKey;
 #else
       WebInputEvent::kAltKey;
diff --git a/third_party/WebKit/Source/core/input/MouseEventManager.cpp b/third_party/WebKit/Source/core/input/MouseEventManager.cpp
index e4a1ec7d..39ed44d 100644
--- a/third_party/WebKit/Source/core/input/MouseEventManager.cpp
+++ b/third_party/WebKit/Source/core/input/MouseEventManager.cpp
@@ -4,6 +4,7 @@
 
 #include "core/input/MouseEventManager.h"
 
+#include "build/build_config.h"
 #include "core/clipboard/DataObject.h"
 #include "core/clipboard/DataTransfer.h"
 #include "core/dom/Element.h"
@@ -59,7 +60,7 @@
 const double kFakeMouseMoveInterval = 0.1;
 
 // TODO(crbug.com/653490): Read these values from the OS.
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 const int kDragThresholdX = 3;
 const int kDragThresholdY = 3;
 constexpr TimeDelta kTextDragDelay = TimeDelta::FromSecondsD(0.15);
@@ -242,7 +243,7 @@
   bool context_menu_event =
       !RuntimeEnabledFeatures::AuxclickEnabled() &&
       mev.Event().button == WebPointerProperties::Button::kRight;
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // FIXME: The Mac port achieves the same behavior by checking whether the
   // context menu is currently open in WebPage::mouseEvent(). Consider merging
   // the implementations.
diff --git a/third_party/WebKit/Source/core/input/MouseWheelEventManager.cpp b/third_party/WebKit/Source/core/input/MouseWheelEventManager.cpp
index cfaf8541..643f6da 100644
--- a/third_party/WebKit/Source/core/input/MouseWheelEventManager.cpp
+++ b/third_party/WebKit/Source/core/input/MouseWheelEventManager.cpp
@@ -4,6 +4,7 @@
 
 #include "core/input/MouseWheelEventManager.h"
 
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/events/WheelEvent.h"
 #include "core/frame/LocalFrameView.h"
@@ -75,7 +76,7 @@
     }
   } else {  // !wheel_scroll_latching, wheel_target_ will be updated for each
             // wheel event.
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     // Filter Mac OS specific phases, usually with a zero-delta.
     // https://crbug.com/553732
     // TODO(chongz): EventSender sends events with
diff --git a/third_party/WebKit/Source/core/inspector/InspectorOverlayAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorOverlayAgent.cpp
index c82ea827..efe726a 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorOverlayAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorOverlayAgent.cpp
@@ -34,6 +34,7 @@
 #include "bindings/core/v8/ScriptSourceCode.h"
 #include "bindings/core/v8/V8BindingForCore.h"
 #include "bindings/core/v8/V8InspectorOverlayHost.h"
+#include "build/build_config.h"
 #include "core/dom/DOMNodeIds.h"
 #include "core/dom/Node.h"
 #include "core/dom/StaticNodeList.h"
@@ -858,11 +859,11 @@
             V8AtomicString(isolate, "InspectorOverlayHost"), overlay_host_obj)
       .ToChecked();
 
-#if OS(WIN)
+#if defined(OS_WIN)
   EvaluateInOverlay("setPlatform", "windows");
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
   EvaluateInOverlay("setPlatform", "mac");
-#elif OS(POSIX)
+#elif defined(OS_POSIX)
   EvaluateInOverlay("setPlatform", "linux");
 #endif
 
diff --git a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
index b144d18..a15af9a 100644
--- a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
+++ b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
@@ -31,8 +31,10 @@
 #include "core/inspector/InspectorPageAgent.h"
 
 #include <memory>
+
 #include "bindings/core/v8/ScriptController.h"
 #include "bindings/core/v8/ScriptRegexp.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
@@ -753,7 +755,7 @@
 void InspectorPageAgent::DidResizeMainFrame() {
   if (!inspected_frames_->Root()->IsMainFrame())
     return;
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
   PageLayoutInvalidated(true);
 #endif
   GetFrontend()->frameResized();
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp
index 699b0188..0a9ba37 100644
--- a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp
@@ -3885,7 +3885,7 @@
   if (!prev->floating_objects_)
     return;
 
-  logical_left_offset += MarginLineLeft();
+  logical_left_offset += MarginLogicalLeft();
 
   const FloatingObjectSet& prev_set = prev->floating_objects_->Set();
   FloatingObjectSetIterator prev_end = prev_set.end();
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp b/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp
index 89d78a1..c25fa47d 100644
--- a/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlowLine.cpp
@@ -21,6 +21,7 @@
  *
  */
 
+#include "build/build_config.h"
 #include "core/dom/AXObjectCache.h"
 #include "core/editing/EditingUtilities.h"
 #include "core/layout/BidiRunForLine.h"
@@ -549,7 +550,7 @@
   bool kerning_is_enabled =
       font.GetFontDescription().GetTypesettingFeatures() & kKerning;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // FIXME: Having any font feature settings enabled can lead to selection gaps
   // on Chromium-mac. https://bugs.webkit.org/show_bug.cgi?id=113418
   bool can_use_cached_word_measurements =
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.h b/third_party/WebKit/Source/core/layout/LayoutBox.h
index 1232d76..88d4969 100644
--- a/third_party/WebKit/Source/core/layout/LayoutBox.h
+++ b/third_party/WebKit/Source/core/layout/LayoutBox.h
@@ -595,7 +595,9 @@
                            bool make_visible_in_visual_viewport = true,
                            ScrollBehavior = kScrollBehaviorAuto);
 
-  LayoutRectOutsets MarginBoxOutsets() const { return margin_box_outsets_; }
+  LayoutRectOutsets MarginBoxOutsets() const override {
+    return margin_box_outsets_;
+  }
   LayoutUnit MarginTop() const override { return margin_box_outsets_.Top(); }
   LayoutUnit MarginBottom() const override {
     return margin_box_outsets_.Bottom();
@@ -613,21 +615,66 @@
     margin_box_outsets_.SetRight(margin);
   }
 
+  LayoutUnit MarginLogicalLeft() const {
+    return margin_box_outsets_.LogicalLeft(Style()->GetWritingMode());
+  }
+  LayoutUnit MarginLogicalRight() const {
+    return margin_box_outsets_.LogicalRight(Style()->GetWritingMode());
+  }
+
+  LayoutUnit MarginBefore(
+      const ComputedStyle* override_style = nullptr) const final {
+    return margin_box_outsets_.Before(
+        (override_style ? override_style : Style())->GetWritingMode());
+  }
+  LayoutUnit MarginAfter(
+      const ComputedStyle* override_style = nullptr) const final {
+    return margin_box_outsets_.After(
+        (override_style ? override_style : Style())->GetWritingMode());
+  }
+  LayoutUnit MarginStart(
+      const ComputedStyle* override_style = nullptr) const final {
+    const ComputedStyle* style_to_use =
+        override_style ? override_style : Style();
+    return margin_box_outsets_.Start(style_to_use->GetWritingMode(),
+                                     style_to_use->Direction());
+  }
+  LayoutUnit MarginEnd(
+      const ComputedStyle* override_style = nullptr) const final {
+    const ComputedStyle* style_to_use =
+        override_style ? override_style : Style();
+    return margin_box_outsets_.end(style_to_use->GetWritingMode(),
+                                   style_to_use->Direction());
+  }
+  LayoutUnit MarginOver() const final {
+    return margin_box_outsets_.Over(Style()->GetWritingMode());
+  }
+  LayoutUnit MarginUnder() const final {
+    return margin_box_outsets_.Under(Style()->GetWritingMode());
+  }
   void SetMarginBefore(LayoutUnit value,
                        const ComputedStyle* override_style = nullptr) {
-    LogicalMarginToPhysicalSetter(override_style).SetBefore(value);
+    margin_box_outsets_.SetBefore(
+        (override_style ? override_style : Style())->GetWritingMode(), value);
   }
   void SetMarginAfter(LayoutUnit value,
                       const ComputedStyle* override_style = nullptr) {
-    LogicalMarginToPhysicalSetter(override_style).SetAfter(value);
+    margin_box_outsets_.SetAfter(
+        (override_style ? override_style : Style())->GetWritingMode(), value);
   }
   void SetMarginStart(LayoutUnit value,
                       const ComputedStyle* override_style = nullptr) {
-    LogicalMarginToPhysicalSetter(override_style).SetStart(value);
+    const ComputedStyle* style_to_use =
+        override_style ? override_style : Style();
+    margin_box_outsets_.SetStart(style_to_use->GetWritingMode(),
+                                 style_to_use->Direction(), value);
   }
   void SetMarginEnd(LayoutUnit value,
                     const ComputedStyle* override_style = nullptr) {
-    LogicalMarginToPhysicalSetter(override_style).SetEnd(value);
+    const ComputedStyle* style_to_use =
+        override_style ? override_style : Style();
+    margin_box_outsets_.SetEnd(style_to_use->GetWritingMode(),
+                               style_to_use->Direction(), value);
   }
 
   // The following functions are used to implement collapsing margins.
@@ -1630,15 +1677,6 @@
   std::unique_ptr<BoxOverflowModel> overflow_;
 
  private:
-  LogicalToPhysicalSetter<LayoutUnit, LayoutBox> LogicalMarginToPhysicalSetter(
-      const ComputedStyle* override_style) {
-    const auto& style = override_style ? *override_style : StyleRef();
-    return LogicalToPhysicalSetter<LayoutUnit, LayoutBox>(
-        style.GetWritingMode(), style.Direction(), *this,
-        &LayoutBox::SetMarginTop, &LayoutBox::SetMarginRight,
-        &LayoutBox::SetMarginBottom, &LayoutBox::SetMarginLeft);
-  }
-
   // The inline box containing this LayoutBox, for atomic inline elements.
   InlineBox* inline_box_wrapper_;
 
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h
index 8b54c72f..a97d25ad 100644
--- a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h
+++ b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h
@@ -31,7 +31,6 @@
 #include "core/layout/LayoutObject.h"
 #include "core/page/scrolling/StickyPositionScrollingConstraints.h"
 #include "platform/geometry/LayoutRect.h"
-#include "platform/text/WritingModeUtils.h"
 #include "platform/wtf/PtrUtil.h"
 
 namespace blink {
@@ -244,15 +243,14 @@
   }
   virtual LayoutUnit PaddingLeft() const { return ComputedCSSPaddingLeft(); }
   virtual LayoutUnit PaddingRight() const { return ComputedCSSPaddingRight(); }
-
-  LayoutUnit PaddingBefore() const {
-    return PhysicalPaddingToLogical().Before();
+  virtual LayoutUnit PaddingBefore() const {
+    return ComputedCSSPaddingBefore();
   }
-  LayoutUnit PaddingAfter() const { return PhysicalPaddingToLogical().After(); }
-  LayoutUnit PaddingStart() const { return PhysicalPaddingToLogical().Start(); }
-  LayoutUnit PaddingEnd() const { return PhysicalPaddingToLogical().End(); }
-  LayoutUnit PaddingOver() const { return PhysicalPaddingToLogical().Over(); }
-  LayoutUnit PaddingUnder() const { return PhysicalPaddingToLogical().Under(); }
+  virtual LayoutUnit PaddingAfter() const { return ComputedCSSPaddingAfter(); }
+  virtual LayoutUnit PaddingStart() const { return ComputedCSSPaddingStart(); }
+  virtual LayoutUnit PaddingEnd() const { return ComputedCSSPaddingEnd(); }
+  LayoutUnit PaddingOver() const { return ComputedCSSPaddingOver(); }
+  LayoutUnit PaddingUnder() const { return ComputedCSSPaddingUnder(); }
 
   virtual LayoutUnit BorderTop() const {
     return LayoutUnit(Style()->BorderTopWidth());
@@ -266,18 +264,29 @@
   virtual LayoutUnit BorderRight() const {
     return LayoutUnit(Style()->BorderRightWidth());
   }
-
-  LayoutUnit BorderBefore() const { return PhysicalBorderToLogical().Before(); }
-  LayoutUnit BorderAfter() const { return PhysicalBorderToLogical().After(); }
-  LayoutUnit BorderStart() const { return PhysicalBorderToLogical().Start(); }
-  LayoutUnit BorderEnd() const { return PhysicalBorderToLogical().End(); }
-  LayoutUnit BorderOver() const { return PhysicalBorderToLogical().Over(); }
-  LayoutUnit BorderUnder() const { return PhysicalBorderToLogical().Under(); }
+  virtual LayoutUnit BorderBefore() const {
+    return LayoutUnit(Style()->BorderBeforeWidth());
+  }
+  virtual LayoutUnit BorderAfter() const {
+    return LayoutUnit(Style()->BorderAfterWidth());
+  }
+  virtual LayoutUnit BorderStart() const {
+    return LayoutUnit(Style()->BorderStartWidth());
+  }
+  virtual LayoutUnit BorderEnd() const {
+    return LayoutUnit(Style()->BorderEndWidth());
+  }
+  LayoutUnit BorderOver() const {
+    return LayoutUnit(Style()->BorderOverWidth());
+  }
+  LayoutUnit BorderUnder() const {
+    return LayoutUnit(Style()->BorderUnderWidth());
+  }
 
   LayoutUnit BorderWidth() const { return BorderLeft() + BorderRight(); }
   LayoutUnit BorderHeight() const { return BorderTop() + BorderBottom(); }
 
-  LayoutRectOutsets BorderBoxOutsets() const {
+  virtual LayoutRectOutsets BorderBoxOutsets() const {
     return LayoutRectOutsets(BorderTop(), BorderRight(), BorderBottom(),
                              BorderLeft());
   }
@@ -363,36 +372,21 @@
            BorderBefore() + BorderAfter();
   }
 
+  virtual LayoutRectOutsets MarginBoxOutsets() const = 0;
   virtual LayoutUnit MarginTop() const = 0;
   virtual LayoutUnit MarginBottom() const = 0;
   virtual LayoutUnit MarginLeft() const = 0;
   virtual LayoutUnit MarginRight() const = 0;
-
-  LayoutUnit MarginBefore(const ComputedStyle* other_style = nullptr) const {
-    return PhysicalMarginToLogical(other_style).Before();
-  }
-  LayoutUnit MarginAfter(const ComputedStyle* other_style = nullptr) const {
-    return PhysicalMarginToLogical(other_style).After();
-  }
-  LayoutUnit MarginStart(const ComputedStyle* other_style = nullptr) const {
-    return PhysicalMarginToLogical(other_style).Start();
-  }
-  LayoutUnit MarginEnd(const ComputedStyle* other_style = nullptr) const {
-    return PhysicalMarginToLogical(other_style).End();
-  }
-  LayoutUnit MarginLineLeft() const {
-    return PhysicalMarginToLogical(nullptr).LineLeft();
-  }
-  LayoutUnit MarginLineRight() const {
-    return PhysicalMarginToLogical(nullptr).LineRight();
-  }
-  LayoutUnit MarginOver() const {
-    return PhysicalMarginToLogical(nullptr).Over();
-  }
-  LayoutUnit MarginUnder() const {
-    return PhysicalMarginToLogical(nullptr).Under();
-  }
-
+  virtual LayoutUnit MarginBefore(
+      const ComputedStyle* other_style = nullptr) const = 0;
+  virtual LayoutUnit MarginAfter(
+      const ComputedStyle* other_style = nullptr) const = 0;
+  virtual LayoutUnit MarginStart(
+      const ComputedStyle* other_style = nullptr) const = 0;
+  virtual LayoutUnit MarginEnd(
+      const ComputedStyle* other_style = nullptr) const = 0;
+  virtual LayoutUnit MarginOver() const = 0;
+  virtual LayoutUnit MarginUnder() const = 0;
   DISABLE_CFI_PERF LayoutUnit MarginHeight() const {
     return MarginTop() + MarginBottom();
   }
@@ -559,32 +553,6 @@
   LayoutUnit ComputedCSSPadding(const Length&) const;
   bool IsBoxModelObject() const final { return true; }
 
-  PhysicalToLogicalGetter<LayoutUnit, LayoutBoxModelObject>
-  PhysicalPaddingToLogical() const {
-    return PhysicalToLogicalGetter<LayoutUnit, LayoutBoxModelObject>(
-        StyleRef().GetWritingMode(), StyleRef().Direction(), *this,
-        &LayoutBoxModelObject::PaddingTop, &LayoutBoxModelObject::PaddingRight,
-        &LayoutBoxModelObject::PaddingBottom,
-        &LayoutBoxModelObject::PaddingLeft);
-  }
-
-  PhysicalToLogicalGetter<LayoutUnit, LayoutBoxModelObject>
-  PhysicalMarginToLogical(const ComputedStyle* other_style) const {
-    const auto& style = other_style ? *other_style : StyleRef();
-    return PhysicalToLogicalGetter<LayoutUnit, LayoutBoxModelObject>(
-        style.GetWritingMode(), style.Direction(), *this,
-        &LayoutBoxModelObject::MarginTop, &LayoutBoxModelObject::MarginRight,
-        &LayoutBoxModelObject::MarginBottom, &LayoutBoxModelObject::MarginLeft);
-  }
-
-  PhysicalToLogicalGetter<LayoutUnit, LayoutBoxModelObject>
-  PhysicalBorderToLogical() const {
-    return PhysicalToLogicalGetter<LayoutUnit, LayoutBoxModelObject>(
-        StyleRef().GetWritingMode(), StyleRef().Direction(), *this,
-        &LayoutBoxModelObject::BorderTop, &LayoutBoxModelObject::BorderRight,
-        &LayoutBoxModelObject::BorderBottom, &LayoutBoxModelObject::BorderLeft);
-  }
-
   LayoutBoxModelObjectRareData& EnsureRareData() {
     if (!rare_data_)
       rare_data_ = WTF::MakeUnique<LayoutBoxModelObjectRareData>();
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp b/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp
index 3cf1a412..bdde12e 100644
--- a/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutBoxTest.cpp
@@ -4,6 +4,7 @@
 
 #include "core/layout/LayoutBox.h"
 
+#include "build/build_config.h"
 #include "core/html/HTMLElement.h"
 #include "core/layout/ImageQualityController.h"
 #include "core/layout/LayoutTestHelper.h"
@@ -225,7 +226,7 @@
   EXPECT_TRUE(target->HasControlClip());
   EXPECT_TRUE(target->HasClipRelatedProperty());
   EXPECT_TRUE(target->ShouldClipOverflow());
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   EXPECT_EQ(LayoutRect(0, 0, 100, 18), target->ClippingRect());
 #else
   EXPECT_EQ(LayoutRect(2, 2, 96, 46), target->ClippingRect());
diff --git a/third_party/WebKit/Source/core/layout/LayoutInline.cpp b/third_party/WebKit/Source/core/layout/LayoutInline.cpp
index c034749..e053cf9 100644
--- a/third_party/WebKit/Source/core/layout/LayoutInline.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutInline.cpp
@@ -822,6 +822,11 @@
   return LayoutUnit();
 }
 
+LayoutRectOutsets LayoutInline::MarginBoxOutsets() const {
+  return LayoutRectOutsets(MarginTop(), MarginRight(), MarginBottom(),
+                           MarginLeft());
+}
+
 LayoutUnit LayoutInline::MarginLeft() const {
   return ComputeMargin(this, Style()->MarginLeft());
 }
@@ -838,6 +843,34 @@
   return ComputeMargin(this, Style()->MarginBottom());
 }
 
+LayoutUnit LayoutInline::MarginStart(const ComputedStyle* other_style) const {
+  return ComputeMargin(this, StyleRef().MarginStartUsing(
+                                 other_style ? *other_style : StyleRef()));
+}
+
+LayoutUnit LayoutInline::MarginEnd(const ComputedStyle* other_style) const {
+  return ComputeMargin(
+      this, StyleRef().MarginEndUsing(other_style ? *other_style : StyleRef()));
+}
+
+LayoutUnit LayoutInline::MarginBefore(const ComputedStyle* other_style) const {
+  return ComputeMargin(this, StyleRef().MarginBeforeUsing(
+                                 other_style ? *other_style : StyleRef()));
+}
+
+LayoutUnit LayoutInline::MarginAfter(const ComputedStyle* other_style) const {
+  return ComputeMargin(this, StyleRef().MarginAfterUsing(
+                                 other_style ? *other_style : StyleRef()));
+}
+
+LayoutUnit LayoutInline::MarginOver() const {
+  return ComputeMargin(this, Style()->MarginOver());
+}
+
+LayoutUnit LayoutInline::MarginUnder() const {
+  return ComputeMargin(this, Style()->MarginUnder());
+}
+
 bool LayoutInline::NodeAtPoint(HitTestResult& result,
                                const HitTestLocation& location_in_container,
                                const LayoutPoint& accumulated_offset,
diff --git a/third_party/WebKit/Source/core/layout/LayoutInline.h b/third_party/WebKit/Source/core/layout/LayoutInline.h
index 0ae88fee..3b3348b3 100644
--- a/third_party/WebKit/Source/core/layout/LayoutInline.h
+++ b/third_party/WebKit/Source/core/layout/LayoutInline.h
@@ -135,10 +135,20 @@
     return ToElement(LayoutBoxModelObject::GetNode());
   }
 
+  LayoutRectOutsets MarginBoxOutsets() const final;
   LayoutUnit MarginLeft() const final;
   LayoutUnit MarginRight() const final;
   LayoutUnit MarginTop() const final;
   LayoutUnit MarginBottom() const final;
+  LayoutUnit MarginBefore(
+      const ComputedStyle* other_style = nullptr) const final;
+  LayoutUnit MarginAfter(
+      const ComputedStyle* other_style = nullptr) const final;
+  LayoutUnit MarginStart(
+      const ComputedStyle* other_style = nullptr) const final;
+  LayoutUnit MarginEnd(const ComputedStyle* other_style = nullptr) const final;
+  LayoutUnit MarginOver() const final;
+  LayoutUnit MarginUnder() const final;
 
   void AbsoluteRects(Vector<IntRect>&,
                      const LayoutPoint& accumulated_offset) const final;
diff --git a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h
index 435e23c..b654339 100644
--- a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h
+++ b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h
@@ -48,6 +48,10 @@
   void UpdateLayout() override;
 
   // Scrollbar parts needs to be rendered at device pixel boundaries.
+  LayoutRectOutsets MarginBoxOutsets() const override {
+    DCHECK(IsIntegerValue(LayoutBlock::MarginBoxOutsets().Top()));
+    return LayoutBlock::MarginBoxOutsets();
+  }
   LayoutUnit MarginTop() const override {
     DCHECK(IsIntegerValue(LayoutBlock::MarginTop()));
     return LayoutBlock::MarginTop();
@@ -98,6 +102,10 @@
   LayoutUnit PaddingBottom() const override { return LayoutUnit(); }
   LayoutUnit PaddingLeft() const override { return LayoutUnit(); }
   LayoutUnit PaddingRight() const override { return LayoutUnit(); }
+  LayoutUnit PaddingBefore() const override { return LayoutUnit(); }
+  LayoutUnit PaddingAfter() const override { return LayoutUnit(); }
+  LayoutUnit PaddingStart() const override { return LayoutUnit(); }
+  LayoutUnit PaddingEnd() const override { return LayoutUnit(); }
 
   void LayoutHorizontalPart();
   void LayoutVerticalPart();
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.cpp b/third_party/WebKit/Source/core/layout/LayoutTable.cpp
index 0ce46b1..1c4df9ff 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTable.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutTable.cpp
@@ -1135,36 +1135,36 @@
   needs_section_recalc_ = false;
 }
 
-LayoutUnit LayoutTable::BorderLeft() const {
+LayoutUnit LayoutTable::BorderBefore() const {
   if (ShouldCollapseBorders()) {
     UpdateCollapsedOuterBorders();
-    return LayoutUnit(LogicalCollapsedOuterBorderToPhysical().Left());
+    return LayoutUnit(collapsed_outer_border_before_);
   }
-  return LayoutUnit(LayoutBlock::BorderLeft().ToInt());
+  return LayoutUnit(LayoutBlock::BorderBefore().ToInt());
 }
 
-LayoutUnit LayoutTable::BorderRight() const {
+LayoutUnit LayoutTable::BorderAfter() const {
   if (ShouldCollapseBorders()) {
     UpdateCollapsedOuterBorders();
-    return LayoutUnit(LogicalCollapsedOuterBorderToPhysical().Right());
+    return LayoutUnit(collapsed_outer_border_after_);
   }
-  return LayoutUnit(LayoutBlock::BorderRight().ToInt());
+  return LayoutUnit(LayoutBlock::BorderAfter().ToInt());
 }
 
-LayoutUnit LayoutTable::BorderTop() const {
+LayoutUnit LayoutTable::BorderStart() const {
   if (ShouldCollapseBorders()) {
     UpdateCollapsedOuterBorders();
-    return LayoutUnit(LogicalCollapsedOuterBorderToPhysical().Top());
+    return LayoutUnit(collapsed_outer_border_start_);
   }
-  return LayoutUnit(LayoutBlock::BorderTop().ToInt());
+  return LayoutUnit(LayoutBlock::BorderStart().ToInt());
 }
 
-LayoutUnit LayoutTable::BorderBottom() const {
+LayoutUnit LayoutTable::BorderEnd() const {
   if (ShouldCollapseBorders()) {
     UpdateCollapsedOuterBorders();
-    return LayoutUnit(LogicalCollapsedOuterBorderToPhysical().Bottom());
+    return LayoutUnit(collapsed_outer_border_end_);
   }
-  return LayoutUnit(LayoutBlock::BorderBottom().ToInt());
+  return LayoutUnit(LayoutBlock::BorderEnd().ToInt());
 }
 
 LayoutTableSection* LayoutTable::SectionAbove(
@@ -1502,36 +1502,28 @@
   if (ShouldCollapseBorders())
     return LayoutUnit();
 
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(LayoutBlock::PaddingTop().ToInt());
+  return LayoutBlock::PaddingTop();
 }
 
 LayoutUnit LayoutTable::PaddingBottom() const {
   if (ShouldCollapseBorders())
     return LayoutUnit();
 
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(LayoutBlock::PaddingBottom().ToInt());
+  return LayoutBlock::PaddingBottom();
 }
 
 LayoutUnit LayoutTable::PaddingLeft() const {
   if (ShouldCollapseBorders())
     return LayoutUnit();
 
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(LayoutBlock::PaddingLeft().ToInt());
+  return LayoutBlock::PaddingLeft();
 }
 
 LayoutUnit LayoutTable::PaddingRight() const {
   if (ShouldCollapseBorders())
     return LayoutUnit();
 
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(LayoutBlock::PaddingRight().ToInt());
+  return LayoutBlock::PaddingRight();
 }
 
 unsigned LayoutTable::ComputeCollapsedOuterBorderBefore() const {
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.h b/third_party/WebKit/Source/core/layout/LayoutTable.h
index f6842f0..8098318a 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTable.h
+++ b/third_party/WebKit/Source/core/layout/LayoutTable.h
@@ -148,10 +148,40 @@
     return Style()->BorderCollapse() == EBorderCollapse::kCollapse;
   }
 
-  LayoutUnit BorderLeft() const override;
-  LayoutUnit BorderRight() const override;
-  LayoutUnit BorderTop() const override;
-  LayoutUnit BorderBottom() const override;
+  LayoutUnit BorderStart() const override;
+  LayoutUnit BorderEnd() const override;
+  LayoutUnit BorderBefore() const override;
+  LayoutUnit BorderAfter() const override;
+
+  LayoutUnit BorderLeft() const override {
+    if (Style()->IsHorizontalWritingMode())
+      return Style()->IsLeftToRightDirection() ? BorderStart() : BorderEnd();
+    return Style()->IsFlippedBlocksWritingMode() ? BorderAfter()
+                                                 : BorderBefore();
+  }
+
+  LayoutUnit BorderRight() const override {
+    if (Style()->IsHorizontalWritingMode())
+      return Style()->IsLeftToRightDirection() ? BorderEnd() : BorderStart();
+    return Style()->IsFlippedBlocksWritingMode() ? BorderBefore()
+                                                 : BorderAfter();
+  }
+
+  LayoutUnit BorderTop() const override {
+    if (Style()->IsHorizontalWritingMode()) {
+      return Style()->IsFlippedBlocksWritingMode() ? BorderAfter()
+                                                   : BorderBefore();
+    }
+    return Style()->IsLeftToRightDirection() ? BorderStart() : BorderEnd();
+  }
+
+  LayoutUnit BorderBottom() const override {
+    if (Style()->IsHorizontalWritingMode()) {
+      return Style()->IsFlippedBlocksWritingMode() ? BorderBefore()
+                                                   : BorderAfter();
+    }
+    return Style()->IsLeftToRightDirection() ? BorderEnd() : BorderStart();
+  }
 
   void AddChild(LayoutObject* child,
                 LayoutObject* before_child = nullptr) override;
@@ -267,6 +297,15 @@
   LayoutUnit PaddingLeft() const override;
   LayoutUnit PaddingRight() const override;
 
+  // Override paddingStart/End to return pixel values to match behavor of
+  // LayoutTableCell.
+  LayoutUnit PaddingEnd() const override {
+    return LayoutUnit(LayoutBlock::PaddingEnd().ToInt());
+  }
+  LayoutUnit PaddingStart() const override {
+    return LayoutUnit(LayoutBlock::PaddingStart().ToInt());
+  }
+
   LayoutUnit BordersPaddingAndSpacingInRowDirection() const {
     // 'border-spacing' only applies to separate borders (see 17.6.1 The
     // separated borders model).
@@ -551,13 +590,6 @@
     return NumEffectiveColumns();
   }
 
-  LogicalToPhysical<unsigned> LogicalCollapsedOuterBorderToPhysical() const {
-    return LogicalToPhysical<unsigned>(
-        StyleRef().GetWritingMode(), StyleRef().Direction(),
-        collapsed_outer_border_start_, collapsed_outer_border_end_,
-        collapsed_outer_border_before_, collapsed_outer_border_after_);
-  }
-
   short h_spacing_;
   short v_spacing_;
 
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp
index e991442..dcca5eec 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp
@@ -322,34 +322,60 @@
 
 LayoutUnit LayoutTableCell::PaddingTop() const {
   LayoutUnit result = ComputedCSSPaddingTop();
-  result += LogicalIntrinsicPaddingToPhysical().Top();
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(result.ToInt());
+  if (IsHorizontalWritingMode()) {
+    result += (blink::IsHorizontalWritingMode(Style()->GetWritingMode())
+                   ? IntrinsicPaddingBefore()
+                   : IntrinsicPaddingAfter());
+  }
+  // TODO(leviw): The floor call should be removed when Table is sub-pixel
+  // aware. crbug.com/377847
+  return LayoutUnit(result.Floor());
 }
 
 LayoutUnit LayoutTableCell::PaddingBottom() const {
   LayoutUnit result = ComputedCSSPaddingBottom();
-  result += LogicalIntrinsicPaddingToPhysical().Bottom();
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(result.ToInt());
+  if (IsHorizontalWritingMode()) {
+    result += (blink::IsHorizontalWritingMode(Style()->GetWritingMode())
+                   ? IntrinsicPaddingAfter()
+                   : IntrinsicPaddingBefore());
+  }
+  // TODO(leviw): The floor call should be removed when Table is sub-pixel
+  // aware. crbug.com/377847
+  return LayoutUnit(result.Floor());
 }
 
 LayoutUnit LayoutTableCell::PaddingLeft() const {
   LayoutUnit result = ComputedCSSPaddingLeft();
-  result += LogicalIntrinsicPaddingToPhysical().Left();
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(result.ToInt());
+  if (!IsHorizontalWritingMode()) {
+    result += (IsFlippedLinesWritingMode(Style()->GetWritingMode())
+                   ? IntrinsicPaddingBefore()
+                   : IntrinsicPaddingAfter());
+  }
+  // TODO(leviw): The floor call should be removed when Table is sub-pixel
+  // aware. crbug.com/377847
+  return LayoutUnit(result.Floor());
 }
 
 LayoutUnit LayoutTableCell::PaddingRight() const {
   LayoutUnit result = ComputedCSSPaddingRight();
-  result += LogicalIntrinsicPaddingToPhysical().Right();
-  // TODO(crbug.com/377847): The ToInt call should be removed when Table is
-  // sub-pixel aware.
-  return LayoutUnit(result.ToInt());
+  if (!IsHorizontalWritingMode()) {
+    result += (IsFlippedLinesWritingMode(Style()->GetWritingMode())
+                   ? IntrinsicPaddingAfter()
+                   : IntrinsicPaddingBefore());
+  }
+  // TODO(leviw): The floor call should be removed when Table is sub-pixel
+  // aware. crbug.com/377847
+  return LayoutUnit(result.Floor());
+}
+
+LayoutUnit LayoutTableCell::PaddingBefore() const {
+  return LayoutUnit(ComputedCSSPaddingBefore().Floor() +
+                    IntrinsicPaddingBefore());
+}
+
+LayoutUnit LayoutTableCell::PaddingAfter() const {
+  return LayoutUnit(ComputedCSSPaddingAfter().Floor() +
+                    IntrinsicPaddingAfter());
 }
 
 void LayoutTableCell::SetOverrideLogicalContentHeightFromRowHeight(
@@ -1034,6 +1060,33 @@
              : LayoutBlockFlow::BorderBottom();
 }
 
+// FIXME: https://bugs.webkit.org/show_bug.cgi?id=46191, make the collapsed
+// border drawing work with different block flow values instead of being
+// hard-coded to top-to-bottom.
+LayoutUnit LayoutTableCell::BorderStart() const {
+  return Table()->ShouldCollapseBorders()
+             ? LayoutUnit(CollapsedBorderHalfStart(false))
+             : LayoutBlockFlow::BorderStart();
+}
+
+LayoutUnit LayoutTableCell::BorderEnd() const {
+  return Table()->ShouldCollapseBorders()
+             ? LayoutUnit(CollapsedBorderHalfEnd(false))
+             : LayoutBlockFlow::BorderEnd();
+}
+
+LayoutUnit LayoutTableCell::BorderBefore() const {
+  return Table()->ShouldCollapseBorders()
+             ? LayoutUnit(CollapsedBorderHalfBefore(false))
+             : LayoutBlockFlow::BorderBefore();
+}
+
+LayoutUnit LayoutTableCell::BorderAfter() const {
+  return Table()->ShouldCollapseBorders()
+             ? LayoutUnit(CollapsedBorderHalfAfter(false))
+             : LayoutBlockFlow::BorderAfter();
+}
+
 void LayoutTableCell::Paint(const PaintInfo& paint_info,
                             const LayoutPoint& paint_offset) const {
   TableCellPainter(*this).Paint(paint_info, paint_offset);
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.h b/third_party/WebKit/Source/core/layout/LayoutTableCell.h
index 73ea06c..ec1add8 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTableCell.h
+++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.h
@@ -182,6 +182,10 @@
   LayoutUnit BorderRight() const override;
   LayoutUnit BorderTop() const override;
   LayoutUnit BorderBottom() const override;
+  LayoutUnit BorderStart() const override;
+  LayoutUnit BorderEnd() const override;
+  LayoutUnit BorderBefore() const override;
+  LayoutUnit BorderAfter() const override;
 
   void UpdateLayout() override;
 
@@ -213,6 +217,13 @@
   LayoutUnit PaddingLeft() const override;
   LayoutUnit PaddingRight() const override;
 
+  // FIXME: For now we just assume the cell has the same block flow direction as
+  // the table. It's likely we'll create an extra anonymous LayoutBlock to
+  // handle mixing directionality anyway, in which case we can lock the block
+  // flow directionality of the cells to the table's directionality.
+  LayoutUnit PaddingBefore() const override;
+  LayoutUnit PaddingAfter() const override;
+
   void SetOverrideLogicalContentHeightFromRowHeight(LayoutUnit);
 
   void ScrollbarsChanged(bool horizontal_scrollbar_changed,
@@ -419,11 +430,6 @@
     return 0;
   }
 
-  LogicalToPhysical<int> LogicalIntrinsicPaddingToPhysical() const {
-    return LogicalToPhysical<int>(
-        StyleRef().GetWritingMode(), StyleRef().Direction(), 0, 0,
-        intrinsic_padding_before_, intrinsic_padding_after_);
-  }
   void SetIntrinsicPaddingBefore(int p) { intrinsic_padding_before_ = p; }
   void SetIntrinsicPaddingAfter(int p) { intrinsic_padding_after_ = p; }
   void SetIntrinsicPadding(int before, int after) {
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp b/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp
index c2c688d..0811b18 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp
@@ -25,6 +25,7 @@
 
 #include "core/layout/LayoutTableCell.h"
 
+#include "build/build_config.h"
 #include "core/layout/LayoutTestHelper.h"
 
 namespace blink {
@@ -59,7 +60,7 @@
 // See: https://bugs.webkit.org/show_bug.cgi?id=74089
 // TODO(dgrogan): These tests started flaking on Mac try bots around 2016-07-28.
 // https://crbug.com/632816
-#if !OS(ANDROID) && !OS(MACOSX)
+#if !defined(OS_ANDROID) && !defined(OS_MACOSX)
 
 TEST_F(LayoutTableCellDeathTest, CrashIfColumnOverflowOnSetting) {
   ASSERT_DEATH(cell_->SetAbsoluteColumnIndex(kMaxColumnIndex + 1), "");
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableRowTest.cpp b/third_party/WebKit/Source/core/layout/LayoutTableRowTest.cpp
index 211e8178..bae242f 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTableRowTest.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutTableRowTest.cpp
@@ -25,6 +25,7 @@
 
 #include "core/layout/LayoutTableRow.h"
 
+#include "build/build_config.h"
 #include "core/layout/LayoutTestHelper.h"
 
 namespace blink {
@@ -58,7 +59,7 @@
 // See: https://bugs.webkit.org/show_bug.cgi?id=74089
 // TODO(dgrogan): These tests started flaking on Mac try bots around 2016-07-28.
 // https://crbug.com/632816
-#if !OS(ANDROID) && !OS(MACOSX)
+#if !defined(OS_ANDROID) && !defined(OS_MACOSX)
 
 TEST_F(LayoutTableRowDeathTest, CrashIfRowOverflowOnSetting) {
   ASSERT_DEATH(row_->SetRowIndex(kMaxRowIndex + 1), "");
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableTest.cpp b/third_party/WebKit/Source/core/layout/LayoutTableTest.cpp
index 109d8eb6..2781377 100644
--- a/third_party/WebKit/Source/core/layout/LayoutTableTest.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutTableTest.cpp
@@ -203,25 +203,6 @@
   EXPECT_EQ(999999, table->OffsetWidth());
 }
 
-TEST_F(LayoutTableTest, PaddingWithCollapsedBorder) {
-  SetBodyInnerHTML(
-      "<table id='table' style='padding: 20px; border-collapse: collapse'>"
-      "  <tr><td>TD</td</tr>"
-      "</table>");
-
-  auto* table = GetTableByElementId("table");
-  EXPECT_EQ(0, table->PaddingLeft());
-  EXPECT_EQ(0, table->PaddingRight());
-  EXPECT_EQ(0, table->PaddingTop());
-  EXPECT_EQ(0, table->PaddingBottom());
-  EXPECT_EQ(0, table->PaddingStart());
-  EXPECT_EQ(0, table->PaddingEnd());
-  EXPECT_EQ(0, table->PaddingBefore());
-  EXPECT_EQ(0, table->PaddingAfter());
-  EXPECT_EQ(0, table->PaddingOver());
-  EXPECT_EQ(0, table->PaddingUnder());
-}
-
 }  // anonymous namespace
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/LayoutThemeMobile.cpp b/third_party/WebKit/Source/core/layout/LayoutThemeMobile.cpp
index 6755215..c80faef 100644
--- a/third_party/WebKit/Source/core/layout/LayoutThemeMobile.cpp
+++ b/third_party/WebKit/Source/core/layout/LayoutThemeMobile.cpp
@@ -25,6 +25,7 @@
 
 #include "core/layout/LayoutThemeMobile.h"
 
+#include "build/build_config.h"
 #include "core/style/ComputedStyle.h"
 #include "platform/DataResourceHelper.h"
 #include "platform/LayoutTestSupport.h"
@@ -68,7 +69,7 @@
 
 bool LayoutThemeMobile::ShouldUseFallbackTheme(
     const ComputedStyle& style) const {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // Mac WebThemeEngine cannot handle these controls.
   ControlPart part = style.Appearance();
   if (part == kCheckboxPart || part == kRadioPart)
diff --git a/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp b/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp
index cb39348..dc7f2411 100644
--- a/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp
+++ b/third_party/WebKit/Source/core/layout/ScrollbarsTest.cpp
@@ -2,6 +2,7 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "build/build_config.h"
 #include "core/frame/LocalFrameView.h"
 #include "core/frame/WebLocalFrameBase.h"
 #include "core/layout/LayoutView.h"
@@ -176,7 +177,7 @@
 // Test both overlay and non-overlay scrollbars.
 INSTANTIATE_TEST_CASE_P(All, ScrollbarAppearanceTest, ::testing::Bool());
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 // Ensure that the minimum length for a scrollbar thumb comes from the
 // WebThemeEngine. Note, Mac scrollbars differ from all other platforms so this
 // test doesn't apply there. https://crbug.com/682209.
diff --git a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp
index 90e423e6..f78f76f 100644
--- a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp
+++ b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp
@@ -963,7 +963,7 @@
   // actually the opposite shadow that applies, since the line is "upside down"
   // in terms of block coordinates.
   LayoutRectOutsets logical_outsets(
-      outsets.LineOrientationOutsetsWithFlippedLines(writing_mode));
+      outsets.LogicalOutsetsWithFlippedLines(writing_mode));
 
   LayoutRect shadow_bounds(LogicalFrameRect());
   shadow_bounds.Expand(logical_outsets);
@@ -987,7 +987,7 @@
   // actually the opposite border that applies, since the line is "upside down"
   // in terms of block coordinates. vertical-rl is the flipped line mode.
   LayoutRectOutsets logical_outsets =
-      style.BorderImageOutsets().LineOrientationOutsetsWithFlippedLines(
+      style.BorderImageOutsets().LogicalOutsetsWithFlippedLines(
           style.GetWritingMode());
 
   if (!IncludeLogicalLeftEdge())
@@ -1069,7 +1069,7 @@
   if (ShadowList* text_shadow = style.TextShadow()) {
     text_shadow_logical_outsets =
         LayoutRectOutsets(text_shadow->RectOutsetsIncludingOriginal())
-            .LineOrientationOutsets(style.GetWritingMode());
+            .LogicalOutsets(style.GetWritingMode());
   }
 
   // FIXME: This code currently uses negative values for expansion of the top
diff --git a/third_party/WebKit/Source/core/layout/shapes/ShapeOutsideInfo.cpp b/third_party/WebKit/Source/core/layout/shapes/ShapeOutsideInfo.cpp
index 914cc9cd..2cf99987 100644
--- a/third_party/WebKit/Source/core/layout/shapes/ShapeOutsideInfo.cpp
+++ b/third_party/WebKit/Source/core/layout/shapes/ShapeOutsideInfo.cpp
@@ -116,10 +116,11 @@
 static LayoutRect GetShapeImageMarginRect(
     const LayoutBox& layout_box,
     const LayoutSize& reference_box_logical_size) {
-  LayoutPoint margin_box_origin(
-      -layout_box.MarginLineLeft() - layout_box.BorderAndPaddingLogicalLeft(),
-      -layout_box.MarginBefore() - layout_box.BorderBefore() -
-          layout_box.PaddingBefore());
+  LayoutPoint margin_box_origin(-layout_box.MarginLogicalLeft() -
+                                    layout_box.BorderAndPaddingLogicalLeft(),
+                                -layout_box.MarginBefore() -
+                                    layout_box.BorderBefore() -
+                                    layout_box.PaddingBefore());
   LayoutSize margin_box_size_delta(
       layout_box.MarginLogicalWidth() +
           layout_box.BorderAndPaddingLogicalWidth(),
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
index 3c745b8..16c4ab0 100644
--- a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
+++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -253,6 +253,12 @@
   return GetFrame()->FrameScheduler()->LoadingTaskRunner();
 }
 
+WebFrameScheduler* FrameFetchContext::GetFrameScheduler() {
+  if (IsDetached())
+    return nullptr;
+  return GetFrame()->FrameScheduler();
+}
+
 KURL FrameFetchContext::GetFirstPartyForCookies() const {
   if (IsDetached())
     return frozen_state_->first_party_for_cookies;
@@ -267,6 +273,7 @@
   if (!document_loader_)
     return FrameOfImportsController();
 
+  DCHECK(!IsDetached());
   LocalFrame* frame = document_loader_->GetFrame();
   DCHECK(frame);
   return frame;
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.h b/third_party/WebKit/Source/core/loader/FrameFetchContext.h
index 6260d7d..d59f33e3 100644
--- a/third_party/WebKit/Source/core/loader/FrameFetchContext.h
+++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.h
@@ -179,6 +179,9 @@
   LocalFrame* FrameOfImportsController() const;
   RefPtr<WebTaskRunner> GetTaskRunner() const;
 
+  // FetchContext overrides:
+  WebFrameScheduler* GetFrameScheduler() override;
+
   // BaseFetchContext overrides:
   KURL GetFirstPartyForCookies() const override;
   ContentSettingsClient* GetContentSettingsClient() const override;
diff --git a/third_party/WebKit/Source/core/loader/NavigationPolicy.cpp b/third_party/WebKit/Source/core/loader/NavigationPolicy.cpp
index 90b2baa..88dabaa15 100644
--- a/third_party/WebKit/Source/core/loader/NavigationPolicy.cpp
+++ b/third_party/WebKit/Source/core/loader/NavigationPolicy.cpp
@@ -30,6 +30,7 @@
 
 #include "core/loader/NavigationPolicy.h"
 
+#include "build/build_config.h"
 #include "platform/wtf/Assertions.h"
 
 namespace blink {
@@ -40,7 +41,7 @@
                                     bool alt,
                                     bool meta,
                                     NavigationPolicy* policy) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   const bool new_tab_modifier = (button == 1) || meta;
 #else
   const bool new_tab_modifier = (button == 1) || ctrl;
diff --git a/third_party/WebKit/Source/core/page/ChromeClient.h b/third_party/WebKit/Source/core/page/ChromeClient.h
index ecfe6bab5..40d1a17f 100644
--- a/third_party/WebKit/Source/core/page/ChromeClient.h
+++ b/third_party/WebKit/Source/core/page/ChromeClient.h
@@ -39,7 +39,6 @@
 #include "platform/graphics/TouchAction.h"
 #include "platform/heap/Handle.h"
 #include "platform/scroll/ScrollTypes.h"
-#include "platform/text/TextDirection.h"
 #include "platform/wtf/Forward.h"
 #include "platform/wtf/Optional.h"
 #include "platform/wtf/Vector.h"
diff --git a/third_party/WebKit/Source/core/page/DragController.cpp b/third_party/WebKit/Source/core/page/DragController.cpp
index ba8ef57..f067d17 100644
--- a/third_party/WebKit/Source/core/page/DragController.cpp
+++ b/third_party/WebKit/Source/core/page/DragController.cpp
@@ -27,7 +27,9 @@
 #include "core/page/DragController.h"
 
 #include <memory>
+
 #include "bindings/core/v8/ExceptionState.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/InputTypeNames.h"
 #include "core/clipboard/DataObject.h"
@@ -91,7 +93,7 @@
 #include "public/platform/WebPoint.h"
 #include "public/platform/WebScreenInfo.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
 #endif
 
@@ -985,7 +987,7 @@
 }
 
 static const IntSize MaxDragImageSize(float device_scale_factor) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // Match Safari's drag image size.
   static const IntSize kMaxDragImageSize(400, 400);
 #else
@@ -1278,7 +1280,7 @@
 bool DragController::IsCopyKeyDown(DragData* drag_data) {
   int modifiers = drag_data->GetModifiers();
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   return modifiers & WebInputEvent::kAltKey;
 #else
   return modifiers & WebInputEvent::kControlKey;
diff --git a/third_party/WebKit/Source/core/page/EffectiveNavigationPolicyTest.cpp b/third_party/WebKit/Source/core/page/EffectiveNavigationPolicyTest.cpp
index 357fde7a..595b6b4 100644
--- a/third_party/WebKit/Source/core/page/EffectiveNavigationPolicyTest.cpp
+++ b/third_party/WebKit/Source/core/page/EffectiveNavigationPolicyTest.cpp
@@ -28,6 +28,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "build/build_config.h"
 #include "core/page/CreateWindow.h"
 #include "public/platform/WebInputEvent.h"
 #include "public/platform/WebMouseEvent.h"
@@ -82,7 +83,7 @@
 }
 
 TEST_F(EffectiveNavigationPolicyTest, ControlOrMetaLeftClick) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   int modifiers = WebInputEvent::kMetaKey;
 #else
   int modifiers = WebInputEvent::kControlKey;
@@ -94,7 +95,7 @@
 }
 
 TEST_F(EffectiveNavigationPolicyTest, ControlOrMetaLeftClickPopup) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   int modifiers = WebInputEvent::kMetaKey;
 #else
   int modifiers = WebInputEvent::kControlKey;
@@ -106,7 +107,7 @@
 }
 
 TEST_F(EffectiveNavigationPolicyTest, ControlOrMetaAndShiftLeftClick) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   int modifiers = WebInputEvent::kMetaKey;
 #else
   int modifiers = WebInputEvent::kControlKey;
@@ -119,7 +120,7 @@
 }
 
 TEST_F(EffectiveNavigationPolicyTest, ControlOrMetaAndShiftLeftClickPopup) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   int modifiers = WebInputEvent::kMetaKey;
 #else
   int modifiers = WebInputEvent::kControlKey;
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
index de26df74..fc95746 100644
--- a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -25,6 +25,7 @@
 
 #include "core/page/scrolling/ScrollingCoordinator.h"
 
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/dom/Node.h"
 #include "core/frame/EventHandlerRegistry.h"
@@ -52,7 +53,7 @@
 #include "platform/graphics/CompositorElementId.h"
 #include "platform/graphics/GraphicsLayer.h"
 #include "platform/instrumentation/tracing/TraceEvent.h"
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include "platform/mac/ScrollAnimatorMac.h"
 #endif
 #include <memory>
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinatorTest.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinatorTest.cpp
index 29a30c5..e4c63b0 100644
--- a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinatorTest.cpp
+++ b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinatorTest.cpp
@@ -24,6 +24,7 @@
 
 #include "core/page/scrolling/ScrollingCoordinator.h"
 
+#include "build/build_config.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StyleSheetList.h"
 #include "core/exported/WebViewBase.h"
@@ -570,7 +571,7 @@
   ASSERT_TRUE(web_scroll_layer->UserScrollableHorizontal());
   ASSERT_TRUE(web_scroll_layer->UserScrollableVertical());
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   // Now verify we've attached impl-side scrollbars onto the scrollbar layers
   ASSERT_TRUE(composited_layer_mapping->LayerForHorizontalScrollbar());
   ASSERT_TRUE(composited_layer_mapping->LayerForHorizontalScrollbar()
@@ -681,7 +682,7 @@
   WebLayer* web_scroll_layer = scroll_layer->PlatformLayer();
   ASSERT_TRUE(web_scroll_layer->Scrollable());
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   // Now verify we've attached impl-side scrollbars onto the scrollbar layers
   GraphicsLayer* horizontal_scrollbar_layer =
       inner_frame_view->LayoutViewportScrollableArea()
@@ -777,7 +778,7 @@
       scrollbar_graphics_layer->PlatformLayer()->ShouldScrollOnMainThread());
 }
 
-#if OS(MACOSX) || OS(ANDROID)
+#if defined(OS_MACOSX) || defined(OS_ANDROID)
 TEST_P(ScrollingCoordinatorTest,
        DISABLED_setupScrollbarLayerShouldSetScrollLayerOpaque)
 #else
diff --git a/third_party/WebKit/Source/core/paint/InlineTextBoxPainter.cpp b/third_party/WebKit/Source/core/paint/InlineTextBoxPainter.cpp
index 23c13dc..262a323 100644
--- a/third_party/WebKit/Source/core/paint/InlineTextBoxPainter.cpp
+++ b/third_party/WebKit/Source/core/paint/InlineTextBoxPainter.cpp
@@ -4,6 +4,7 @@
 
 #include "core/paint/InlineTextBoxPainter.h"
 
+#include "build/build_config.h"
 #include "core/editing/Editor.h"
 #include "core/editing/markers/CompositionMarker.h"
 #include "core/editing/markers/DocumentMarkerController.h"
@@ -700,7 +701,7 @@
 
 namespace {
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 
 static const float kMarkerWidth = 4;
 static const float kMarkerHeight = 2;
@@ -744,7 +745,7 @@
   return recorder.finishRecordingAsPicture();
 }
 
-#else  // OS(MACOSX)
+#else  // defined(OS_MACOSX)
 
 static const float kMarkerWidth = 4;
 static const float kMarkerHeight = 3;
@@ -785,7 +786,7 @@
   return recorder.finishRecordingAsPicture();
 }
 
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
 
 void DrawDocumentMarker(GraphicsContext& context,
                         const FloatPoint& pt,
@@ -807,7 +808,7 @@
   SkScalar origin_x = WebCoreFloatToSkScalar(pt.X());
   SkScalar origin_y = WebCoreFloatToSkScalar(pt.Y());
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // Make sure to draw only complete dots, and finish inside the marked text.
   width -= fmodf(width, kMarkerWidth * zoom);
 #else
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerClipperTest.cpp b/third_party/WebKit/Source/core/paint/PaintLayerClipperTest.cpp
index 2c9b9f1..4a87c74d 100644
--- a/third_party/WebKit/Source/core/paint/PaintLayerClipperTest.cpp
+++ b/third_party/WebKit/Source/core/paint/PaintLayerClipperTest.cpp
@@ -4,6 +4,7 @@
 
 #include "core/paint/PaintLayerClipper.h"
 
+#include "build/build_config.h"
 #include "core/layout/LayoutBoxModelObject.h"
 #include "core/layout/LayoutTestHelper.h"
 #include "core/layout/LayoutView.h"
@@ -80,7 +81,7 @@
   target_paint_layer->Clipper(PaintLayer::kUseGeometryMapper)
       .CalculateRects(context, LayoutRect(LayoutRect::InfiniteIntRect()),
                       layer_bounds, background_rect, foreground_rect);
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // If the PaintLayer clips overflow, the background rect is intersected with
   // the PaintLayer bounds...
   EXPECT_EQ(LayoutRect(3, 4, 210, 28), background_rect.Rect());
@@ -188,9 +189,9 @@
       .CalculateRects(context, LayoutRect(LayoutRect::InfiniteIntRect()),
                       layer_bounds, background_rect, foreground_rect);
 // The control clip for a select excludes the area for the down arrow.
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   EXPECT_EQ(LayoutRect(16, 9, 79, 13), foreground_rect.Rect());
-#elif OS(WIN)
+#elif defined(OS_WIN)
   EXPECT_EQ(LayoutRect(17, 9, 60, 16), foreground_rect.Rect());
 #else
   EXPECT_EQ(LayoutRect(17, 9, 60, 15), foreground_rect.Rect());
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.cpp b/third_party/WebKit/Source/core/style/ComputedStyle.cpp
index 15b31bd..4c4bb52 100644
--- a/third_party/WebKit/Source/core/style/ComputedStyle.cpp
+++ b/third_party/WebKit/Source/core/style/ComputedStyle.cpp
@@ -25,6 +25,8 @@
 
 #include <algorithm>
 #include <memory>
+
+#include "build/build_config.h"
 #include "core/animation/css/CSSAnimationData.h"
 #include "core/animation/css/CSSTransitionData.h"
 #include "core/css/CSSPaintValue.h"
@@ -1882,7 +1884,7 @@
 }
 
 float ComputedStyle::GetOutlineStrokeWidthForFocusRing() const {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   return OutlineWidth();
 #else
   // Draw an outline with thickness in proportion to the zoom level, but never
diff --git a/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp b/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp
index 8a47f28..02c6c21 100644
--- a/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp
+++ b/third_party/WebKit/Source/core/style/ComputedStyleTest.cpp
@@ -4,6 +4,7 @@
 
 #include "core/style/ComputedStyle.h"
 
+#include "build/build_config.h"
 #include "core/style/ClipPathOperation.h"
 #include "core/style/ShapeValue.h"
 #include "core/style/StyleDifference.h"
@@ -47,7 +48,7 @@
 TEST(ComputedStyleTest, FocusRingWidth) {
   RefPtr<ComputedStyle> style = ComputedStyle::Create();
   style->SetEffectiveZoom(3.5);
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   style->SetOutlineStyle(EBorderStyle::kSolid);
   ASSERT_EQ(3, style->GetOutlineStrokeWidthForFocusRing());
 #else
@@ -62,7 +63,7 @@
   style->SetOutlineStyle(EBorderStyle::kSolid);
   style->SetOutlineStyleIsAuto(kOutlineIsAutoOn);
   style->SetEffectiveZoom(4.75);
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   ASSERT_EQ(4, style->OutlineOutsetExtent());
 #else
   ASSERT_EQ(3, style->OutlineOutsetExtent());
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/BUILD.gn b/third_party/WebKit/Source/modules/encryptedmedia/BUILD.gn
index 771f45e..4e95d23 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/BUILD.gn
+++ b/third_party/WebKit/Source/modules/encryptedmedia/BUILD.gn
@@ -28,6 +28,10 @@
     "MediaKeysClient.h",
     "MediaKeysController.cpp",
     "MediaKeysController.h",
+    "MediaKeysGetStatusForPolicy.cpp",
+    "MediaKeysGetStatusForPolicy.h",
+    "MediaKeysPolicy.cpp",
+    "MediaKeysPolicy.h",
     "NavigatorRequestMediaKeySystemAccess.cpp",
     "NavigatorRequestMediaKeySystemAccess.h",
   ]
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.cpp b/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.cpp
index 19b8679f..2c4fe40a 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.cpp
+++ b/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.cpp
@@ -63,6 +63,13 @@
   Reject(kInvalidStateError, "Unexpected completion.");
 }
 
+void ContentDecryptionModuleResultPromise::CompleteWithKeyStatus(
+    WebEncryptedMediaKeyInformation::KeyStatus) {
+  if (!IsValidToFulfillPromise())
+    return;
+  Reject(kInvalidStateError, "Unexpected completion.");
+}
+
 void ContentDecryptionModuleResultPromise::CompleteWithError(
     WebContentDecryptionModuleException exception_code,
     unsigned long system_code,
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.h b/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.h
index 15d4d32..dba52f6 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.h
+++ b/third_party/WebKit/Source/modules/encryptedmedia/ContentDecryptionModuleResultPromise.h
@@ -8,6 +8,7 @@
 #include "bindings/core/v8/ScriptPromiseResolver.h"
 #include "core/dom/ExceptionCode.h"
 #include "platform/ContentDecryptionModuleResult.h"
+#include "public/platform/WebEncryptedMediaKeyInformation.h"
 
 namespace blink {
 
@@ -39,6 +40,8 @@
       WebContentDecryptionModule*) override;
   void CompleteWithSession(
       WebContentDecryptionModuleResult::SessionStatus) override;
+  void CompleteWithKeyStatus(
+      WebEncryptedMediaKeyInformation::KeyStatus) override;
   void CompleteWithError(WebContentDecryptionModuleException,
                          unsigned long system_code,
                          const WebString&) override;
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.cpp b/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.cpp
index 7c87076..bbc8ec9 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.cpp
+++ b/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.cpp
@@ -13,6 +13,7 @@
 
 }  // namespace
 
+// static
 WebEncryptedMediaInitDataType EncryptedMediaUtils::ConvertToInitDataType(
     const String& init_data_type) {
   if (init_data_type == "cenc")
@@ -26,6 +27,7 @@
   return WebEncryptedMediaInitDataType::kUnknown;
 }
 
+// static
 String EncryptedMediaUtils::ConvertFromInitDataType(
     WebEncryptedMediaInitDataType init_data_type) {
   switch (init_data_type) {
@@ -45,6 +47,7 @@
   return String();
 }
 
+// static
 WebEncryptedMediaSessionType EncryptedMediaUtils::ConvertToSessionType(
     const String& session_type) {
   if (session_type == kTemporary)
@@ -56,6 +59,7 @@
   return WebEncryptedMediaSessionType::kUnknown;
 }
 
+// static
 String EncryptedMediaUtils::ConvertFromSessionType(
     WebEncryptedMediaSessionType session_type) {
   switch (session_type) {
@@ -75,4 +79,28 @@
   return String();
 }
 
+// static
+String EncryptedMediaUtils::ConvertKeyStatusToString(
+    const WebEncryptedMediaKeyInformation::KeyStatus status) {
+  switch (status) {
+    case WebEncryptedMediaKeyInformation::KeyStatus::kUsable:
+      return "usable";
+    case WebEncryptedMediaKeyInformation::KeyStatus::kExpired:
+      return "expired";
+    case WebEncryptedMediaKeyInformation::KeyStatus::kReleased:
+      return "released";
+    case WebEncryptedMediaKeyInformation::KeyStatus::kOutputRestricted:
+      return "output-restricted";
+    case WebEncryptedMediaKeyInformation::KeyStatus::kOutputDownscaled:
+      return "output-downscaled";
+    case WebEncryptedMediaKeyInformation::KeyStatus::kStatusPending:
+      return "status-pending";
+    case WebEncryptedMediaKeyInformation::KeyStatus::kInternalError:
+      return "internal-error";
+  }
+
+  NOTREACHED();
+  return "internal-error";
+}
+
 }  // namespace blink
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.h b/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.h
index 558af1c..ca15662 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.h
+++ b/third_party/WebKit/Source/modules/encryptedmedia/EncryptedMediaUtils.h
@@ -7,6 +7,7 @@
 
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/text/WTFString.h"
+#include "public/platform/WebEncryptedMediaKeyInformation.h"
 #include "public/platform/WebEncryptedMediaTypes.h"
 
 namespace blink {
@@ -22,6 +23,9 @@
   static WebEncryptedMediaSessionType ConvertToSessionType(
       const String& session_type);
   static String ConvertFromSessionType(WebEncryptedMediaSessionType);
+
+  static String ConvertKeyStatusToString(
+      const WebEncryptedMediaKeyInformation::KeyStatus);
 };
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp b/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp
index fc37f31..e1201cdc 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp
+++ b/third_party/WebKit/Source/modules/encryptedmedia/HTMLMediaElementEncryptedMedia.cpp
@@ -87,6 +87,12 @@
     (*failure_callback_)(kInvalidStateError, "Unexpected completion.");
   }
 
+  void CompleteWithKeyStatus(
+      WebEncryptedMediaKeyInformation::KeyStatus key_status) override {
+    NOTREACHED();
+    (*failure_callback_)(kInvalidStateError, "Unexpected completion.");
+  }
+
   void CompleteWithError(WebContentDecryptionModuleException code,
                          unsigned long system_code,
                          const WebString& message) override {
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySession.cpp b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySession.cpp
index c9c7c9b2..096aa26d 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySession.cpp
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeySession.cpp
@@ -103,29 +103,6 @@
   return false;
 }
 
-static String ConvertKeyStatusToString(
-    const WebEncryptedMediaKeyInformation::KeyStatus status) {
-  switch (status) {
-    case WebEncryptedMediaKeyInformation::KeyStatus::kUsable:
-      return "usable";
-    case WebEncryptedMediaKeyInformation::KeyStatus::kExpired:
-      return "expired";
-    case WebEncryptedMediaKeyInformation::KeyStatus::kReleased:
-      return "released";
-    case WebEncryptedMediaKeyInformation::KeyStatus::kOutputRestricted:
-      return "output-restricted";
-    case WebEncryptedMediaKeyInformation::KeyStatus::kOutputDownscaled:
-      return "output-downscaled";
-    case WebEncryptedMediaKeyInformation::KeyStatus::kStatusPending:
-      return "status-pending";
-    case WebEncryptedMediaKeyInformation::KeyStatus::kInternalError:
-      return "internal-error";
-  }
-
-  NOTREACHED();
-  return "internal-error";
-}
-
 static ScriptPromise CreateRejectedPromiseNotCallable(
     ScriptState* script_state) {
   return ScriptPromise::RejectWithDOMException(
@@ -149,7 +126,7 @@
 }
 
 // A class holding a pending action.
-class MediaKeySession::PendingAction
+class MediaKeySession::PendingAction final
     : public GarbageCollectedFinalized<MediaKeySession::PendingAction> {
  public:
   enum Type { kGenerateRequest, kLoad, kUpdate, kClose, kRemove };
@@ -988,8 +965,8 @@
     const auto& key = keys[i];
     // 4.2.2 Insert an entry for pair's key ID into statuses with the
     //       value of pair's MediaKeyStatus value.
-    key_statuses_map_->AddEntry(key.Id(),
-                                ConvertKeyStatusToString(key.Status()));
+    key_statuses_map_->AddEntry(
+        key.Id(), EncryptedMediaUtils::ConvertKeyStatusToString(key.Status()));
   }
 
   // 5. Queue a task to fire a simple event named keystatuseschange
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp
index f2c5a649..991936f 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.cpp
@@ -36,12 +36,14 @@
 #include "modules/encryptedmedia/ContentDecryptionModuleResultPromise.h"
 #include "modules/encryptedmedia/EncryptedMediaUtils.h"
 #include "modules/encryptedmedia/MediaKeySession.h"
+#include "modules/encryptedmedia/MediaKeysPolicy.h"
 #include "platform/InstanceCounters.h"
 #include "platform/Timer.h"
 #include "platform/bindings/ScriptState.h"
 #include "platform/bindings/V8ThrowException.h"
 #include "platform/wtf/RefPtr.h"
 #include "public/platform/WebContentDecryptionModule.h"
+#include "public/platform/WebEncryptedMediaKeyInformation.h"
 
 #define MEDIA_KEYS_LOG_LEVEL 3
 
@@ -49,20 +51,41 @@
 
 // A class holding a pending action.
 class MediaKeys::PendingAction final
-    : public GarbageCollected<MediaKeys::PendingAction> {
+    : public GarbageCollectedFinalized<MediaKeys::PendingAction> {
  public:
+  enum class Type { kSetServerCertificate, kGetStatusForPolicy };
+
+  Type GetType() const { return type_; }
+
   const Persistent<ContentDecryptionModuleResult> Result() const {
     return result_;
   }
 
-  DOMArrayBuffer* Data() const { return data_; }
+  DOMArrayBuffer* Data() const {
+    DCHECK_EQ(Type::kSetServerCertificate, type_);
+    return data_;
+  }
+
+  const String& StringData() const {
+    DCHECK_EQ(Type::kGetStatusForPolicy, type_);
+    return string_data_;
+  }
 
   static PendingAction* CreatePendingSetServerCertificate(
       ContentDecryptionModuleResult* result,
       DOMArrayBuffer* server_certificate) {
     DCHECK(result);
     DCHECK(server_certificate);
-    return new PendingAction(result, server_certificate);
+    return new PendingAction(Type::kSetServerCertificate, result,
+                             server_certificate, String());
+  }
+
+  static PendingAction* CreatePendingGetStatusForPolicy(
+      ContentDecryptionModuleResult* result,
+      const String& min_hdcp_version) {
+    DCHECK(result);
+    return new PendingAction(Type::kGetStatusForPolicy, result, nullptr,
+                             min_hdcp_version);
   }
 
   DEFINE_INLINE_TRACE() {
@@ -71,11 +94,16 @@
   }
 
  private:
-  PendingAction(ContentDecryptionModuleResult* result, DOMArrayBuffer* data)
-      : result_(result), data_(data) {}
+  PendingAction(Type type,
+                ContentDecryptionModuleResult* result,
+                DOMArrayBuffer* data,
+                const String& string_data)
+      : type_(type), result_(result), data_(data), string_data_(string_data) {}
 
+  const Type type_;
   const Member<ContentDecryptionModuleResult> result_;
   const Member<DOMArrayBuffer> data_;
+  const String string_data_;
 };
 
 // This class wraps the promise resolver used when setting the certificate
@@ -90,7 +118,7 @@
       : ContentDecryptionModuleResultPromise(script_state),
         media_keys_(media_keys) {}
 
-  ~SetCertificateResultPromise() override {}
+  ~SetCertificateResultPromise() override = default;
 
   // ContentDecryptionModuleResult implementation.
   void Complete() override {
@@ -125,6 +153,40 @@
   }
 
  private:
+  // Keeping a reference to MediaKeys to prevent GC from collecting it while
+  // the promise is pending.
+  Member<MediaKeys> media_keys_;
+};
+
+// This class wraps the promise resolver used when getting the key status for
+// policy and is passed to Chromium to fullfill the promise.
+class GetStatusForPolicyResultPromise
+    : public ContentDecryptionModuleResultPromise {
+ public:
+  GetStatusForPolicyResultPromise(ScriptState* script_state,
+                                  MediaKeys* media_keys)
+      : ContentDecryptionModuleResultPromise(script_state),
+        media_keys_(media_keys) {}
+
+  ~GetStatusForPolicyResultPromise() override = default;
+
+  // ContentDecryptionModuleResult implementation.
+  void CompleteWithKeyStatus(
+      WebEncryptedMediaKeyInformation::KeyStatus key_status) override {
+    if (!IsValidToFulfillPromise())
+      return;
+
+    Resolve(EncryptedMediaUtils::ConvertKeyStatusToString(key_status));
+  }
+
+  DEFINE_INLINE_TRACE() {
+    visitor->Trace(media_keys_);
+    ContentDecryptionModuleResultPromise::Trace(visitor);
+  }
+
+ private:
+  // Keeping a reference to MediaKeys to prevent GC from collecting it while
+  // the promise is pending.
   Member<MediaKeys> media_keys_;
 };
 
@@ -220,7 +282,7 @@
       new SetCertificateResultPromise(script_state, this);
   ScriptPromise promise = result->Promise();
 
-  // 5. Run the following steps asynchronously (documented in timerFired()).
+  // 5. Run the following steps asynchronously. See SetServerCertificateTask().
   pending_actions_.push_back(PendingAction::CreatePendingSetServerCertificate(
       result, server_certificate_buffer));
   if (!timer_.IsActive())
@@ -230,6 +292,55 @@
   return promise;
 }
 
+void MediaKeys::SetServerCertificateTask(
+    DOMArrayBuffer* server_certificate,
+    ContentDecryptionModuleResult* result) {
+  DVLOG(MEDIA_KEYS_LOG_LEVEL) << __func__ << "(" << this << ")";
+
+  // 5.1 Let cdm be the cdm during the initialization of this object.
+  WebContentDecryptionModule* cdm = ContentDecryptionModule();
+
+  // 5.2 Use the cdm to process certificate.
+  cdm->SetServerCertificate(
+      static_cast<unsigned char*>(server_certificate->Data()),
+      server_certificate->ByteLength(), result->Result());
+
+  // 5.3 If any of the preceding steps failed, reject promise with a
+  //     new DOMException whose name is the appropriate error name.
+  // 5.4 Resolve promise.
+  // (These are handled by Chromium and the CDM.)
+}
+
+ScriptPromise MediaKeys::getStatusForPolicy(
+    ScriptState* script_state,
+    const MediaKeysPolicy& media_keys_policy) {
+  // TODO(xhwang): Pass MediaKeysPolicy classes all the way to Chromium when
+  // we have more than one policy to check.
+  String min_hdcp_version = media_keys_policy.minHdcpVersion();
+
+  // Let promise be a new promise.
+  GetStatusForPolicyResultPromise* result =
+      new GetStatusForPolicyResultPromise(script_state, this);
+  ScriptPromise promise = result->Promise();
+
+  // Run the following steps asynchronously. See GetStatusForPolicyTask().
+  pending_actions_.push_back(
+      PendingAction::CreatePendingGetStatusForPolicy(result, min_hdcp_version));
+  if (!timer_.IsActive())
+    timer_.StartOneShot(0, BLINK_FROM_HERE);
+
+  // Return promise.
+  return promise;
+}
+
+void MediaKeys::GetStatusForPolicyTask(const String& min_hdcp_version,
+                                       ContentDecryptionModuleResult* result) {
+  DVLOG(MEDIA_KEYS_LOG_LEVEL) << __func__ << ": " << min_hdcp_version;
+
+  WebContentDecryptionModule* cdm = ContentDecryptionModule();
+  cdm->GetStatusForPolicy(min_hdcp_version, result->Result());
+}
+
 bool MediaKeys::ReserveForMediaElement(HTMLMediaElement* media_element) {
   // If some other HtmlMediaElement already has a reference to us, fail.
   if (media_element_)
@@ -274,19 +385,16 @@
 
   while (!pending_actions.IsEmpty()) {
     PendingAction* action = pending_actions.TakeFirst();
-    DVLOG(MEDIA_KEYS_LOG_LEVEL) << __func__ << "(" << this << ") Certificate";
 
-    // 5.1 Let cdm be the cdm during the initialization of this object.
-    WebContentDecryptionModule* cdm = ContentDecryptionModule();
+    switch (action->GetType()) {
+      case PendingAction::Type::kSetServerCertificate:
+        SetServerCertificateTask(action->Data(), action->Result());
+        break;
 
-    // 5.2 Use the cdm to process certificate.
-    cdm->SetServerCertificate(
-        static_cast<unsigned char*>(action->Data()->Data()),
-        action->Data()->ByteLength(), action->Result()->Result());
-    // 5.3 If any of the preceding steps failed, reject promise with a
-    //     new DOMException whose name is the appropriate error name.
-    // 5.4 Resolve promise.
-    // (These are handled by Chromium and the CDM.)
+      case PendingAction::Type::kGetStatusForPolicy:
+        GetStatusForPolicyTask(action->StringData(), action->Result());
+        break;
+    }
   }
 }
 
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.h b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.h
index f785bd3..cd41833e 100644
--- a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.h
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeys.h
@@ -45,6 +45,7 @@
 class ExceptionState;
 class ExecutionContext;
 class HTMLMediaElement;
+class MediaKeysPolicy;
 class MediaKeySession;
 class ScriptState;
 class WebContentDecryptionModule;
@@ -72,6 +73,8 @@
   ScriptPromise setServerCertificate(ScriptState*,
                                      const DOMArrayPiece& server_certificate);
 
+  ScriptPromise getStatusForPolicy(ScriptState*, const MediaKeysPolicy&);
+
   // Indicates that the provided HTMLMediaElement wants to use this object.
   // Returns true if no other HTMLMediaElement currently references this
   // object, false otherwise. If true, will take a weak reference to
@@ -107,6 +110,11 @@
       std::unique_ptr<WebContentDecryptionModule>);
   class PendingAction;
 
+  void SetServerCertificateTask(DOMArrayBuffer* server_certificate,
+                                ContentDecryptionModuleResult*);
+  void GetStatusForPolicyTask(const String& min_hdcp_version,
+                              ContentDecryptionModuleResult*);
+
   bool SessionTypeSupported(WebEncryptedMediaSessionType);
   void TimerFired(TimerBase*);
 
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.cpp b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.cpp
new file mode 100644
index 0000000..b45cd3ab
--- /dev/null
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.cpp
@@ -0,0 +1,24 @@
+// Copyright 2017 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 "modules/encryptedmedia/MediaKeysGetStatusForPolicy.h"
+
+#include "bindings/core/v8/ScriptPromise.h"
+#include "modules/encryptedmedia/MediaKeys.h"
+#include "modules/encryptedmedia/MediaKeysPolicy.h"
+#include "platform/bindings/ScriptState.h"
+
+namespace blink {
+
+ScriptPromise MediaKeysGetStatusForPolicy::getStatusForPolicy(
+    ScriptState* script_state,
+    MediaKeys& media_keys,
+    MediaKeysPolicy* media_keys_policy) {
+  DVLOG(1) << __func__;
+  DCHECK(media_keys_policy);
+
+  return media_keys.getStatusForPolicy(script_state, *media_keys_policy);
+}
+
+}  // namespace blink
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.h b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.h
new file mode 100644
index 0000000..4994e09
--- /dev/null
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.h
@@ -0,0 +1,25 @@
+// Copyright 2017 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 MediaKeysGetStatusForPolicy_h
+#define MediaKeysGetStatusForPolicy_h
+
+#include "bindings/core/v8/ScriptPromise.h"
+
+namespace blink {
+
+class MediaKeys;
+class MediaKeysPolicy;
+class ScriptState;
+
+class MediaKeysGetStatusForPolicy {
+ public:
+  static ScriptPromise getStatusForPolicy(ScriptState*,
+                                          MediaKeys&,
+                                          MediaKeysPolicy*);
+};
+
+}  // namespace blink
+
+#endif  // MediaKeysGetStatusForPolicy_h
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.idl b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.idl
new file mode 100644
index 0000000..f2f9fed9
--- /dev/null
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysGetStatusForPolicy.idl
@@ -0,0 +1,11 @@
+// Copyright 2017 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.
+
+// https://github.com/WICG/media-capabilities/blob/master/eme-extension-policy-check.md
+
+[
+    RuntimeEnabled=EncryptedMediaHdcpPolicyCheck
+] partial interface MediaKeys {
+    [CallWith=ScriptState] Promise<MediaKeyStatus> getStatusForPolicy(MediaKeysPolicy policy);
+};
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.cpp b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.cpp
new file mode 100644
index 0000000..2437e14
--- /dev/null
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.cpp
@@ -0,0 +1,16 @@
+// Copyright 2017 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 "modules/encryptedmedia/MediaKeysPolicy.h"
+
+namespace blink {
+
+MediaKeysPolicy::MediaKeysPolicy(const MediaKeysPolicyInit& initializer) {
+  if (initializer.minHdcpVersion())
+    min_hdcp_version_ = initializer.minHdcpVersion();
+}
+
+DEFINE_TRACE(MediaKeysPolicy) {}
+
+}  // namespace blink
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.h b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.h
new file mode 100644
index 0000000..ab318a1
--- /dev/null
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.h
@@ -0,0 +1,36 @@
+// Copyright 2017 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 MediaKeysPolicy_h
+#define MediaKeysPolicy_h
+
+#include "modules/encryptedmedia/MediaKeysPolicyInit.h"
+#include "platform/bindings/ScriptWrappable.h"
+#include "platform/wtf/text/WTFString.h"
+
+namespace blink {
+
+class MediaKeysPolicy final : public GarbageCollectedFinalized<MediaKeysPolicy>,
+                              public ScriptWrappable {
+  DEFINE_WRAPPERTYPEINFO();
+
+ public:
+  static MediaKeysPolicy* Create(const MediaKeysPolicyInit& initializer) {
+    return new MediaKeysPolicy(initializer);
+  }
+
+  String minHdcpVersion() const { return min_hdcp_version_; }
+
+  DECLARE_VIRTUAL_TRACE();
+
+ private:
+  MediaKeysPolicy() = delete;
+  explicit MediaKeysPolicy(const MediaKeysPolicyInit& initializer);
+
+  String min_hdcp_version_;
+};
+
+}  // namespace blink
+
+#endif  // MediaKeysPolicy_h
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.idl b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.idl
new file mode 100644
index 0000000..845ff41
--- /dev/null
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicy.idl
@@ -0,0 +1,13 @@
+// Copyright 2017 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.
+
+// https://github.com/WICG/media-capabilities/blob/master/eme-extension-policy-check.md
+
+[
+    Exposed=Window,
+    RuntimeEnabled=EncryptedMediaHdcpPolicyCheck,
+    Constructor(MediaKeysPolicyInit init)
+] interface MediaKeysPolicy {
+    readonly attribute DOMString minHdcpVersion;
+};
diff --git a/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicyInit.idl b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicyInit.idl
new file mode 100644
index 0000000..d13abfa
--- /dev/null
+++ b/third_party/WebKit/Source/modules/encryptedmedia/MediaKeysPolicyInit.idl
@@ -0,0 +1,9 @@
+// Copyright 2017 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.
+
+// https://github.com/WICG/media-capabilities/blob/master/eme-extension-policy-check.md
+
+dictionary MediaKeysPolicyInit {
+    DOMString minHdcpVersion = "";
+};
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp b/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp
index 8dd1dfdc..5745aca5 100644
--- a/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp
+++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp
@@ -6,6 +6,8 @@
 
 #include <limits>
 #include <memory>
+
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/ClientRect.h"
@@ -42,7 +44,7 @@
 
 // The MediaTimelineWidths histogram suffix expected to be encountered in these
 // tests. Depends on the OS, since Android sizes its timeline differently.
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define TIMELINE_W "80_127"
 #else
 #define TIMELINE_W "128_255"
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.cpp b/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.cpp
index f7d96b7c..35bf7b9 100644
--- a/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.cpp
+++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsOrientationLockDelegate.cpp
@@ -4,6 +4,7 @@
 
 #include "modules/media_controls/MediaControlsOrientationLockDelegate.h"
 
+#include "build/build_config.h"
 #include "core/dom/TaskRunnerHelper.h"
 #include "core/events/Event.h"
 #include "core/frame/LocalDOMWindow.h"
@@ -22,12 +23,12 @@
 #include "public/platform/WebScreenInfo.h"
 #include "public/platform/modules/screen_orientation/WebLockOrientationCallback.h"
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #include "platform/mojo/MojoHelper.h"
 #include "public/platform/Platform.h"
 #include "services/device/public/interfaces/constants.mojom-blink.h"
 #include "services/service_manager/public/cpp/connector.h"
-#endif  // OS(ANDROID)
+#endif  // defined(OS_ANDROID)
 
 #undef atan2  // to use std::atan2 instead of wtf_atan2
 #undef fmod   // to use std::fmod instead of wtf_fmod
@@ -203,7 +204,7 @@
   }
 
 // Check whether the user locked screen orientation at the OS level.
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   DCHECK(!monitor_.is_bound());
   Platform::Current()->GetConnector()->BindInterface(
       device::mojom::blink::kServiceName, mojo::MakeRequest(&monitor_));
@@ -212,7 +213,7 @@
       WrapPersistent(this))));
 #else
   GotIsAutoRotateEnabledByUser(true);  // Assume always enabled on other OSes.
-#endif  // OS(ANDROID)
+#endif  // defined(OS_ANDROID)
 }
 
 void MediaControlsOrientationLockDelegate::GotIsAutoRotateEnabledByUser(
diff --git a/third_party/WebKit/Source/modules/modules_idl_files.gni b/third_party/WebKit/Source/modules/modules_idl_files.gni
index 6c587d7..a5c52308 100644
--- a/third_party/WebKit/Source/modules/modules_idl_files.gni
+++ b/third_party/WebKit/Source/modules/modules_idl_files.gni
@@ -90,6 +90,7 @@
                     "encoding/TextEncoder.idl",
                     "encryptedmedia/MediaEncryptedEvent.idl",
                     "encryptedmedia/MediaKeyMessageEvent.idl",
+                    "encryptedmedia/MediaKeysPolicy.idl",
                     "encryptedmedia/MediaKeySession.idl",
                     "encryptedmedia/MediaKeyStatusMap.idl",
                     "encryptedmedia/MediaKeySystemAccess.idl",
@@ -429,6 +430,7 @@
                     "encoding/TextDecodeOptions.idl",
                     "encoding/TextDecoderOptions.idl",
                     "encryptedmedia/MediaEncryptedEventInit.idl",
+                    "encryptedmedia/MediaKeysPolicyInit.idl",
                     "encryptedmedia/MediaKeyMessageEventInit.idl",
                     "encryptedmedia/MediaKeySystemConfiguration.idl",
                     "encryptedmedia/MediaKeySystemMediaCapability.idl",
@@ -607,6 +609,7 @@
           "device_orientation/WindowDeviceOrientation.idl",
           "donottrack/NavigatorDoNotTrack.idl",
           "encryptedmedia/HTMLMediaElementEncryptedMedia.idl",
+          "encryptedmedia/MediaKeysGetStatusForPolicy.idl",
           "encryptedmedia/NavigatorRequestMediaKeySystemAccess.idl",
           "fetch/WindowFetch.idl",
           "fetch/WorkerFetch.idl",
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
index 07bb7fc..d8c6de50 100644
--- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
+++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -26,10 +26,12 @@
 #include "modules/webgl/WebGLRenderingContextBase.h"
 
 #include <memory>
+
 #include "bindings/core/v8/ExceptionMessages.h"
 #include "bindings/core/v8/ExceptionState.h"
 #include "bindings/modules/v8/HTMLCanvasElementOrOffscreenCanvas.h"
 #include "bindings/modules/v8/WebGLAny.h"
+#include "build/build_config.h"
 #include "core/dom/ArrayBufferViewHelpers.h"
 #include "core/dom/DOMArrayBuffer.h"
 #include "core/dom/DOMTypedArray.h"
@@ -114,11 +116,11 @@
 const int kMaxGLErrorsAllowedToConsole = 256;
 const unsigned kMaxGLActiveContextsOnWorker = 4;
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 const unsigned kMaxGLActiveContexts = 8;
-#else   // OS(ANDROID)
+#else   // defined(OS_ANDROID)
 const unsigned kMaxGLActiveContexts = 16;
-#endif  // OS(ANDROID)
+#endif  // defined(OS_ANDROID)
 
 unsigned CurrentMaxGLContexts() {
   return IsMainThread() ? kMaxGLActiveContexts : kMaxGLActiveContextsOnWorker;
@@ -4867,7 +4869,7 @@
 
 bool WebGLRenderingContextBase::CanUseTexImageByGPU(GLenum format,
                                                     GLenum type) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // RGB5_A1 is not color-renderable on NVIDIA Mac, see crbug.com/676209.
   // Though, glCopyTextureCHROMIUM can handle RGB5_A1 internalformat by doing a
   // fallback path, but it doesn't know the type info. So, we still cannot do
@@ -4884,7 +4886,7 @@
   if (format == GL_RED || format == GL_RED_INTEGER)
     return false;
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   // TODO(kbr): bugs were seen on Android devices with NVIDIA GPUs
   // when copying hardware-accelerated video textures to
   // floating-point textures. Investigate the root cause of this and
diff --git a/third_party/WebKit/Source/platform/ContentDecryptionModuleResult.h b/third_party/WebKit/Source/platform/ContentDecryptionModuleResult.h
index 0a5e4a3..cad50ce 100644
--- a/third_party/WebKit/Source/platform/ContentDecryptionModuleResult.h
+++ b/third_party/WebKit/Source/platform/ContentDecryptionModuleResult.h
@@ -8,6 +8,7 @@
 #include "platform/heap/Handle.h"
 #include "public/platform/WebContentDecryptionModuleException.h"
 #include "public/platform/WebContentDecryptionModuleResult.h"
+#include "public/platform/WebEncryptedMediaKeyInformation.h"
 
 namespace blink {
 
@@ -25,6 +26,8 @@
       WebContentDecryptionModule*) = 0;
   virtual void CompleteWithSession(
       WebContentDecryptionModuleResult::SessionStatus) = 0;
+  virtual void CompleteWithKeyStatus(
+      WebEncryptedMediaKeyInformation::KeyStatus) = 0;
   virtual void CompleteWithError(WebContentDecryptionModuleException,
                                  unsigned long system_code,
                                  const WebString&) = 0;
diff --git a/third_party/WebKit/Source/platform/KeyboardCodes.h b/third_party/WebKit/Source/platform/KeyboardCodes.h
index e2e5f37c..2ddf6b00 100644
--- a/third_party/WebKit/Source/platform/KeyboardCodes.h
+++ b/third_party/WebKit/Source/platform/KeyboardCodes.h
@@ -31,9 +31,9 @@
 #ifndef KeyboardCodes_h
 #define KeyboardCodes_h
 
-#include "platform/wtf/build_config.h"
+#include "build/build_config.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
 #endif
 
diff --git a/third_party/WebKit/Source/platform/MemoryCoordinator.cpp b/third_party/WebKit/Source/platform/MemoryCoordinator.cpp
index 02c0a31d..4afa2b0f 100644
--- a/third_party/WebKit/Source/platform/MemoryCoordinator.cpp
+++ b/third_party/WebKit/Source/platform/MemoryCoordinator.cpp
@@ -5,6 +5,7 @@
 #include "platform/MemoryCoordinator.h"
 
 #include "base/sys_info.h"
+#include "build/build_config.h"
 #include "platform/WebTaskRunner.h"
 #include "platform/fonts/FontGlobalContext.h"
 #include "platform/graphics/ImageDecodingStore.h"
@@ -12,7 +13,7 @@
 #include "platform/wtf/allocator/Partitions.h"
 #include "public/platform/WebThread.h"
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #include "base/android/sys_utils.h"
 #endif
 
@@ -40,7 +41,7 @@
 
 // static
 bool MemoryCoordinator::IsCurrentlyLowMemory() {
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   return base::android::SysUtils::IsCurrentlyLowMemory();
 #else
   return false;
diff --git a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5
index fa79b48..f329ba1 100644
--- a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5
+++ b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5
@@ -388,6 +388,10 @@
       status: "stable",
     },
     {
+      name: "EncryptedMediaHdcpPolicyCheck",
+      status: "test",
+    },
+    {
       name: "ExecCommandInJavaScript",
       status: "test",
     },
@@ -418,7 +422,7 @@
       name: "FeaturePolicyExperimentalFeatures",
     },
     {
-      name:"FetchRequestCache",
+      name: "FetchRequestCache",
       status: "experimental",
     },
     {
@@ -881,6 +885,10 @@
       status: "experimental",
     },
     {
+      name: "ResourceLoadScheduler",
+      status: "experimental",
+    },
+    {
       name: "RestrictCanRequestURLCharacterSet",
       status: "stable",
     },
diff --git a/third_party/WebKit/Source/platform/SecureTextInput.cpp b/third_party/WebKit/Source/platform/SecureTextInput.cpp
index 3a28130..ed64c686 100644
--- a/third_party/WebKit/Source/platform/SecureTextInput.cpp
+++ b/third_party/WebKit/Source/platform/SecureTextInput.cpp
@@ -25,7 +25,9 @@
 
 #include "platform/SecureTextInput.h"
 
-#if OS(MACOSX)
+#include "build/build_config.h"
+
+#if defined(OS_MACOSX)
 #import <Carbon/Carbon.h>
 
 namespace blink {
@@ -44,4 +46,4 @@
 
 }  // namespace blink
 
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
diff --git a/third_party/WebKit/Source/platform/SecureTextInput.h b/third_party/WebKit/Source/platform/SecureTextInput.h
index 0aa85d6..80f0484 100644
--- a/third_party/WebKit/Source/platform/SecureTextInput.h
+++ b/third_party/WebKit/Source/platform/SecureTextInput.h
@@ -31,12 +31,13 @@
 #ifndef SecureTextInput_h
 #define SecureTextInput_h
 
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/wtf/build_config.h"
 
 namespace blink {
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 // Once enableSecureTextInput is called, secure text input mode is set until
 // disableSecureTextInput has been called.
 PLATFORM_EXPORT void EnableSecureTextInput();
diff --git a/third_party/WebKit/Source/platform/WebThread.cpp b/third_party/WebKit/Source/platform/WebThread.cpp
index eea3015..67e2529 100644
--- a/third_party/WebKit/Source/platform/WebThread.cpp
+++ b/third_party/WebKit/Source/platform/WebThread.cpp
@@ -4,21 +4,22 @@
 
 #include "public/platform/WebThread.h"
 
+#include "build/build_config.h"
 #include "platform/WebTaskRunner.h"
 #include "platform/wtf/Assertions.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
-#elif OS(POSIX)
+#elif defined(OS_POSIX)
 #include <unistd.h>
 #endif
 
 namespace blink {
 
-#if OS(WIN)
+#if defined(OS_WIN)
 static_assert(sizeof(blink::PlatformThreadId) >= sizeof(DWORD),
               "size of platform thread id is too small");
-#elif OS(POSIX)
+#elif defined(OS_POSIX)
 static_assert(sizeof(blink::PlatformThreadId) >= sizeof(pid_t),
               "size of platform thread id is too small");
 #else
diff --git a/third_party/WebKit/Source/platform/audio/Biquad.cpp b/third_party/WebKit/Source/platform/audio/Biquad.cpp
index 8505bda..19b10f6 100644
--- a/third_party/WebKit/Source/platform/audio/Biquad.cpp
+++ b/third_party/WebKit/Source/platform/audio/Biquad.cpp
@@ -28,6 +28,7 @@
 
 #include "platform/audio/Biquad.h"
 
+#include "build/build_config.h"
 #include "platform/audio/AudioUtilities.h"
 #include "platform/audio/DenormalDisabler.h"
 #include "platform/wtf/MathExtras.h"
@@ -35,18 +36,18 @@
 #include <algorithm>
 #include <complex>
 #include <stdio.h>
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include <Accelerate/Accelerate.h>
 #endif
 
 namespace blink {
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 const int kBufferSize = 1024;
 #endif
 
 Biquad::Biquad() : has_sample_accurate_values_(false) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // Allocate two samples more for filter history
   input_buffer_.Allocate(kBufferSize + 2);
   output_buffer_.Allocate(kBufferSize + 2);
@@ -118,7 +119,7 @@
     // path.  The structure of the state variable in these cases aren't well
     // documented so it's not clear how to update them anyway.
   } else {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     double* input_p = input_buffer_.Data();
     double* output_p = output_buffer_.Data();
 
@@ -183,7 +184,7 @@
   }
 }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 
 // Here we have optimized version using Accelerate.framework
 
@@ -241,10 +242,10 @@
   dest_p[1] = dest_p[frames_to_process - 1 + 2];
 }
 
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
 
 void Biquad::Reset() {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // Two extra samples for filter history
   double* input_p = input_buffer_.Data();
   input_p[0] = 0;
diff --git a/third_party/WebKit/Source/platform/audio/Biquad.h b/third_party/WebKit/Source/platform/audio/Biquad.h
index 9d51ba3..c9253d2d 100644
--- a/third_party/WebKit/Source/platform/audio/Biquad.h
+++ b/third_party/WebKit/Source/platform/audio/Biquad.h
@@ -30,7 +30,10 @@
 #define Biquad_h
 
 #include <sys/types.h>
+
 #include <complex>
+
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/audio/AudioArray.h"
 #include "platform/wtf/Allocator.h"
@@ -107,7 +110,7 @@
   AudioDoubleArray a1_;
   AudioDoubleArray a2_;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   void ProcessFast(const float* source_p,
                    float* dest_p,
                    size_t frames_to_process);
diff --git a/third_party/WebKit/Source/platform/audio/FFTFrame.h b/third_party/WebKit/Source/platform/audio/FFTFrame.h
index 593f64c..814ea01e 100644
--- a/third_party/WebKit/Source/platform/audio/FFTFrame.h
+++ b/third_party/WebKit/Source/platform/audio/FFTFrame.h
@@ -30,13 +30,15 @@
 #define FFTFrame_h
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/audio/AudioArray.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Forward.h"
 #include "platform/wtf/Threading.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include <Accelerate/Accelerate.h>
 #elif USE(WEBAUDIO_OPENMAX_DL_FFT)
 #include <dl/sp/api/omxSP.h>
@@ -99,7 +101,7 @@
   AudioFloatArray real_data_;
   AudioFloatArray imag_data_;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   DSPSplitComplex& DspSplitComplex() { return frame_; }
   DSPSplitComplex DspSplitComplex() const { return frame_; }
   static FFTSetup FftSetupForSize(unsigned fft_size);
diff --git a/third_party/WebKit/Source/platform/audio/FFTFrameStub.cpp b/third_party/WebKit/Source/platform/audio/FFTFrameStub.cpp
index 9c874cb..f08937a 100644
--- a/third_party/WebKit/Source/platform/audio/FFTFrameStub.cpp
+++ b/third_party/WebKit/Source/platform/audio/FFTFrameStub.cpp
@@ -25,9 +25,11 @@
 
 // FFTFrame stub implementation to avoid link errors during bringup
 
+#include "build/build_config.h"
 #include "platform/wtf/build_config.h"
 
-#if !OS(MACOSX) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
+#if !defined(OS_MACOSX) && !USE(WEBAUDIO_FFMPEG) && \
+    !USE(WEBAUDIO_OPENMAX_DL_FFT)
 
 #include "platform/audio/FFTFrame.h"
 
@@ -69,4 +71,5 @@
 
 }  // namespace blink
 
-#endif  // !OS(MACOSX) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
+#endif  // !defined(OS_MACOSX) && !USE(WEBAUDIO_FFMPEG) &&
+        // !USE(WEBAUDIO_OPENMAX_DL_FFT)
diff --git a/third_party/WebKit/Source/platform/audio/PushPullFIFO.cpp b/third_party/WebKit/Source/platform/audio/PushPullFIFO.cpp
index 5e87c4af..e2d91ab 100644
--- a/third_party/WebKit/Source/platform/audio/PushPullFIFO.cpp
+++ b/third_party/WebKit/Source/platform/audio/PushPullFIFO.cpp
@@ -5,6 +5,7 @@
 #include "platform/audio/PushPullFIFO.h"
 
 #include <memory>
+#include "build/build_config.h"
 #include "platform/Histogram.h"
 #include "platform/audio/AudioUtilities.h"
 #include "platform/wtf/PtrUtil.h"
@@ -109,7 +110,7 @@
 size_t PushPullFIFO::Pull(AudioBus* output_bus, size_t frames_requested) {
   MutexLocker locker(lock_);
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   if (!output_bus) {
     // Log when outputBus or FIFO object is invalid. (crbug.com/692423)
     LOG(WARNING) << "[WebAudio/PushPullFIFO::pull <" << static_cast<void*>(this)
diff --git a/third_party/WebKit/Source/platform/audio/Reverb.cpp b/third_party/WebKit/Source/platform/audio/Reverb.cpp
index 62cac9d..70a2843 100644
--- a/third_party/WebKit/Source/platform/audio/Reverb.cpp
+++ b/third_party/WebKit/Source/platform/audio/Reverb.cpp
@@ -29,13 +29,16 @@
 #include "platform/audio/Reverb.h"
 
 #include <math.h>
+
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/audio/AudioBus.h"
 #include "platform/audio/VectorMath.h"
 #include "platform/wtf/MathExtras.h"
 #include "platform/wtf/PtrUtil.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 using namespace std;
 #endif
 
diff --git a/third_party/WebKit/Source/platform/audio/VectorMath.cpp b/third_party/WebKit/Source/platform/audio/VectorMath.cpp
index 75c7169..db214b8 100644
--- a/third_party/WebKit/Source/platform/audio/VectorMath.cpp
+++ b/third_party/WebKit/Source/platform/audio/VectorMath.cpp
@@ -31,7 +31,7 @@
 #include "platform/wtf/CPU.h"
 #include "platform/wtf/MathExtras.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include <Accelerate/Accelerate.h>
 #endif
 
@@ -54,7 +54,7 @@
 
 namespace VectorMath {
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 // On the Mac we use the highly optimized versions in Accelerate.framework
 // In 32-bit mode (__ppc__ or __i386__) <Accelerate/Accelerate.h> includes
 // <vecLib/vDSP_translate.h> which defines macros of the same name as
@@ -893,7 +893,7 @@
   }
 }
 
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
 
 }  // namespace VectorMath
 
diff --git a/third_party/WebKit/Source/platform/audio/android/FFTFrameOpenMAXDLAndroid.cpp b/third_party/WebKit/Source/platform/audio/android/FFTFrameOpenMAXDLAndroid.cpp
index e71f12af..b6e0981b 100644
--- a/third_party/WebKit/Source/platform/audio/android/FFTFrameOpenMAXDLAndroid.cpp
+++ b/third_party/WebKit/Source/platform/audio/android/FFTFrameOpenMAXDLAndroid.cpp
@@ -22,9 +22,10 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include "build/build_config.h"
 #include "platform/wtf/build_config.h"
 
-#if OS(ANDROID) && USE(WEBAUDIO_OPENMAX_DL_FFT)
+#if defined(OS_ANDROID) && USE(WEBAUDIO_OPENMAX_DL_FFT)
 
 #include "platform/audio/FFTFrame.h"
 
@@ -157,4 +158,4 @@
 
 }  // namespace blink
 
-#endif  // #if OS(ANDROID) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
+#endif  // #if defined(OS_ANDROID) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
diff --git a/third_party/WebKit/Source/platform/audio/mac/FFTFrameMac.cpp b/third_party/WebKit/Source/platform/audio/mac/FFTFrameMac.cpp
index 0bc711d..180924d 100644
--- a/third_party/WebKit/Source/platform/audio/mac/FFTFrameMac.cpp
+++ b/third_party/WebKit/Source/platform/audio/mac/FFTFrameMac.cpp
@@ -28,9 +28,10 @@
 
 // Mac OS X - specific FFTFrame implementation
 
+#include "build/build_config.h"
 #include "platform/wtf/build_config.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 
 #include "platform/audio/FFTFrame.h"
 
@@ -140,4 +141,4 @@
 
 }  // namespace blink
 
-#endif  // #if OS(MACOSX)
+#endif  // #if defined(OS_MACOSX)
diff --git a/third_party/WebKit/Source/platform/clipboard/ClipboardUtilities.h b/third_party/WebKit/Source/platform/clipboard/ClipboardUtilities.h
index 835051c..39614f8d 100644
--- a/third_party/WebKit/Source/platform/clipboard/ClipboardUtilities.h
+++ b/third_party/WebKit/Source/platform/clipboard/ClipboardUtilities.h
@@ -31,13 +31,14 @@
 #ifndef ClipboardUtilities_h
 #define ClipboardUtilities_h
 
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/wtf/Forward.h"
 #include "platform/wtf/build_config.h"
 
 namespace blink {
 
-#if OS(WIN)
+#if defined(OS_WIN)
 PLATFORM_EXPORT void ReplaceNewlinesWithWindowsStyleNewlines(String&);
 #endif
 PLATFORM_EXPORT void ReplaceNBSPWithSpace(String&);
diff --git a/third_party/WebKit/Source/platform/exported/FilePathConversion.cpp b/third_party/WebKit/Source/platform/exported/FilePathConversion.cpp
index d8fcaa5..7c4d7dd 100644
--- a/third_party/WebKit/Source/platform/exported/FilePathConversion.cpp
+++ b/third_party/WebKit/Source/platform/exported/FilePathConversion.cpp
@@ -5,6 +5,7 @@
 #include "public/platform/FilePathConversion.h"
 
 #include "base/files/file_path.h"
+#include "build/build_config.h"
 #include "platform/wtf/text/StringUTF8Adaptor.h"
 #include "platform/wtf/text/WTFString.h"
 #include "public/platform/WebString.h"
@@ -21,7 +22,7 @@
         base::StringPiece16(str.Characters16(), str.length()));
   }
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
   StringUTF8Adaptor utf8(str);
   return base::FilePath::FromUTF8Unsafe(utf8.AsStringPiece());
 #else
@@ -35,7 +36,7 @@
   if (path.empty())
     return WebString();
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
   return WebString::FromUTF8(path.value());
 #else
   return WebString::FromUTF16(path.AsUTF16Unsafe());
diff --git a/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp b/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp
index 0e1dfaa..6867b8a 100644
--- a/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp
+++ b/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp
@@ -25,6 +25,12 @@
   Reset();
 }
 
+void WebContentDecryptionModuleResult::CompleteWithKeyStatus(
+    WebEncryptedMediaKeyInformation::KeyStatus key_status) {
+  impl_->CompleteWithKeyStatus(key_status);
+  Reset();
+}
+
 void WebContentDecryptionModuleResult::CompleteWithError(
     WebContentDecryptionModuleException exception,
     unsigned long system_code,
diff --git a/third_party/WebKit/Source/platform/fonts/AlternateFontFamily.h b/third_party/WebKit/Source/platform/fonts/AlternateFontFamily.h
index c5b17a9..6b7f097 100644
--- a/third_party/WebKit/Source/platform/fonts/AlternateFontFamily.h
+++ b/third_party/WebKit/Source/platform/fonts/AlternateFontFamily.h
@@ -31,6 +31,7 @@
 #ifndef AlternateFontFamily_h
 #define AlternateFontFamily_h
 
+#include "build/build_config.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/wtf/text/AtomicString.h"
 
@@ -41,7 +42,7 @@
 // path map certain common bitmap fonts to their truetype equivalent up front.
 inline const AtomicString& AdjustFamilyNameToAvoidUnsupportedFonts(
     const AtomicString& family_name) {
-#if OS(WIN)
+#if defined(OS_WIN)
   // On Windows, 'Courier New' (truetype font) is always present and
   // 'Courier' is a bitmap font. On Mac on the other hand 'Courier' is
   // a truetype font. Thus pages asking for Courier are better of
@@ -79,7 +80,7 @@
   DEFINE_STATIC_LOCAL(AtomicString, courier_new, ("Courier New"));
   if (DeprecatedEqualIgnoringCase(family_name, courier))
     return courier_new;
-#if !OS(WIN)
+#if !defined(OS_WIN)
   // On Windows, Courier New (truetype font) is always present and
   // Courier is a bitmap font. So, we don't want to map Courier New to
   // Courier.
diff --git a/third_party/WebKit/Source/platform/fonts/FontCache.cpp b/third_party/WebKit/Source/platform/fonts/FontCache.cpp
index e5f4dc9..2e0a775 100644
--- a/third_party/WebKit/Source/platform/fonts/FontCache.cpp
+++ b/third_party/WebKit/Source/platform/fonts/FontCache.cpp
@@ -30,7 +30,9 @@
 #include "platform/fonts/FontCache.h"
 
 #include <memory>
+
 #include "base/trace_event/process_memory_dump.h"
+#include "build/build_config.h"
 #include "platform/FontFamilyNames.h"
 #include "platform/Histogram.h"
 #include "platform/RuntimeEnabledFeatures.h"
@@ -64,28 +66,28 @@
 
 namespace blink {
 
-#if !OS(WIN) && !OS(LINUX)
+#if !defined(OS_WIN) && !defined(OS_LINUX)
 FontCache::FontCache() : purge_prevent_count_(0), font_manager_(nullptr) {}
-#endif  // !OS(WIN) && !OS(LINUX)
+#endif  // !defined(OS_WIN) && !defined(OS_LINUX)
 
 SkFontMgr* FontCache::static_font_manager_ = nullptr;
 
-#if OS(WIN)
+#if defined(OS_WIN)
 bool FontCache::antialiased_text_enabled_ = false;
 bool FontCache::lcd_text_enabled_ = false;
 float FontCache::device_scale_factor_ = 1.0;
 bool FontCache::use_skia_font_fallback_ = false;
-#endif  // OS(WIN)
+#endif  // defined(OS_WIN)
 
 FontCache* FontCache::GetFontCache() {
   return &FontGlobalContext::GetFontCache();
 }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 FontPlatformData* FontCache::SystemFontPlatformData(
     const FontDescription& font_description) {
   const AtomicString& family = FontCache::SystemFontFamily();
-#if OS(LINUX)
+#if defined(OS_LINUX)
   if (family.IsEmpty() || family == FontFamilyNames::system_ui)
     return nullptr;
 #else
@@ -105,7 +107,7 @@
     PlatformInit();
   }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   if (creation_params.CreationType() == kCreateFontByFamily &&
       creation_params.Family() == FontFamilyNames::system_ui) {
     return SystemFontPlatformData(font_description);
@@ -183,7 +185,7 @@
     const FontDescription& font_description,
     const FontFaceCreationParams& creation_params,
     float font_size) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   return CreateFontPlatformData(font_description, creation_params, font_size);
 #else
   return WTF::MakeUnique<FontPlatformData>(font_platform_data, font_size);
diff --git a/third_party/WebKit/Source/platform/fonts/FontCache.h b/third_party/WebKit/Source/platform/fonts/FontCache.h
index 4f583fda..6c98add 100644
--- a/third_party/WebKit/Source/platform/fonts/FontCache.h
+++ b/third_party/WebKit/Source/platform/fonts/FontCache.h
@@ -31,7 +31,10 @@
 #define FontCache_h
 
 #include <limits.h>
+
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/fonts/FallbackListCompositeKey.h"
 #include "platform/fonts/FontCacheClient.h"
@@ -157,16 +160,16 @@
   SkFontMgr* FontManager() { return font_manager_.get(); }
   static void SetFontManager(sk_sp<SkFontMgr>);
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   static const AtomicString& SystemFontFamily();
 #else
   static const AtomicString& LegacySystemFontFamily();
 #endif
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
   static void SetSystemFontFamily(const AtomicString&);
 #endif
 
-#if OS(WIN)
+#if defined(OS_WIN)
   static bool AntialiasedTextEnabled() { return antialiased_text_enabled_; }
   static bool LcdTextEnabled() { return lcd_text_enabled_; }
   static float DeviceScaleFactor() { return device_scale_factor_; }
@@ -208,7 +211,7 @@
 
   static void AcceptLanguagesChanged(const String&);
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   static AtomicString GetGenericFamilyNameForScript(
       const AtomicString& family_name,
       const FontDescription&);
@@ -258,7 +261,7 @@
       const FontDescription&,
       const FontFaceCreationParams&,
       AlternateFontName = AlternateFontName::kAllowAlternate);
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   FontPlatformData* SystemFontPlatformData(const FontDescription&);
 #endif
 
@@ -279,7 +282,7 @@
                                    const FontFaceCreationParams&,
                                    CString& name);
 
-#if OS(ANDROID) || OS(LINUX)
+#if defined(OS_ANDROID) || defined(OS_LINUX)
   static AtomicString GetFamilyNameForCharacter(SkFontMgr*,
                                                 UChar32,
                                                 const FontDescription&,
@@ -297,7 +300,7 @@
   // A leaky owning bare pointer.
   static SkFontMgr* static_font_manager_;
 
-#if OS(WIN)
+#if defined(OS_WIN)
   static bool antialiased_text_enabled_;
   static bool lcd_text_enabled_;
   static float device_scale_factor_;
diff --git a/third_party/WebKit/Source/platform/fonts/FontCacheTest.cpp b/third_party/WebKit/Source/platform/fonts/FontCacheTest.cpp
index c597708f..e1d3529 100644
--- a/third_party/WebKit/Source/platform/fonts/FontCacheTest.cpp
+++ b/third_party/WebKit/Source/platform/fonts/FontCacheTest.cpp
@@ -4,6 +4,7 @@
 
 #include "platform/fonts/FontCache.h"
 
+#include "build/build_config.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/fonts/SimpleFontData.h"
 #include "platform/testing/TestingPlatformSupport.h"
@@ -47,7 +48,7 @@
             FontCache::FirstAvailableOrFirst(", not exist, not exist"));
 }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 TEST(FontCache, systemFont) {
   FontCache::SystemFontFamily();
   // Test the function does not crash. Return value varies by system and config.
diff --git a/third_party/WebKit/Source/platform/fonts/FontCustomPlatformData.cpp b/third_party/WebKit/Source/platform/fonts/FontCustomPlatformData.cpp
index af4daa3..d361307 100644
--- a/third_party/WebKit/Source/platform/fonts/FontCustomPlatformData.cpp
+++ b/third_party/WebKit/Source/platform/fonts/FontCustomPlatformData.cpp
@@ -32,19 +32,20 @@
 
 #include "platform/fonts/FontCustomPlatformData.h"
 
+#include "build/build_config.h"
 #include "platform/LayoutTestSupport.h"
 #include "platform/SharedBuffer.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/fonts/FontPlatformData.h"
 #include "platform/fonts/WebFontDecoder.h"
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include "platform/fonts/mac/CoreTextVariationsSupport.h"
 #endif
 #include "platform/fonts/opentype/FontSettings.h"
 #include "platform/fonts/opentype/VariableFontCheck.h"
 #include "third_party/skia/include/core/SkStream.h"
 #include "third_party/skia/include/core/SkTypeface.h"
-#if OS(WIN) || OS(MACOSX)
+#if defined(OS_WIN) || defined(OS_MACOSX)
 #include "third_party/skia/include/ports/SkFontMgr_empty.h"
 #endif
 #include "platform/wtf/PtrUtil.h"
@@ -76,9 +77,9 @@
   // handled by Skia with priority given to the last occuring
   // assignment.
   if (VariableFontCheck::IsVariableFont(base_typeface_.get())) {
-#if OS(WIN)
+#if defined(OS_WIN)
     sk_sp<SkFontMgr> fm(SkFontMgr_New_Custom_Empty());
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
     sk_sp<SkFontMgr> fm;
     if (CoreTextVersionSupportsVariations())
       fm = SkFontMgr::RefDefault();
diff --git a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp
index 8fa38e51..9561c5d 100644
--- a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp
+++ b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp
@@ -30,11 +30,12 @@
 
 #include "platform/fonts/FontDataCache.h"
 
+#include "build/build_config.h"
 #include "platform/fonts/SimpleFontData.h"
 
 namespace blink {
 
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
 const unsigned kCMaxInactiveFontData = 250;
 const unsigned kCTargetInactiveFontData = 200;
 #else
diff --git a/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h b/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h
index eae7f6b..7eeea3bc 100644
--- a/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h
+++ b/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h
@@ -31,6 +31,7 @@
 #ifndef FontFaceCreationParams_h
 #define FontFaceCreationParams_h
 
+#include "build/build_config.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Assertions.h"
 #include "platform/wtf/StringHasher.h"
@@ -61,7 +62,7 @@
         filename_(CString()),
         fontconfig_interface_id_(0),
         ttc_index_(0) {
-#if OS(WIN)
+#if defined(OS_WIN)
     // Leading "@" in the font name enables Windows vertical flow flag for the
     // font.  Because we do vertical flow by ourselves, we don't want to use the
     // Windows feature.  IE disregards "@" regardless of the orientation, so we
diff --git a/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp b/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp
index 012726e3..efd4e8fa 100644
--- a/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp
+++ b/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp
@@ -21,6 +21,7 @@
 #include "platform/fonts/FontPlatformData.h"
 
 #include "SkTypeface.h"
+#include "build/build_config.h"
 #include "hb-ot.h"
 #include "hb.h"
 #include "platform/fonts/FontCache.h"
@@ -31,7 +32,7 @@
 #include "platform/wtf/text/StringHash.h"
 #include "platform/wtf/text/WTFString.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include "third_party/skia/include/ports/SkTypeface_mac.h"
 #endif
 
@@ -44,7 +45,7 @@
       synthetic_italic_(false),
       orientation_(FontOrientation::kHorizontal),
       is_hash_table_deleted_value_(true)
-#if OS(WIN)
+#if defined(OS_WIN)
       ,
       paint_text_flags_(0)
 #endif
@@ -58,7 +59,7 @@
       synthetic_italic_(false),
       orientation_(FontOrientation::kHorizontal),
       is_hash_table_deleted_value_(false)
-#if OS(WIN)
+#if defined(OS_WIN)
       ,
       paint_text_flags_(0)
 #endif
@@ -75,7 +76,7 @@
       synthetic_italic_(synthetic_italic),
       orientation_(orientation),
       is_hash_table_deleted_value_(false)
-#if OS(WIN)
+#if defined(OS_WIN)
       ,
       paint_text_flags_(0)
 #endif
@@ -84,19 +85,19 @@
 
 FontPlatformData::FontPlatformData(const FontPlatformData& source)
     : typeface_(source.typeface_),
-#if !OS(WIN)
+#if !defined(OS_WIN)
       family_(source.family_),
 #endif
       text_size_(source.text_size_),
       synthetic_bold_(source.synthetic_bold_),
       synthetic_italic_(source.synthetic_italic_),
       orientation_(source.orientation_),
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
       style_(source.style_),
 #endif
       harf_buzz_face_(nullptr),
       is_hash_table_deleted_value_(false)
-#if OS(WIN)
+#if defined(OS_WIN)
       ,
       paint_text_flags_(source.paint_text_flags_)
 #endif
@@ -105,26 +106,26 @@
 
 FontPlatformData::FontPlatformData(const FontPlatformData& src, float text_size)
     : typeface_(src.typeface_),
-#if !OS(WIN)
+#if !defined(OS_WIN)
       family_(src.family_),
 #endif
       text_size_(text_size),
       synthetic_bold_(src.synthetic_bold_),
       synthetic_italic_(src.synthetic_italic_),
       orientation_(src.orientation_),
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
       style_(FontRenderStyle::QuerySystem(family_,
                                           text_size_,
                                           typeface_->fontStyle())),
 #endif
       harf_buzz_face_(nullptr),
       is_hash_table_deleted_value_(false)
-#if OS(WIN)
+#if defined(OS_WIN)
       ,
       paint_text_flags_(src.paint_text_flags_)
 #endif
 {
-#if OS(WIN)
+#if defined(OS_WIN)
   QuerySystemForRenderStyle();
 #endif
 }
@@ -136,32 +137,32 @@
                                    bool synthetic_italic,
                                    FontOrientation orientation)
     : typeface_(std::move(tf)),
-#if !OS(WIN)
+#if !defined(OS_WIN)
       family_(family),
 #endif
       text_size_(text_size),
       synthetic_bold_(synthetic_bold),
       synthetic_italic_(synthetic_italic),
       orientation_(orientation),
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
       style_(FontRenderStyle::QuerySystem(family_,
                                           text_size_,
                                           typeface_->fontStyle())),
 #endif
       is_hash_table_deleted_value_(false)
-#if OS(WIN)
+#if defined(OS_WIN)
       ,
       paint_text_flags_(0)
 #endif
 {
-#if OS(WIN)
+#if defined(OS_WIN)
   QuerySystemForRenderStyle();
 #endif
 }
 
 FontPlatformData::~FontPlatformData() {}
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 CTFontRef FontPlatformData::CtFont() const {
   return SkTypeface_GetCTFontRef(typeface_.get());
 };
@@ -180,7 +181,7 @@
     return *this;
 
   typeface_ = other.typeface_;
-#if !OS(WIN)
+#if !defined(OS_WIN)
   family_ = other.family_;
 #endif
   text_size_ = other.text_size_;
@@ -188,11 +189,11 @@
   synthetic_italic_ = other.synthetic_italic_;
   harf_buzz_face_ = nullptr;
   orientation_ = other.orientation_;
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
   style_ = other.style_;
 #endif
 
-#if OS(WIN)
+#if defined(OS_WIN)
   paint_text_flags_ = 0;
 #endif
 
@@ -212,7 +213,7 @@
          is_hash_table_deleted_value_ == a.is_hash_table_deleted_value_ &&
          synthetic_bold_ == a.synthetic_bold_ &&
          synthetic_italic_ == a.synthetic_italic_
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
          && style_ == a.style_
 #endif
          && orientation_ == a.orientation_;
@@ -311,7 +312,7 @@
   return h;
 }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 bool FontPlatformData::FontContainsCharacter(UChar32 character) {
   SkPaint paint;
   SetupPaint(&paint);
diff --git a/third_party/WebKit/Source/platform/fonts/FontPlatformData.h b/third_party/WebKit/Source/platform/fonts/FontPlatformData.h
index 7c27ed7..12dc8c4 100644
--- a/third_party/WebKit/Source/platform/fonts/FontPlatformData.h
+++ b/third_party/WebKit/Source/platform/fonts/FontPlatformData.h
@@ -33,6 +33,7 @@
 
 #include "SkPaint.h"
 #include "SkTypeface.h"
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/fonts/FontOrientation.h"
@@ -47,11 +48,11 @@
 #include "platform/wtf/text/StringImpl.h"
 #include "third_party/skia/include/core/SkRefCnt.h"
 
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
 #include "platform/fonts/linux/FontRenderStyle.h"
-#endif  // OS(LINUX) || OS(ANDROID)
+#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 OBJC_CLASS NSFont;
 
 typedef struct CGFont* CGFontRef;
@@ -65,7 +66,7 @@
 inline NSFont* toNSFont(CTFontRef ctFontRef) {
   return const_cast<NSFont*>(reinterpret_cast<const NSFont*>(ctFontRef));
 }
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
 
 class SkTypeface;
 typedef uint32_t SkFontID;
@@ -93,7 +94,7 @@
                    bool synthetic_italic,
                    FontOrientation = FontOrientation::kHorizontal);
   FontPlatformData(const FontPlatformData& src, float text_size);
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   FontPlatformData(NSFont*,
                    float size,
                    bool synthetic_bold,
@@ -109,7 +110,7 @@
                    FontOrientation = FontOrientation::kHorizontal);
   ~FontPlatformData();
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // These methods return a nullptr for FreeType backed SkTypefaces, compare
   // FontCustomPlatformData, which are used for variable fonts on Mac OS <
   // 10.12. They should not return nullptr otherwise. So they allow
@@ -151,7 +152,7 @@
   PassRefPtr<OpenTypeVerticalData> VerticalData() const;
   Vector<char> OpenTypeTable(SkFontTableTag) const;
 
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
   // The returned styles are all actual styles without
   // FontRenderStyle::NoPreference.
   const FontRenderStyle& GetFontRenderStyle() const { return style_; }
@@ -160,17 +161,17 @@
                   float device_scale_factor = 1,
                   const Font* = 0) const;
 
-#if OS(WIN)
+#if defined(OS_WIN)
   int PaintTextFlags() const { return paint_text_flags_; }
 #endif
 
  private:
-#if OS(WIN)
+#if defined(OS_WIN)
   void QuerySystemForRenderStyle();
 #endif
 
   sk_sp<SkTypeface> typeface_;
-#if !OS(WIN)
+#if !defined(OS_WIN)
   CString family_;
 #endif
 
@@ -181,13 +182,13 @@
   FontOrientation orientation_;
 
  private:
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
   FontRenderStyle style_;
 #endif
 
   mutable RefPtr<HarfBuzzFace> harf_buzz_face_;
   bool is_hash_table_deleted_value_;
-#if OS(WIN)
+#if defined(OS_WIN)
   int paint_text_flags_;
 #endif
 };
diff --git a/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp b/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp
index d422288..d837015 100644
--- a/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp
+++ b/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp
@@ -31,10 +31,14 @@
 
 #include <unicode/unorm.h>
 #include <unicode/utf16.h>
+
 #include <memory>
+
 #include "SkPath.h"
 #include "SkTypeface.h"
 #include "SkTypes.h"
+
+#include "build/build_config.h"
 #include "platform/fonts/FontDescription.h"
 #include "platform/fonts/VDMXParser.h"
 #include "platform/fonts/skia/SkiaTextMetrics.h"
@@ -51,7 +55,7 @@
 const float kSmallCapsFontSizeMultiplier = 0.7f;
 const float kEmphasisMarkFontSizeMultiplier = 0.5f;
 
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
 // This is the largest VDMX table which we'll try to load and parse.
 static const size_t kMaxVDMXTableSize = 1024 * 1024;  // 1 MB
 #endif
@@ -106,7 +110,7 @@
   int vdmx_ascent = 0, vdmx_descent = 0;
   bool is_vdmx_valid = false;
 
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
   // Manually digging up VDMX metrics is only applicable when bytecode hinting
   // using FreeType.  With DirectWrite or CoreText, no bytecode hinting is ever
   // done.  This code should be pushed into FreeType (hinted font metrics).
@@ -155,7 +159,7 @@
       visual_overflow_inflation_for_ascent_ = 1;
     if (descent < metrics.fDescent) {
       visual_overflow_inflation_for_descent_ = 1;
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
       // When subpixel positioning is enabled, if the descent is rounded down,
       // the descent part of the glyph may be truncated when displayed in a
       // 'overflow: hidden' container.  To avoid that, borrow 1 unit from the
@@ -172,7 +176,7 @@
     }
   }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // We are preserving this ascent hack to match Safari's ascent adjustment
   // in their SimpleFontDataMac.mm, for details see crbug.com/445830.
   // We need to adjust Times, Helvetica, and Courier to closely match the
@@ -195,7 +199,7 @@
   float x_height;
   if (metrics.fXHeight) {
     x_height = metrics.fXHeight;
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     // Mac OS CTFontGetXHeight reports the bounding box height of x,
     // including parts extending below the baseline and apparently no x-height
     // value from the OS/2 table. However, the CSS ex unit
@@ -232,7 +236,7 @@
 // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is
 // calculated for us, but we need to calculate m_maxCharWidth and
 // m_avgCharWidth in order for text entry widgets to be sized correctly.
-#if OS(WIN)
+#if defined(OS_WIN)
   max_char_width_ = SkScalarRoundToInt(metrics.fMaxCharWidth);
 
   // Older version of the DirectWrite API doesn't implement support for max
@@ -240,7 +244,7 @@
   // arbitrary but comes pretty close to the expected value in most cases.
   if (max_char_width_ < 1)
     max_char_width_ = ascent * 2;
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
   // FIXME: The current avg/max character width calculation is not ideal,
   // it should check either the OS2 table or, better yet, query FontMetrics.
   // Sadly FontMetrics provides incorrect data on Mac at the moment.
@@ -253,7 +257,7 @@
 
 #endif
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   if (metrics.fAvgCharWidth) {
     avg_char_width_ = SkScalarRoundToInt(metrics.fAvgCharWidth);
   } else {
@@ -263,7 +267,7 @@
     if (x_glyph) {
       avg_char_width_ = WidthForGlyph(x_glyph);
     }
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   }
 #endif
 
diff --git a/third_party/WebKit/Source/platform/fonts/SimpleFontData.h b/third_party/WebKit/Source/platform/fonts/SimpleFontData.h
index 5b174904..6c3ce43 100644
--- a/third_party/WebKit/Source/platform/fonts/SimpleFontData.h
+++ b/third_party/WebKit/Source/platform/fonts/SimpleFontData.h
@@ -25,7 +25,10 @@
 #define SimpleFontData_h
 
 #include <SkPaint.h>
+
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/fonts/CustomFontData.h"
 #include "platform/fonts/FontBaseline.h"
@@ -38,7 +41,7 @@
 #include "platform/wtf/PtrUtil.h"
 #include "platform/wtf/text/StringHash.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include "platform/fonts/GlyphMetricsMap.h"
 #endif
 
@@ -246,14 +249,14 @@
 // https://bugs.chromium.org/p/skia/issues/detail?id=5328 :
 // On Mac we're still using path based glyph metrics, and they seem to be
 // too slow to be able to remove the caching layer we have here.
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   mutable std::unique_ptr<GlyphMetricsMap<FloatRect>> glyph_to_bounds_map_;
   mutable GlyphMetricsMap<float> glyph_to_width_map_;
 #endif
 };
 
 ALWAYS_INLINE FloatRect SimpleFontData::BoundsForGlyph(Glyph glyph) const {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   return PlatformBoundsForGlyph(glyph);
 #else
   FloatRect bounds_result;
@@ -273,7 +276,7 @@
 }
 
 ALWAYS_INLINE float SimpleFontData::WidthForGlyph(Glyph glyph) const {
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   return PlatformWidthForGlyph(glyph);
 #else
   float width = glyph_to_width_map_.MetricsForGlyph(glyph);
diff --git a/third_party/WebKit/Source/platform/fonts/WebFontDecoder.cpp b/third_party/WebKit/Source/platform/fonts/WebFontDecoder.cpp
index fac7f50..ed953ea 100644
--- a/third_party/WebKit/Source/platform/fonts/WebFontDecoder.cpp
+++ b/third_party/WebKit/Source/platform/fonts/WebFontDecoder.cpp
@@ -216,7 +216,7 @@
 
   sk_sp<SkData> sk_data = SkData::MakeWithCopy(output.get(), decoded_length);
   SkMemoryStream* stream = new SkMemoryStream(sk_data);
-#if OS(WIN)
+#if defined(OS_WIN)
   sk_sp<SkTypeface> typeface(
       FontCache::GetFontCache()->FontManager()->createFromStream(stream));
 #else
diff --git a/third_party/WebKit/Source/platform/fonts/linux/FontCacheLinux.cpp b/third_party/WebKit/Source/platform/fonts/linux/FontCacheLinux.cpp
index 304fb37..b034c71e 100644
--- a/third_party/WebKit/Source/platform/fonts/linux/FontCacheLinux.cpp
+++ b/third_party/WebKit/Source/platform/fonts/linux/FontCacheLinux.cpp
@@ -24,6 +24,7 @@
 
 #include "platform/fonts/FontCache.h"
 
+#include "build/build_config.h"
 #include "platform/fonts/FontPlatformData.h"
 #include "platform/fonts/SimpleFontData.h"
 #include "platform/wtf/text/CString.h"
@@ -83,7 +84,7 @@
   }
 }
 
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
 PassRefPtr<SimpleFontData> FontCache::FallbackFontForCharacter(
     const FontDescription& font_description,
     UChar32 c,
@@ -167,6 +168,6 @@
   return FontDataFromFontPlatformData(platform_data.get(), kDoNotRetain);
 }
 
-#endif  // !OS(ANDROID)
+#endif  // !defined(OS_ANDROID)
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/fonts/linux/FontRenderStyle.cpp b/third_party/WebKit/Source/platform/fonts/linux/FontRenderStyle.cpp
index 2c95754d..658bc84 100644
--- a/third_party/WebKit/Source/platform/fonts/linux/FontRenderStyle.cpp
+++ b/third_party/WebKit/Source/platform/fonts/linux/FontRenderStyle.cpp
@@ -4,6 +4,7 @@
 
 #include "platform/fonts/linux/FontRenderStyle.h"
 
+#include "build/build_config.h"
 #include "platform/LayoutTestSupport.h"
 #include "platform/fonts/FontDescription.h"
 #include "public/platform/Platform.h"
@@ -52,7 +53,7 @@
                                              float text_size,
                                              SkFontStyle font_style) {
   WebFontRenderStyle style;
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   style.SetDefaults();
 #else
   // If the font name is missing (i.e. probably a web font) or the sandbox is
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
index 548e4e5..7c27533 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
+++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
@@ -31,6 +31,8 @@
 #include "platform/fonts/shaping/HarfBuzzFace.h"
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/Histogram.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/fonts/FontGlobalContext.h"
@@ -46,7 +48,7 @@
 
 #include <hb-ot.h>
 #include <hb.h>
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include <hb-coretext.h>
 #endif
 
@@ -267,7 +269,7 @@
 }
 
 hb_face_t* HarfBuzzFace::CreateFace() {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // hb_face_t needs to be instantiated using the CoreText constructor for
   // compatibility with AAT font, in which case HarfBuzz' CoreText backend is
   // used. If we encounter a FreeType backed SkTypeface, for variable fonts on
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaperTest.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaperTest.cpp
index 0fab5bcd..ef8cabe8 100644
--- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaperTest.cpp
+++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaperTest.cpp
@@ -5,6 +5,8 @@
 #include "platform/fonts/shaping/HarfBuzzShaper.h"
 
 #include <unicode/uscript.h>
+
+#include "build/build_config.h"
 #include "platform/fonts/Font.h"
 #include "platform/fonts/FontCache.h"
 #include "platform/fonts/shaping/ShapeResultInlineHeaders.h"
@@ -96,7 +98,7 @@
 // If the specified VS is not in the font, it's mapped to .notdef.
 // then hb_ot_hide_default_ignorables() swaps it to a space with zero-advance.
 // http://lists.freedesktop.org/archives/harfbuzz/2015-May/004888.html
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
       EXPECT_EQ(TestInfo(result)->FontDataForTesting(0)->SpaceGlyph(),
                 TestInfo(result)->GlyphForTesting(0, 1))
           << test.name;
diff --git a/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp b/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp
index c9ea688..3a4e9fd 100644
--- a/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp
+++ b/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp
@@ -30,10 +30,14 @@
  */
 
 #include <unicode/locid.h>
+
 #include <memory>
+
 #include "SkFontMgr.h"
 #include "SkStream.h"
 #include "SkTypeface.h"
+
+#include "build/build_config.h"
 #include "platform/Language.h"
 #include "platform/fonts/AlternateFontFamily.h"
 #include "platform/fonts/FontCache.h"
@@ -48,7 +52,7 @@
 #include "public/platform/Platform.h"
 #include "public/platform/linux/WebSandboxSupport.h"
 
-#if !OS(WIN) && !OS(ANDROID)
+#if !defined(OS_WIN) && !defined(OS_ANDROID)
 #include "SkFontConfigInterface.h"
 
 static sk_sp<SkTypeface> typefaceForFontconfigInterfaceIdAndTtcIndex(
@@ -68,7 +72,7 @@
   return AtomicString::FromUTF8(str.c_str(), str.size());
 }
 
-#if OS(ANDROID) || OS(LINUX)
+#if defined(OS_ANDROID) || defined(OS_LINUX)
 // Android special locale for retrieving the color emoji font
 // based on the proposed changes in UTR #51 for introducing
 // an Emoji script code:
@@ -163,7 +167,7 @@
     font_platform_data = GetFontPlatformData(description, arial_creation_params,
                                              AlternateFontName::kLastResort);
   }
-#if OS(WIN)
+#if defined(OS_WIN)
   // Try some more Windows-specific fallbacks.
   if (!font_platform_data) {
     DEFINE_STATIC_LOCAL(const FontFaceCreationParams,
@@ -219,7 +223,7 @@
     const FontDescription& font_description,
     const FontFaceCreationParams& creation_params,
     CString& name) {
-#if !OS(WIN) && !OS(ANDROID)
+#if !defined(OS_WIN) && !defined(OS_ANDROID)
   if (creation_params.CreationType() == kCreateFontByFciIdAndTtcIndex) {
     if (Platform::Current()->GetSandboxSupport())
       return typefaceForFontconfigInterfaceIdAndTtcIndex(
@@ -240,7 +244,7 @@
     name = family.Utf8();
   }
 
-#if OS(WIN)
+#if defined(OS_WIN)
   if (sideloaded_fonts_) {
     HashMap<String, sk_sp<SkTypeface>>::iterator sideloaded_font =
         sideloaded_fonts_->find(name.data());
@@ -249,7 +253,7 @@
   }
 #endif
 
-#if OS(LINUX) || OS(WIN)
+#if defined(OS_LINUX) || defined(OS_WIN)
   // On linux if the fontManager has been overridden then we should be calling
   // the embedder provided font Manager rather than calling
   // SkTypeface::CreateFromName which may redirect the call to the default font
@@ -266,7 +270,7 @@
       fm->legacyCreateTypeface(name.data(), font_description.SkiaFontStyle()));
 }
 
-#if !OS(WIN)
+#if !defined(OS_WIN)
 std::unique_ptr<FontPlatformData> FontCache::CreateFontPlatformData(
     const FontDescription& font_description,
     const FontFaceCreationParams& creation_params,
@@ -289,6 +293,6 @@
                                font_description.IsSyntheticItalic(),
                            font_description.Orientation()));
 }
-#endif  // !OS(WIN)
+#endif  // !defined(OS_WIN)
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/fonts/skia/SkiaTextMetrics.cpp b/third_party/WebKit/Source/platform/fonts/skia/SkiaTextMetrics.cpp
index 285bad7f3..df2ecfb 100644
--- a/third_party/WebKit/Source/platform/fonts/skia/SkiaTextMetrics.cpp
+++ b/third_party/WebKit/Source/platform/fonts/skia/SkiaTextMetrics.cpp
@@ -4,6 +4,7 @@
 
 #include "SkiaTextMetrics.h"
 
+#include "build/build_config.h"
 #include "platform/wtf/MathExtras.h"
 
 #include <SkPath.h>
@@ -60,7 +61,7 @@
 }
 
 void SkiaTextMetrics::GetSkiaBoundsForGlyph(Glyph glyph, SkRect* bounds) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // TODO(drott): Remove this once we have better metrics bounds
   // on Mac, https://bugs.chromium.org/p/skia/issues/detail?id=5328
   SkPath path;
diff --git a/third_party/WebKit/Source/platform/geometry/FloatPoint.h b/third_party/WebKit/Source/platform/geometry/FloatPoint.h
index 1667a94..42538c8 100644
--- a/third_party/WebKit/Source/platform/geometry/FloatPoint.h
+++ b/third_party/WebKit/Source/platform/geometry/FloatPoint.h
@@ -29,6 +29,8 @@
 
 #include <algorithm>
 #include <iosfwd>
+
+#include "build/build_config.h"
 #include "platform/geometry/FloatSize.h"
 #include "platform/geometry/IntPoint.h"
 #include "platform/wtf/Allocator.h"
@@ -36,7 +38,7 @@
 #include "platform/wtf/MathExtras.h"
 #include "third_party/skia/include/core/SkPoint.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 typedef struct CGPoint CGPoint;
 
 #ifdef __OBJC__
@@ -128,7 +130,7 @@
     return FloatPoint(x_ * scale, y_ * scale);
   }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   FloatPoint(const CGPoint&);
   operator CGPoint() const;
 #if defined(__OBJC__) && !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
diff --git a/third_party/WebKit/Source/platform/geometry/FloatRect.h b/third_party/WebKit/Source/platform/geometry/FloatRect.h
index 77a306f..7906580 100644
--- a/third_party/WebKit/Source/platform/geometry/FloatRect.h
+++ b/third_party/WebKit/Source/platform/geometry/FloatRect.h
@@ -28,6 +28,8 @@
 #define FloatRect_h
 
 #include <iosfwd>
+
+#include "build/build_config.h"
 #include "platform/geometry/FloatPoint.h"
 #include "platform/geometry/FloatRectOutsets.h"
 #include "platform/geometry/IntRect.h"
@@ -36,7 +38,7 @@
 #include "platform/wtf/Vector.h"
 #include "third_party/skia/include/core/SkRect.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 typedef struct CGRect CGRect;
 
 #ifdef __OBJC__
@@ -185,7 +187,7 @@
 
   float SquaredDistanceTo(const FloatPoint&) const;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   FloatRect(const CGRect&);
   operator CGRect() const;
 #if defined(__OBJC__) && !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
diff --git a/third_party/WebKit/Source/platform/geometry/FloatSize.h b/third_party/WebKit/Source/platform/geometry/FloatSize.h
index 0dbbafe..29b7152f 100644
--- a/third_party/WebKit/Source/platform/geometry/FloatSize.h
+++ b/third_party/WebKit/Source/platform/geometry/FloatSize.h
@@ -29,13 +29,15 @@
 #define FloatSize_h
 
 #include <iosfwd>
+
+#include "build/build_config.h"
 #include "platform/geometry/IntPoint.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Forward.h"
 #include "platform/wtf/MathExtras.h"
 #include "third_party/skia/include/core/SkSize.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 typedef struct CGSize CGSize;
 
 #ifdef __OBJC__
@@ -114,7 +116,7 @@
     return FloatSize(width_ * scale_x, height_ * scale_y);
   }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   explicit FloatSize(
       const CGSize&);  // don't do this implicitly since it's lossy
   operator CGSize() const;
diff --git a/third_party/WebKit/Source/platform/geometry/IntPoint.h b/third_party/WebKit/Source/platform/geometry/IntPoint.h
index 26fe3ec6..a9091f5 100644
--- a/third_party/WebKit/Source/platform/geometry/IntPoint.h
+++ b/third_party/WebKit/Source/platform/geometry/IntPoint.h
@@ -27,6 +27,7 @@
 #ifndef IntPoint_h
 #define IntPoint_h
 
+#include "build/build_config.h"
 #include "platform/geometry/IntSize.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Forward.h"
@@ -34,7 +35,7 @@
 #include "platform/wtf/SaturatedArithmetic.h"
 #include "platform/wtf/VectorTraits.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 typedef struct CGPoint CGPoint;
 
 #ifdef __OBJC__
@@ -93,7 +94,7 @@
 
   IntPoint TransposedPoint() const { return IntPoint(y_, x_); }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   explicit IntPoint(
       const CGPoint&);  // don't do this implicitly since it's lossy
   operator CGPoint() const;
diff --git a/third_party/WebKit/Source/platform/geometry/IntRect.h b/third_party/WebKit/Source/platform/geometry/IntRect.h
index d4a44839..7da480f 100644
--- a/third_party/WebKit/Source/platform/geometry/IntRect.h
+++ b/third_party/WebKit/Source/platform/geometry/IntRect.h
@@ -26,6 +26,7 @@
 #ifndef IntRect_h
 #define IntRect_h
 
+#include "build/build_config.h"
 #include "platform/geometry/IntPoint.h"
 #include "platform/geometry/IntRectOutsets.h"
 #include "platform/wtf/Allocator.h"
@@ -33,7 +34,7 @@
 #include "platform/wtf/Vector.h"
 #include "platform/wtf/VectorTraits.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 typedef struct CGRect CGRect;
 
 #ifdef __OBJC__
@@ -188,7 +189,7 @@
     return IntRect(location_.TransposedPoint(), size_.TransposedSize());
   }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   operator CGRect() const;
 #if defined(__OBJC__) && !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
   operator NSRect() const;
@@ -237,7 +238,7 @@
   return a.Location() != b.Location() || a.Size() != b.Size();
 }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 PLATFORM_EXPORT IntRect EnclosingIntRect(const CGRect&);
 #if defined(__OBJC__) && !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
 PLATFORM_EXPORT IntRect enclosingIntRect(const NSRect&);
diff --git a/third_party/WebKit/Source/platform/geometry/IntSize.h b/third_party/WebKit/Source/platform/geometry/IntSize.h
index 5a4ff68..365bc7f 100644
--- a/third_party/WebKit/Source/platform/geometry/IntSize.h
+++ b/third_party/WebKit/Source/platform/geometry/IntSize.h
@@ -28,12 +28,13 @@
 #ifndef IntSize_h
 #define IntSize_h
 
+#include "build/build_config.h"
 #include "platform/PlatformExport.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Forward.h"
 #include "public/platform/WebCommon.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 typedef struct CGSize CGSize;
 
 #ifdef __OBJC__
@@ -107,7 +108,7 @@
 
   IntSize TransposedSize() const { return IntSize(height_, width_); }
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   explicit IntSize(const CGSize&);  // don't do this implicitly since it's lossy
   operator CGSize() const;
 
diff --git a/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.cpp b/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.cpp
index c18fc42..d45cba62 100644
--- a/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.cpp
+++ b/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.cpp
@@ -35,19 +35,149 @@
 
 namespace blink {
 
-LayoutRectOutsets LayoutRectOutsets::LineOrientationOutsets(
+LayoutUnit LayoutRectOutsets::LogicalTop(WritingMode writing_mode) const {
+  return IsHorizontalWritingMode(writing_mode) ? top_ : left_;
+}
+
+LayoutUnit LayoutRectOutsets::LogicalBottom(WritingMode writing_mode) const {
+  return IsHorizontalWritingMode(writing_mode) ? bottom_ : right_;
+}
+
+LayoutUnit LayoutRectOutsets::LogicalLeft(WritingMode writing_mode) const {
+  return IsHorizontalWritingMode(writing_mode) ? left_ : top_;
+}
+
+LayoutUnit LayoutRectOutsets::LogicalRight(WritingMode writing_mode) const {
+  return IsHorizontalWritingMode(writing_mode) ? right_ : bottom_;
+}
+
+LayoutRectOutsets LayoutRectOutsets::LogicalOutsets(
     WritingMode writing_mode) const {
   if (!IsHorizontalWritingMode(writing_mode))
     return LayoutRectOutsets(left_, bottom_, right_, top_);
   return *this;
 }
 
-LayoutRectOutsets LayoutRectOutsets::LineOrientationOutsetsWithFlippedLines(
+LayoutRectOutsets LayoutRectOutsets::LogicalOutsetsWithFlippedLines(
     WritingMode writing_mode) const {
-  LayoutRectOutsets outsets = LineOrientationOutsets(writing_mode);
+  LayoutRectOutsets outsets = LogicalOutsets(writing_mode);
   if (IsFlippedLinesWritingMode(writing_mode))
     std::swap(outsets.top_, outsets.bottom_);
   return outsets;
 }
 
+LayoutUnit LayoutRectOutsets::Before(WritingMode writing_mode) const {
+  switch (writing_mode) {
+    case WritingMode::kHorizontalTb:
+      return top_;
+    case WritingMode::kVerticalLr:
+      return left_;
+    case WritingMode::kVerticalRl:
+      return right_;
+  }
+  NOTREACHED();
+  return top_;
+}
+
+LayoutUnit LayoutRectOutsets::After(WritingMode writing_mode) const {
+  switch (writing_mode) {
+    case WritingMode::kHorizontalTb:
+      return bottom_;
+    case WritingMode::kVerticalLr:
+      return right_;
+    case WritingMode::kVerticalRl:
+      return left_;
+  }
+  NOTREACHED();
+  return bottom_;
+}
+
+LayoutUnit LayoutRectOutsets::Start(WritingMode writing_mode,
+                                    TextDirection direction) const {
+  if (IsHorizontalWritingMode(writing_mode))
+    return IsLtr(direction) ? left_ : right_;
+  return IsLtr(direction) ? top_ : bottom_;
+}
+
+LayoutUnit LayoutRectOutsets::end(WritingMode writing_mode,
+                                  TextDirection direction) const {
+  if (IsHorizontalWritingMode(writing_mode))
+    return IsLtr(direction) ? right_ : left_;
+  return IsLtr(direction) ? bottom_ : top_;
+}
+
+LayoutUnit LayoutRectOutsets::Over(WritingMode writing_mode) const {
+  return IsHorizontalWritingMode(writing_mode) ? top_ : right_;
+}
+
+LayoutUnit LayoutRectOutsets::Under(WritingMode writing_mode) const {
+  return IsHorizontalWritingMode(writing_mode) ? bottom_ : left_;
+}
+
+void LayoutRectOutsets::SetBefore(WritingMode writing_mode, LayoutUnit value) {
+  switch (writing_mode) {
+    case WritingMode::kHorizontalTb:
+      top_ = value;
+      break;
+    case WritingMode::kVerticalLr:
+      left_ = value;
+      break;
+    case WritingMode::kVerticalRl:
+      right_ = value;
+      break;
+    default:
+      NOTREACHED();
+      top_ = value;
+  }
+}
+
+void LayoutRectOutsets::SetAfter(WritingMode writing_mode, LayoutUnit value) {
+  switch (writing_mode) {
+    case WritingMode::kHorizontalTb:
+      bottom_ = value;
+      break;
+    case WritingMode::kVerticalLr:
+      right_ = value;
+      break;
+    case WritingMode::kVerticalRl:
+      left_ = value;
+      break;
+    default:
+      NOTREACHED();
+      bottom_ = value;
+  }
+}
+
+void LayoutRectOutsets::SetStart(WritingMode writing_mode,
+                                 TextDirection direction,
+                                 LayoutUnit value) {
+  if (IsHorizontalWritingMode(writing_mode)) {
+    if (IsLtr(direction))
+      left_ = value;
+    else
+      right_ = value;
+  } else {
+    if (IsLtr(direction))
+      top_ = value;
+    else
+      bottom_ = value;
+  }
+}
+
+void LayoutRectOutsets::SetEnd(WritingMode writing_mode,
+                               TextDirection direction,
+                               LayoutUnit value) {
+  if (IsHorizontalWritingMode(writing_mode)) {
+    if (IsLtr(direction))
+      right_ = value;
+    else
+      left_ = value;
+  } else {
+    if (IsLtr(direction))
+      bottom_ = value;
+    else
+      top_ = value;
+  }
+}
+
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.h b/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.h
index 957cea4..82fb78a3 100644
--- a/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.h
+++ b/third_party/WebKit/Source/platform/geometry/LayoutRectOutsets.h
@@ -35,6 +35,7 @@
 #include "platform/PlatformExport.h"
 #include "platform/geometry/FloatRectOutsets.h"
 #include "platform/geometry/IntRectOutsets.h"
+#include "platform/text/TextDirection.h"
 #include "platform/text/WritingMode.h"
 #include "platform/wtf/Allocator.h"
 
@@ -83,16 +84,29 @@
   void SetBottom(LayoutUnit value) { bottom_ = value; }
   void SetLeft(LayoutUnit value) { left_ = value; }
 
-  // Produces a new LayoutRectOutsets in line orientation
-  // (https://www.w3.org/TR/css-writing-modes-3/#line-orientation), whose
-  // - |top| is the logical 'over',
-  // - |right| is the logical 'line right',
-  // - |bottom| is the logical 'under',
-  // - |left| is the logical 'line left'.
-  LayoutRectOutsets LineOrientationOutsets(WritingMode) const;
+  LayoutUnit LogicalTop(WritingMode) const;
+  LayoutUnit LogicalBottom(WritingMode) const;
+  LayoutUnit LogicalLeft(WritingMode) const;
+  LayoutUnit LogicalRight(WritingMode) const;
+
+  // Produces a new LayoutRectOutsets whose |top| is the |logicalTop| of this
+  // one, and so on.
+  LayoutRectOutsets LogicalOutsets(WritingMode) const;
 
   // The same as |logicalOutsets|, but also adjusting for flipped lines.
-  LayoutRectOutsets LineOrientationOutsetsWithFlippedLines(WritingMode) const;
+  LayoutRectOutsets LogicalOutsetsWithFlippedLines(WritingMode) const;
+
+  LayoutUnit Before(WritingMode) const;
+  LayoutUnit After(WritingMode) const;
+  LayoutUnit Start(WritingMode, TextDirection) const;
+  LayoutUnit end(WritingMode, TextDirection) const;
+  LayoutUnit Over(WritingMode) const;
+  LayoutUnit Under(WritingMode) const;
+
+  void SetBefore(WritingMode, LayoutUnit);
+  void SetAfter(WritingMode, LayoutUnit);
+  void SetStart(WritingMode, TextDirection, LayoutUnit);
+  void SetEnd(WritingMode, TextDirection, LayoutUnit);
 
   bool operator==(const LayoutRectOutsets other) const {
     return Top() == other.Top() && Right() == other.Right() &&
diff --git a/third_party/WebKit/Source/platform/geometry/LayoutRectOutsetsTest.cpp b/third_party/WebKit/Source/platform/geometry/LayoutRectOutsetsTest.cpp
index d5da787..d1a389a 100644
--- a/third_party/WebKit/Source/platform/geometry/LayoutRectOutsetsTest.cpp
+++ b/third_party/WebKit/Source/platform/geometry/LayoutRectOutsetsTest.cpp
@@ -9,31 +9,28 @@
 namespace blink {
 namespace {
 
-TEST(LayoutRectOutsetsTest, LineOrientationOutsets_Horizontal) {
+TEST(LayoutRectOutsetsTest, LogicalOutsets_Horizontal) {
   LayoutRectOutsets outsets(1, 2, 3, 4);
   EXPECT_EQ(LayoutRectOutsets(1, 2, 3, 4),
-            outsets.LineOrientationOutsets(WritingMode::kHorizontalTb));
+            outsets.LogicalOutsets(WritingMode::kHorizontalTb));
 }
 
-TEST(LayoutRectOutsetsTest, LineOrientationOutsets_Vertical) {
+TEST(LayoutRectOutsetsTest, LogicalOutsets_Vertical) {
   LayoutRectOutsets outsets(1, 2, 3, 4);
   EXPECT_EQ(LayoutRectOutsets(4, 3, 2, 1),
-            outsets.LineOrientationOutsets(WritingMode::kVerticalLr));
+            outsets.LogicalOutsets(WritingMode::kVerticalLr));
   EXPECT_EQ(LayoutRectOutsets(4, 3, 2, 1),
-            outsets.LineOrientationOutsets(WritingMode::kVerticalRl));
+            outsets.LogicalOutsets(WritingMode::kVerticalRl));
 }
 
-TEST(LayoutRectOutsetsTest, LineOrientationOutsetsWithFlippedLines) {
+TEST(LayoutRectOutsetsTest, LogicalOutsetsWithFlippedLines) {
   LayoutRectOutsets outsets(1, 2, 3, 4);
   EXPECT_EQ(LayoutRectOutsets(1, 2, 3, 4),
-            outsets.LineOrientationOutsetsWithFlippedLines(
-                WritingMode::kHorizontalTb));
-  EXPECT_EQ(
-      LayoutRectOutsets(2, 3, 4, 1),
-      outsets.LineOrientationOutsetsWithFlippedLines(WritingMode::kVerticalLr));
-  EXPECT_EQ(
-      LayoutRectOutsets(4, 3, 2, 1),
-      outsets.LineOrientationOutsetsWithFlippedLines(WritingMode::kVerticalRl));
+            outsets.LogicalOutsetsWithFlippedLines(WritingMode::kHorizontalTb));
+  EXPECT_EQ(LayoutRectOutsets(2, 3, 4, 1),
+            outsets.LogicalOutsetsWithFlippedLines(WritingMode::kVerticalLr));
+  EXPECT_EQ(LayoutRectOutsets(4, 3, 2, 1),
+            outsets.LogicalOutsetsWithFlippedLines(WritingMode::kVerticalRl));
 }
 
 }  // namespace
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h
index eec71a5..d312ceda 100644
--- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h
+++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridge.h
@@ -26,6 +26,7 @@
 #ifndef Canvas2DLayerBridge_h
 #define Canvas2DLayerBridge_h
 
+#include "build/build_config.h"
 #include "cc/layers/texture_layer_client.h"
 #include "cc/resources/texture_mailbox.h"
 #include "platform/PlatformExport.h"
@@ -61,7 +62,7 @@
 class WebGraphicsContext3DProvider;
 class SharedContextRateLimiter;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 // Canvas hibernation is currently disabled on MacOS X due to a bug that causes
 // content loss. TODO: Find a better fix for crbug.com/588434
 #define CANVAS2D_HIBERNATION_ENABLED 0
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp
index e60f829..29aeb3f 100644
--- a/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp
+++ b/third_party/WebKit/Source/platform/graphics/GraphicsContext.cpp
@@ -27,6 +27,8 @@
 #include "platform/graphics/GraphicsContext.h"
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/geometry/FloatRect.h"
 #include "platform/geometry/FloatRoundedRect.h"
 #include "platform/geometry/IntRect.h"
@@ -366,7 +368,7 @@
 namespace {
 
 int AdjustedFocusRingOffset(int offset) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   return offset + 2;
 #else
   return 0;
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp
index 2e354e6..3595d7f3 100644
--- a/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp
+++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp
@@ -69,10 +69,13 @@
     layer_tree_view_ = WTF::WrapUnique(new WebLayerTreeViewImplForTesting);
     DCHECK(layer_tree_view_);
     layer_tree_view_->SetRootLayer(*clip_layer_->PlatformLayer());
-    layer_tree_view_->RegisterViewportLayers(
-        scroll_elasticity_layer_->PlatformLayer(),
-        page_scale_layer_->PlatformLayer(), clip_layer_->PlatformLayer(),
-        nullptr, graphics_layer_->PlatformLayer(), nullptr);
+    WebLayerTreeView::ViewportLayers viewport_layers;
+    viewport_layers.overscroll_elasticity =
+        scroll_elasticity_layer_->PlatformLayer();
+    viewport_layers.page_scale = page_scale_layer_->PlatformLayer();
+    viewport_layers.inner_viewport_container = clip_layer_->PlatformLayer();
+    viewport_layers.inner_viewport_scroll = graphics_layer_->PlatformLayer();
+    layer_tree_view_->RegisterViewportLayers(viewport_layers);
     layer_tree_view_->SetViewportSize(WebSize(1, 1));
   }
 
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp
index b28d7aa0..8dd4bce 100644
--- a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp
+++ b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp
@@ -32,6 +32,8 @@
 
 #include <algorithm>
 #include <memory>
+
+#include "build/build_config.h"
 #include "cc/resources/shared_bitmap.h"
 #include "gpu/GLES2/gl2extchromium.h"
 #include "gpu/command_buffer/client/gles2_interface.h"
@@ -381,7 +383,7 @@
         color_buffer_for_mailbox->parameters.target,
         color_buffer_for_mailbox->mailbox.name);
     const GLuint64 fence_sync = gl_->InsertFenceSyncCHROMIUM();
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     gl_->DescheduleUntilFinishedCHROMIUM();
 #endif
     gl_->Flush();
@@ -523,7 +525,7 @@
 
 DrawingBuffer::ColorBufferParameters
 DrawingBuffer::GpuMemoryBufferColorBufferParameters() {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // A CHROMIUM_image backed texture requires a specialized set of parameters
   // on OSX.
   ColorBufferParameters parameters;
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTestHelpers.h b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTestHelpers.h
index ec89a02..1c4fad3 100644
--- a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTestHelpers.h
+++ b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTestHelpers.h
@@ -5,6 +5,7 @@
 #ifndef DrawingBufferTestHelpers_h
 #define DrawingBufferTestHelpers_h
 
+#include "build/build_config.h"
 #include "gpu/command_buffer/common/capabilities.h"
 #include "platform/RuntimeEnabledFeatures.h"
 #include "platform/graphics/CanvasColorParams.h"
@@ -52,7 +53,7 @@
 
 // The target to use when binding a texture to a Chromium image.
 GLenum ImageCHROMIUMTextureTarget() {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   return GC3D_TEXTURE_RECTANGLE_ARB;
 #else
   return GL_TEXTURE_2D;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp
index d2921ee4..4f9939ac 100644
--- a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp
+++ b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp
@@ -4,6 +4,8 @@
 
 #include "platform/graphics/paint/PaintController.h"
 
+#include <memory>
+#include "build/build_config.h"
 #include "platform/RuntimeEnabledFeatures.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "platform/graphics/paint/ClipPathDisplayItem.h"
@@ -18,7 +20,6 @@
 #include "platform/testing/RuntimeEnabledFeaturesTestHelpers.h"
 #include "testing/gmock/include/gmock/gmock.h"
 #include "testing/gtest/include/gtest/gtest.h"
-#include <memory>
 
 using blink::testing::CreateOpacityOnlyEffect;
 using blink::testing::DefaultPaintChunkProperties;
@@ -2065,7 +2066,7 @@
 }
 
 // Death tests don't work properly on Android.
-#if defined(GTEST_HAS_DEATH_TEST) && !OS(ANDROID)
+#if defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID)
 
 class PaintControllerUnderInvalidationTest
     : public PaintControllerTestBase,
@@ -2322,6 +2323,6 @@
   TestInvalidationInSubsequence();
 }
 
-#endif  // defined(GTEST_HAS_DEATH_TEST) && !OS(ANDROID)
+#endif  // defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID)
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp b/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp
index 8d38aac9..5acb409 100644
--- a/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp
+++ b/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp
@@ -30,6 +30,7 @@
 
 #include "platform/graphics/skia/SkiaUtils.h"
 
+#include "build/build_config.h"
 #include "platform/graphics/GraphicsContext.h"
 #include "platform/graphics/paint/PaintFlags.h"
 #include "third_party/skia/include/effects/SkCornerPathEffect.h"
@@ -347,7 +348,7 @@
   flags.setColor(color);
   flags.setStrokeWidth(width);
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   flags.setAlpha(64);
   const float corner_radius = (width - 1) * 0.5f;
 #else
@@ -356,7 +357,7 @@
 
   DrawFocusRingPrimitive(primitive, canvas, flags, corner_radius);
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // Inner part
   flags.setAlpha(128);
   flags.setStrokeWidth(flags.getStrokeWidth() * 0.5f);
diff --git a/third_party/WebKit/Source/platform/heap/HeapPage.h b/third_party/WebKit/Source/platform/heap/HeapPage.h
index 8041ef2..03c971b 100644
--- a/third_party/WebKit/Source/platform/heap/HeapPage.h
+++ b/third_party/WebKit/Source/platform/heap/HeapPage.h
@@ -934,10 +934,10 @@
   const uintptr_t random1 = ~(RotateLeft16(reinterpret_cast<uintptr_t>(
       base::trace_event::MemoryAllocatorDump::kNameSize)));
 
-#if OS(WIN)
+#if defined(OS_WIN)
   const uintptr_t random2 =
       ~(RotateLeft16(reinterpret_cast<uintptr_t>(::ReadFile)));
-#elif OS(POSIX)
+#elif defined(OS_POSIX)
   const uintptr_t random2 =
       ~(RotateLeft16(reinterpret_cast<uintptr_t>(::read)));
 #else
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
index ba638be..7709d3b 100644
--- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp
+++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -30,6 +30,8 @@
 
 #include <algorithm>
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/CrossThreadFunctional.h"
 #include "platform/WebTaskRunner.h"
 #include "platform/heap/Handle.h"
@@ -5578,7 +5580,7 @@
 #if DCHECK_IS_ON()
 // TODO(keishi) This test is flaky on mac_chromium_rel_ng bot.
 // crbug.com/709069
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 TEST(HeapDeathTest, MemberSameThreadCheck) {
   EXPECT_DEATH(MemberSameThreadCheckTester().Test(), "");
 }
@@ -5621,7 +5623,7 @@
 #if DCHECK_IS_ON()
 // TODO(keishi) This test is flaky on mac_chromium_rel_ng bot.
 // crbug.com/709069
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 TEST(HeapDeathTest, PersistentSameThreadCheck) {
   EXPECT_DEATH(PersistentSameThreadCheckTester().Test(), "");
 }
@@ -5675,7 +5677,7 @@
 #if DCHECK_IS_ON()
 // TODO(keishi) This test is flaky on mac_chromium_rel_ng bot.
 // crbug.com/709069
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 TEST(HeapDeathTest, MarkingSameThreadCheck) {
   // This will crash during marking, at the DCHECK in Visitor::markHeader() or
   // earlier.
@@ -6033,7 +6035,7 @@
 // The allocation & GC overhead is considerable for this test,
 // straining debug builds and lower-end targets too much to be
 // worth running.
-#if !DCHECK_IS_ON() && !OS(ANDROID)
+#if !DCHECK_IS_ON() && !defined(OS_ANDROID)
   DeepEagerly* obj = nullptr;
   for (int i = 0; i < 10000000; i++)
     obj = new DeepEagerly(obj);
diff --git a/third_party/WebKit/Source/platform/heap/StackFrameDepth.cpp b/third_party/WebKit/Source/platform/heap/StackFrameDepth.cpp
index 07e82f8..41a25d5f 100644
--- a/third_party/WebKit/Source/platform/heap/StackFrameDepth.cpp
+++ b/third_party/WebKit/Source/platform/heap/StackFrameDepth.cpp
@@ -7,7 +7,7 @@
 #include "platform/wtf/StackUtil.h"
 #include "public/platform/Platform.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <stddef.h>
 #include <windows.h>
 #include <winnt.h>
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.cpp b/third_party/WebKit/Source/platform/heap/ThreadState.cpp
index 9d2fd134..94a232d 100644
--- a/third_party/WebKit/Source/platform/heap/ThreadState.cpp
+++ b/third_party/WebKit/Source/platform/heap/ThreadState.cpp
@@ -31,8 +31,11 @@
 #include "platform/heap/ThreadState.h"
 
 #include <v8.h>
+
 #include <memory>
+
 #include "base/trace_event/process_memory_dump.h"
+#include "build/build_config.h"
 #include "platform/Histogram.h"
 #include "platform/RuntimeEnabledFeatures.h"
 #include "platform/ScriptForbiddenScope.h"
@@ -59,7 +62,7 @@
 #include "public/platform/WebThread.h"
 #include "public/platform/WebTraceLocation.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <stddef.h>
 #include <windows.h>
 #include <winnt.h>
@@ -69,7 +72,7 @@
 #include <sanitizer/msan_interface.h>
 #endif
 
-#if OS(FREEBSD)
+#if defined(OS_FREEBSD)
 #include <pthread_np.h>
 #endif
 
diff --git a/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h b/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h
index f28d3d8..ffdb27d 100644
--- a/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h
+++ b/third_party/WebKit/Source/platform/loader/fetch/FetchContext.h
@@ -32,6 +32,7 @@
 #define FetchContext_h
 
 #include "platform/PlatformExport.h"
+#include "platform/WebFrameScheduler.h"
 #include "platform/heap/Handle.h"
 #include "platform/loader/fetch/FetchInitiatorInfo.h"
 #include "platform/loader/fetch/FetchParameters.h"
@@ -219,6 +220,10 @@
 
   virtual bool IsDetached() const { return false; }
 
+  // Obtains WebFrameScheduler instance that is used in the attached frame.
+  // May return nullptr if a frame is not attached or detached.
+  virtual WebFrameScheduler* GetFrameScheduler() { return nullptr; }
+
   // Called when the underlying context is detached. Note that some
   // FetchContexts continue working after detached (e.g., for fetch() operations
   // with "keepalive" specified).
diff --git a/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp b/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp
index 8f905a78..88bf5f93 100644
--- a/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp
+++ b/third_party/WebKit/Source/platform/loader/fetch/Resource.cpp
@@ -25,9 +25,12 @@
 #include "platform/loader/fetch/Resource.h"
 
 #include <stdint.h>
+
 #include <algorithm>
 #include <cassert>
 #include <memory>
+
+#include "build/build_config.h"
 #include "platform/Histogram.h"
 #include "platform/InstanceCounters.h"
 #include "platform/RuntimeEnabledFeatures.h"
@@ -457,7 +460,7 @@
 
 static double FreshnessLifetime(const ResourceResponse& response,
                                 double response_timestamp) {
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
   // On desktop, local files should be reloaded in case they change.
   if (response.Url().IsLocalFile())
     return 0;
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp
index c825a15e..4e37baa 100644
--- a/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp
+++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceFetcher.cpp
@@ -282,7 +282,7 @@
 ResourceFetcher::ResourceFetcher(FetchContext* new_context,
                                  RefPtr<WebTaskRunner> task_runner)
     : context_(new_context),
-      scheduler_(ResourceLoadScheduler::Create()),
+      scheduler_(ResourceLoadScheduler::Create(&Context())),
       archive_(Context().IsMainFrame() ? nullptr : Context().Archive()),
       resource_timing_report_timer_(
           std::move(task_runner),
@@ -1193,6 +1193,7 @@
 }
 
 void ResourceFetcher::ClearContext() {
+  scheduler_->Shutdown();
   ClearPreloads(ResourceFetcher::kClearAllPreloads);
   context_ = Context().Detach();
 }
@@ -1448,6 +1449,9 @@
 }
 
 void ResourceFetcher::StopFetching() {
+  // TODO(toyoshim): May want to suspend scheduler while canceling loaders so
+  // that the cancellations below do not awake unnecessary scheduling.
+
   HeapVector<Member<ResourceLoader>> loaders_to_cancel;
   for (const auto& loader : non_blocking_loaders_) {
     if (!loader->GetKeepalive())
@@ -1465,6 +1469,8 @@
 }
 
 void ResourceFetcher::SetDefersLoading(bool defers) {
+  // TODO(toyoshim): Let |scheduler_| know |defers| too.
+
   for (const auto& loader : non_blocking_loaders_)
     loader->SetDefersLoading(defers);
   for (const auto& loader : loaders_)
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.cpp
index e065a46..fd923936 100644
--- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.cpp
+++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.cpp
@@ -4,24 +4,68 @@
 
 #include "platform/loader/fetch/ResourceLoadScheduler.h"
 
+#include "platform/RuntimeEnabledFeatures.h"
+
 namespace blink {
 
+namespace {
+
+// TODO(toyoshim): Should be managed via field trial flag.
+constexpr size_t kOutstandingThrottledLimit = 16u;
+
+}  // namespace
+
 constexpr ResourceLoadScheduler::ClientId
     ResourceLoadScheduler::kInvalidClientId;
 
-ResourceLoadScheduler::ResourceLoadScheduler() = default;
+ResourceLoadScheduler::ResourceLoadScheduler(FetchContext* context)
+    : context_(context) {
+  DCHECK(context);
+
+  if (!RuntimeEnabledFeatures::ResourceLoadSchedulerEnabled())
+    return;
+
+  auto* scheduler = context->GetFrameScheduler();
+  if (!scheduler)
+    return;
+
+  is_enabled_ = true;
+  scheduler->AddThrottlingObserver(WebFrameScheduler::ObserverType::kLoader,
+                                   this);
+}
 
 DEFINE_TRACE(ResourceLoadScheduler) {
   visitor->Trace(pending_request_map_);
+  visitor->Trace(context_);
+}
+
+void ResourceLoadScheduler::Shutdown() {
+  // Do nothing if the feature is not enabled, or Shutdown() was already called.
+  if (is_shutdown_)
+    return;
+  is_shutdown_ = true;
+
+  if (!is_enabled_)
+    return;
+  auto* scheduler = context_->GetFrameScheduler();
+  // TODO(toyoshim): Replace SECURITY_CHECK below with DCHECK before the next
+  // branch-cut.
+  SECURITY_CHECK(scheduler);
+  scheduler->RemoveThrottlingObserver(WebFrameScheduler::ObserverType::kLoader,
+                                      this);
 }
 
 void ResourceLoadScheduler::Request(ResourceLoadSchedulerClient* client,
                                     ThrottleOption option,
                                     ResourceLoadScheduler::ClientId* id) {
   *id = GenerateClientId();
+  if (is_shutdown_)
+    return;
 
-  if (option == ThrottleOption::kCanNotBeThrottled)
-    return Run(*id, client);
+  if (!is_enabled_ || option == ThrottleOption::kCanNotBeThrottled) {
+    Run(*id, client);
+    return;
+  }
 
   pending_request_map_.insert(*id, client);
   pending_request_queue_.push_back(*id);
@@ -46,7 +90,7 @@
     pending_request_map_.erase(found);
     // Intentionally does not remove it from |pending_request_queue_|.
 
-    // Didn't any release running request, but the outstanding limit might be
+    // Didn't release any running requests, but the outstanding limit might be
     // changed to allow another request.
     if (option == ReleaseOption::kReleaseAndSchedule)
       MaybeRun();
@@ -56,8 +100,20 @@
 }
 
 void ResourceLoadScheduler::SetOutstandingLimitForTesting(size_t limit) {
-  outstanding_limit_ = limit;
-  MaybeRun();
+  SetOutstandingLimitAndMaybeRun(limit);
+  is_enabled_ = limit != 0u;
+}
+
+void ResourceLoadScheduler::OnThrottlingStateChanged(
+    WebFrameScheduler::ThrottlingState state) {
+  switch (state) {
+    case WebFrameScheduler::ThrottlingState::kThrottled:
+      SetOutstandingLimitAndMaybeRun(kOutstandingThrottledLimit);
+      break;
+    case WebFrameScheduler::ThrottlingState::kNotThrottled:
+      SetOutstandingLimitAndMaybeRun(kOutstandingUnlimited);
+      break;
+  }
 }
 
 ResourceLoadScheduler::ClientId ResourceLoadScheduler::GenerateClientId() {
@@ -67,6 +123,11 @@
 }
 
 void ResourceLoadScheduler::MaybeRun() {
+  // Requests for keep-alive loaders could be remained in the pending queue,
+  // but ignore them once Shutdown() is called.
+  if (is_shutdown_)
+    return;
+
   while (!pending_request_queue_.empty()) {
     if (outstanding_limit_ && running_requests_.size() >= outstanding_limit_)
       return;
@@ -86,4 +147,9 @@
   client->Run();
 }
 
+void ResourceLoadScheduler::SetOutstandingLimitAndMaybeRun(size_t limit) {
+  outstanding_limit_ = limit;
+  MaybeRun();
+}
+
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.h b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.h
index 8668d80..0af4151b 100644
--- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.h
+++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadScheduler.h
@@ -5,8 +5,10 @@
 #ifndef ResourceLoadScheduler_h
 #define ResourceLoadScheduler_h
 
+#include "platform/WebFrameScheduler.h"
 #include "platform/heap/GarbageCollected.h"
 #include "platform/heap/HeapAllocator.h"
+#include "platform/loader/fetch/FetchContext.h"
 #include "platform/loader/fetch/Resource.h"
 #include "platform/wtf/Deque.h"
 #include "platform/wtf/HashSet.h"
@@ -30,7 +32,8 @@
 // them possibly with additional throttling/scheduling. This also keeps track of
 // in-flight requests that are granted but are not released (by Release()) yet.
 class PLATFORM_EXPORT ResourceLoadScheduler final
-    : public GarbageCollectedFinalized<ResourceLoadScheduler> {
+    : public GarbageCollectedFinalized<ResourceLoadScheduler>,
+      public WebFrameScheduler::Observer {
   WTF_MAKE_NONCOPYABLE(ResourceLoadScheduler);
 
  public:
@@ -50,13 +53,24 @@
 
   static constexpr ClientId kInvalidClientId = 0u;
 
-  static ResourceLoadScheduler* Create() { return new ResourceLoadScheduler(); }
+  static constexpr size_t kOutstandingUnlimited = 0u;
+
+  static ResourceLoadScheduler* Create(FetchContext* context = nullptr) {
+    return new ResourceLoadScheduler(context ? context
+                                             : &FetchContext::NullInstance());
+  }
   ~ResourceLoadScheduler() {}
   DECLARE_TRACE();
 
-  // Makes a request. ClientId should be set before Run() is invoked so that
-  // caller can call Release() with the assigned ClientId correctly even if
-  // the invocation happens synchronously.
+  // Stops all operations including observing throttling signals.
+  // ResourceLoadSchedulerClient::Run() will not be called once this method is
+  // called. This method can be called multiple times safely.
+  void Shutdown();
+
+  // Makes a request. This may synchronously call
+  // ResourceLoadSchedulerClient::Run(), but it is guaranteed that ClientId is
+  // populated before ResourceLoadSchedulerClient::Run() is called, so that the
+  // caller can call Release() with the assigned ClientId correctly.
   void Request(ResourceLoadSchedulerClient*, ThrottleOption, ClientId*);
 
   // ResourceLoadSchedulerClient should call this method when the loading is
@@ -64,11 +78,15 @@
   // step, bug the ReleaseOption must be kReleaseOnly in such a case.
   bool Release(ClientId, ReleaseOption);
 
-  // Sets outstanding limit for testing.
+  // Sets outstanding limit for testing. Should be reset with
+  // kOutstandingUnlimited before calling Shutdown().
   void SetOutstandingLimitForTesting(size_t limit);
 
+  // WebFrameScheduler::Observer overrides:
+  void OnThrottlingStateChanged(WebFrameScheduler::ThrottlingState) override;
+
  private:
-  ResourceLoadScheduler();
+  ResourceLoadScheduler(FetchContext*);
 
   // Generates the next ClientId.
   ClientId GenerateClientId();
@@ -79,10 +97,20 @@
   // Grants a client to run,
   void Run(ClientId, ResourceLoadSchedulerClient*);
 
+  void SetOutstandingLimitAndMaybeRun(size_t limit);
+
+  // A flag to indicate an internal running state.
+  // TODO(toyoshim): We may want to use enum once we start to have more states.
+  bool is_shutdown_ = false;
+
+  // A mutable flag to indicate if the throttling and scheduling are enabled.
+  // Can be modified by field trial flags or for testing.
+  bool is_enabled_ = false;
+
   // Outstanding limit. 0u means unlimited.
   // TODO(crbug.com/735410): If this throttling is enabled always, it makes some
   // tests fail.
-  size_t outstanding_limit_ = 0;
+  size_t outstanding_limit_ = kOutstandingUnlimited;
 
   // The last used ClientId to calculate the next.
   ClientId current_id_ = kInvalidClientId;
@@ -94,6 +122,9 @@
   HeapHashMap<ClientId, Member<ResourceLoadSchedulerClient>>
       pending_request_map_;
   Deque<ClientId> pending_request_queue_;
+
+  // Holds FetchContext reference to contact WebFrameScheduler.
+  Member<FetchContext> context_;
 };
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadSchedulerTest.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadSchedulerTest.cpp
index ed0436f..bbfdb30e 100644
--- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadSchedulerTest.cpp
+++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoadSchedulerTest.cpp
@@ -34,6 +34,11 @@
     scheduler_ = ResourceLoadScheduler::Create();
     scheduler()->SetOutstandingLimitForTesting(1);
   }
+  void TearDown() override {
+    scheduler()->SetOutstandingLimitForTesting(
+        ResourceLoadScheduler::kOutstandingUnlimited);
+    scheduler()->Shutdown();
+  }
 
   ResourceLoadScheduler* scheduler() { return scheduler_; }
 
diff --git a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp
index e1e6778..2455733 100644
--- a/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp
+++ b/third_party/WebKit/Source/platform/loader/fetch/ResourceLoader.cpp
@@ -149,9 +149,10 @@
 }
 
 void ResourceLoader::SetDefersLoading(bool defers) {
-  DCHECK(loader_);
-
-  loader_->SetDefersLoading(defers);
+  // TODO(toyoshim): Might be called before creating |loader_| if the request
+  // is throttled.
+  if (loader_)
+    loader_->SetDefersLoading(defers);
 }
 
 void ResourceLoader::DidChangePriority(ResourceLoadPriority load_priority,
diff --git a/third_party/WebKit/Source/platform/mhtml/MHTMLArchive.cpp b/third_party/WebKit/Source/platform/mhtml/MHTMLArchive.cpp
index dcf79ee..9a03d64 100644
--- a/third_party/WebKit/Source/platform/mhtml/MHTMLArchive.cpp
+++ b/third_party/WebKit/Source/platform/mhtml/MHTMLArchive.cpp
@@ -30,6 +30,7 @@
 
 #include "platform/mhtml/MHTMLArchive.h"
 
+#include "build/build_config.h"
 #include "platform/DateComponents.h"
 #include "platform/SerializedResource.h"
 #include "platform/SharedBuffer.h"
@@ -118,7 +119,7 @@
     return true;
   if (url.ProtocolIsInHTTPFamily())
     return true;
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   if (url.ProtocolIs("content"))
     return true;
 #endif
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc
index 9f462b75..c0dcae2 100644
--- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc
+++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl.cc
@@ -1144,6 +1144,9 @@
       break;
 
     case UseCase::NONE:
+      new_policy.compositor_queue_policy.priority =
+          main_thread_compositing_is_fast ? TaskQueue::HIGH_PRIORITY
+                                          : TaskQueue::NORMAL_PRIORITY;
       // It's only safe to block tasks that if we are expecting a compositor
       // driven gesture.
       if (touchstart_expected_soon &&
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc
index 3ef917d..9ac4a702 100644
--- a/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc
+++ b/third_party/WebKit/Source/platform/scheduler/renderer/renderer_scheduler_impl_unittest.cc
@@ -854,9 +854,9 @@
   EnableIdleTasks();
   RunUntilIdle();
   EXPECT_THAT(run_order,
-              testing::ElementsAre(std::string("L1"), std::string("D1"),
-                                   std::string("C1"), std::string("D2"),
-                                   std::string("C2"), std::string("I1")));
+              testing::ElementsAre(std::string("C1"), std::string("C2"),
+                                   std::string("L1"), std::string("D1"),
+                                   std::string("D2"), std::string("I1")));
   EXPECT_EQ(RendererSchedulerImpl::UseCase::NONE, CurrentUseCase());
 }
 
@@ -2427,7 +2427,7 @@
   EnableIdleTasks();
   RunUntilIdle();
   EXPECT_THAT(run_order,
-              testing::ElementsAre(std::string("D1"), std::string("C1"),
+              testing::ElementsAre(std::string("C1"), std::string("D1"),
                                    std::string("I1")));
 
   // The rest queued tasks fire when the tab goes foregrounded.
@@ -2459,7 +2459,7 @@
   EnableIdleTasks();
   RunUntilIdle();
   EXPECT_THAT(run_order,
-              testing::ElementsAre(std::string("D1"), std::string("C1"),
+              testing::ElementsAre(std::string("C1"), std::string("D1"),
                                    std::string("I1")));
 
   // The rest queued tasks fire when the renderer is resumed.
@@ -2477,7 +2477,7 @@
   EnableIdleTasks();
   RunUntilIdle();
   EXPECT_THAT(run_order,
-              testing::ElementsAre(std::string("D2"), std::string("C2"),
+              testing::ElementsAre(std::string("C2"), std::string("D2"),
                                    std::string("I2")));
 
   // The rest queued tasks fire when the renderer is resumed.
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp b/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp
index 0eb408c2..fa3815f7 100644
--- a/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp
+++ b/third_party/WebKit/Source/platform/scroll/ScrollableArea.cpp
@@ -31,6 +31,7 @@
 
 #include "platform/scroll/ScrollableArea.h"
 
+#include "build/build_config.h"
 #include "platform/PlatformChromeClient.h"
 #include "platform/graphics/GraphicsLayer.h"
 #include "platform/instrumentation/tracing/TraceEvent.h"
@@ -74,7 +75,7 @@
 ScrollableArea::~ScrollableArea() {}
 
 void ScrollableArea::ClearScrollableArea() {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   if (scroll_animator_)
     scroll_animator_->Dispose();
 #endif
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarTheme.cpp b/third_party/WebKit/Source/platform/scroll/ScrollbarTheme.cpp
index 9ead770..2a5c60b 100644
--- a/third_party/WebKit/Source/platform/scroll/ScrollbarTheme.cpp
+++ b/third_party/WebKit/Source/platform/scroll/ScrollbarTheme.cpp
@@ -25,6 +25,7 @@
 
 #include "platform/scroll/ScrollbarTheme.h"
 
+#include "build/build_config.h"
 #include "platform/RuntimeEnabledFeatures.h"
 #include "platform/graphics/Color.h"
 #include "platform/graphics/GraphicsContext.h"
@@ -44,7 +45,7 @@
 #include "public/platform/WebRect.h"
 #include "public/platform/WebScrollbarBehavior.h"
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 #include "public/platform/WebThemeEngine.h"
 #endif
 
@@ -212,7 +213,7 @@
 
   DrawingRecorder recorder(context, display_item_client,
                            DisplayItem::kScrollbarCorner, corner_rect);
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   context.FillRect(corner_rect, Color::kWhite);
 #else
   Platform::Current()->ThemeEngine()->Paint(
@@ -232,7 +233,7 @@
                                     const Scrollbar& scrollbar,
                                     const IntRect& rect) {
 // Android paints tickmarks in the browser at FindResultBar.java.
-#if !OS(ANDROID)
+#if !defined(OS_ANDROID)
   if (scrollbar.Orientation() != kVerticalScrollbar)
     return;
 
diff --git a/third_party/WebKit/Source/platform/testing/BlinkPerfTestSuite.cpp b/third_party/WebKit/Source/platform/testing/BlinkPerfTestSuite.cpp
index 5e31b63..6b7ab85 100644
--- a/third_party/WebKit/Source/platform/testing/BlinkPerfTestSuite.cpp
+++ b/third_party/WebKit/Source/platform/testing/BlinkPerfTestSuite.cpp
@@ -11,6 +11,7 @@
 #include "base/process/launch.h"
 #include "base/strings/string_util.h"
 #include "base/test/perf_log.h"
+#include "build/build_config.h"
 #include "platform/wtf/WTF.h"
 #include "platform/wtf/allocator/Partitions.h"
 #include "testing/gtest/include/gtest/gtest.h"
@@ -30,7 +31,7 @@
       base::CommandLine::ForCurrentProcess()->GetSwitchValuePath("log-file");
   if (log_path.empty()) {
     base::PathService::Get(base::FILE_EXE, &log_path);
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
     base::FilePath tmp_dir;
     base::PathService::Get(base::DIR_CACHE, &tmp_dir);
     log_path = tmp_dir.Append(log_path.BaseName());
diff --git a/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.cpp b/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.cpp
index 6e8dc90..90e3280 100644
--- a/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.cpp
+++ b/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.cpp
@@ -147,38 +147,33 @@
 }
 
 void WebLayerTreeViewImplForTesting::RegisterViewportLayers(
-    const blink::WebLayer* overscroll_elasticity_layer,
-    const blink::WebLayer* page_scale_layer,
-    const blink::WebLayer* inner_viewport_container_layer,
-    const blink::WebLayer* outer_viewport_container_layer,
-    const blink::WebLayer* inner_viewport_scroll_layer,
-    const blink::WebLayer* outer_viewport_scroll_layer) {
+    const WebLayerTreeView::ViewportLayers& layers) {
   cc::LayerTreeHost::ViewportLayers viewport_layers;
-  if (overscroll_elasticity_layer) {
+  if (layers.overscroll_elasticity) {
     viewport_layers.overscroll_elasticity =
-        static_cast<const cc_blink::WebLayerImpl*>(overscroll_elasticity_layer)
+        static_cast<const cc_blink::WebLayerImpl*>(layers.overscroll_elasticity)
             ->layer();
   }
   viewport_layers.page_scale =
-      static_cast<const cc_blink::WebLayerImpl*>(page_scale_layer)->layer();
-  if (inner_viewport_container_layer) {
+      static_cast<const cc_blink::WebLayerImpl*>(layers.page_scale)->layer();
+  if (layers.inner_viewport_container) {
     viewport_layers.inner_viewport_container =
         static_cast<const cc_blink::WebLayerImpl*>(
-            inner_viewport_container_layer)
+            layers.inner_viewport_container)
             ->layer();
   }
-  if (outer_viewport_container_layer) {
+  if (layers.outer_viewport_container) {
     viewport_layers.outer_viewport_container =
         static_cast<const cc_blink::WebLayerImpl*>(
-            outer_viewport_container_layer)
+            layers.outer_viewport_container)
             ->layer();
   }
   viewport_layers.inner_viewport_scroll =
-      static_cast<const cc_blink::WebLayerImpl*>(inner_viewport_scroll_layer)
+      static_cast<const cc_blink::WebLayerImpl*>(layers.inner_viewport_scroll)
           ->layer();
-  if (outer_viewport_scroll_layer) {
+  if (layers.outer_viewport_scroll) {
     viewport_layers.outer_viewport_scroll =
-        static_cast<const cc_blink::WebLayerImpl*>(outer_viewport_scroll_layer)
+        static_cast<const cc_blink::WebLayerImpl*>(layers.outer_viewport_scroll)
             ->layer();
   }
   layer_tree_host_->RegisterViewportLayers(viewport_layers);
diff --git a/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h b/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h
index ddf923b..31c916e 100644
--- a/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h
+++ b/third_party/WebKit/Source/platform/testing/WebLayerTreeViewImplForTesting.h
@@ -58,14 +58,7 @@
   void SetNeedsBeginFrame() override;
   void DidStopFlinging() override;
   void SetDeferCommits(bool) override;
-  // TODO(pdr): Refactor to use a struct like LayerTreeHost::ViewportLayers.
-  void RegisterViewportLayers(
-      const blink::WebLayer* overscroll_elasticity_layer,
-      const blink::WebLayer* page_scale_layer_layer,
-      const blink::WebLayer* inner_viewport_container_layer,
-      const blink::WebLayer* outer_viewport_container_layer,
-      const blink::WebLayer* inner_viewport_scroll_layer,
-      const blink::WebLayer* outer_viewport_scroll_layer) override;
+  void RegisterViewportLayers(const WebLayerTreeView::ViewportLayers&) override;
   void ClearViewportLayers() override;
   void RegisterSelection(const blink::WebSelection&) override;
   void ClearSelection() override;
diff --git a/third_party/WebKit/Source/platform/text/HyphenationTest.cpp b/third_party/WebKit/Source/platform/text/HyphenationTest.cpp
index 533c8e6..3f9071a 100644
--- a/third_party/WebKit/Source/platform/text/HyphenationTest.cpp
+++ b/third_party/WebKit/Source/platform/text/HyphenationTest.cpp
@@ -4,10 +4,11 @@
 
 #include "platform/text/Hyphenation.h"
 
+#include "build/build_config.h"
 #include "platform/LayoutLocale.h"
 #include "testing/gtest/include/gtest/gtest.h"
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #include "base/files/file_path.h"
 #include "platform/text/hyphenation/HyphenationMinikin.h"
 #endif
@@ -33,9 +34,9 @@
   LayoutLocale::ClearForTesting();
 }
 
-#if OS(ANDROID) || OS(MACOSX)
+#if defined(OS_ANDROID) || defined(OS_MACOSX)
 TEST(HyphenationTest, LastHyphenLocation) {
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   // Because the mojo service to open hyphenation dictionaries is not accessible
   // from the unit test, open the dictionary file directly for testing.
   base::FilePath path("/system/usr/hyphen-data/hyph-en-us.hyb");
diff --git a/third_party/WebKit/Source/platform/text/LineEnding.cpp b/third_party/WebKit/Source/platform/text/LineEnding.cpp
index 766b2f2..2f4a46d9 100644
--- a/third_party/WebKit/Source/platform/text/LineEnding.cpp
+++ b/third_party/WebKit/Source/platform/text/LineEnding.cpp
@@ -31,6 +31,7 @@
 
 #include "platform/text/LineEnding.h"
 
+#include "build/build_config.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Noncopyable.h"
 #include "platform/wtf/text/CString.h"
@@ -202,7 +203,7 @@
 }
 
 void NormalizeLineEndingsToNative(const CString& from, Vector<char>& result) {
-#if OS(WIN)
+#if defined(OS_WIN)
   VectorCharAppendBuffer buffer(result);
   InternalNormalizeLineEndingsToCRLF(from, buffer);
 #else
diff --git a/third_party/WebKit/Source/platform/text/WritingModeUtils.h b/third_party/WebKit/Source/platform/text/WritingModeUtils.h
index 03fcf20..f4d680e 100644
--- a/third_party/WebKit/Source/platform/text/WritingModeUtils.h
+++ b/third_party/WebKit/Source/platform/text/WritingModeUtils.h
@@ -11,43 +11,17 @@
 
 namespace blink {
 
-// Templates to map values between logical orientations and physical
-// orientations. See https://www.w3.org/TR/css-writing-modes-3/ and
-// https://www.w3.org/TR/css-logical-1/ for definitions of logical orientations.
-
-// This file provides two types of templates:
-//
-// - Simple value mappers (PhysicalToLogical and LogicalToPhysical): they take
-//   4 input values in physical or logical orientations, and provide accessors
-//   to get values in logical or physical orientations. As the inputs may be
-//   evaluated even if not used (in case that the compiler is unable to remove
-//   unused evaluations, e.g. containing non-inlined function calls), for
-//   performance-senstive code, the evaluation of the inputs should be simple
-//   and/or be fully inlined.
-//
-// - Value mappers based on getter/setter methods (PhysicalToLogicalGetter,
-//   LogicalToPhysicalGetter, PhysicalToLogicalSetter and
-//   LogicalToPhysicalSetter): they take 4 method pointers as inputs pointing to
-//   methods accessing values in physical or logical orientations, and provide
-//   accessors to get or set values in logical or physical orientations. They
-//   are suitable for mapping of setters, or getters implemented with non-
-//   inlined functions. Evaluation of the input values are delayed when they are
-//   actually needed.
-//
-// See WritingModeUtilsTest.cpp, LayoutBoxModelObject.h and ComputedStyle.h for
-// examples.
-
-template <typename Value>
+template <typename T>
 class PhysicalToLogical {
   STACK_ALLOCATED();
 
  public:
   PhysicalToLogical(WritingMode writing_mode,
                     TextDirection direction,
-                    Value top,
-                    Value right,
-                    Value bottom,
-                    Value left)
+                    T top,
+                    T right,
+                    T bottom,
+                    T left)
       : writing_mode_(writing_mode),
         direction_(direction),
         top_(top),
@@ -55,72 +29,72 @@
         bottom_(bottom),
         left_(left) {}
 
-  Value InlineStart() const {
+  T InlineStart() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return IsLtr(direction_) ? left_ : right_;
     return IsLtr(direction_) ? top_ : bottom_;
   }
 
-  Value InlineEnd() const {
+  T InlineEnd() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return IsLtr(direction_) ? right_ : left_;
     return IsLtr(direction_) ? bottom_ : top_;
   }
 
-  Value BlockStart() const {
+  T BlockStart() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return top_;
     return IsFlippedBlocksWritingMode(writing_mode_) ? right_ : left_;
   }
 
-  Value BlockEnd() const {
+  T BlockEnd() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return bottom_;
     return IsFlippedBlocksWritingMode(writing_mode_) ? left_ : right_;
   }
 
-  Value Over() const {
+  T Over() const {
     return IsHorizontalWritingMode(writing_mode_) ? top_ : right_;
   }
 
-  Value Under() const {
+  T Under() const {
     return IsHorizontalWritingMode(writing_mode_) ? bottom_ : left_;
   }
 
-  Value LineLeft() const {
+  T LineLeft() const {
     return IsHorizontalWritingMode(writing_mode_) ? left_ : top_;
   }
 
-  Value LineRight() const {
+  T LineRight() const {
     return IsHorizontalWritingMode(writing_mode_) ? right_ : bottom_;
   }
 
   // Legacy logical directions.
-  Value Start() const { return InlineStart(); }
-  Value End() const { return InlineEnd(); }
-  Value Before() const { return BlockStart(); }
-  Value After() const { return BlockEnd(); }
+  T Start() const { return InlineStart(); }
+  T End() const { return InlineEnd(); }
+  T Before() const { return BlockStart(); }
+  T After() const { return BlockEnd(); }
 
  private:
   WritingMode writing_mode_;
   TextDirection direction_;
-  Value top_;
-  Value right_;
-  Value bottom_;
-  Value left_;
+  T top_;
+  T right_;
+  T bottom_;
+  T left_;
 };
 
-template <typename Value>
+template <typename T>
 class LogicalToPhysical {
   STACK_ALLOCATED();
 
  public:
   LogicalToPhysical(WritingMode writing_mode,
                     TextDirection direction,
-                    Value inline_start,
-                    Value inline_end,
-                    Value block_start,
-                    Value block_end)
+                    T inline_start,
+                    T inline_end,
+                    T block_start,
+                    T block_end)
       : writing_mode_(writing_mode),
         direction_(direction),
         inline_start_(inline_start),
@@ -128,27 +102,27 @@
         block_start_(block_start),
         block_end_(block_end) {}
 
-  Value Left() const {
+  T Left() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return IsLtr(direction_) ? inline_start_ : inline_end_;
     return IsFlippedBlocksWritingMode(writing_mode_) ? block_end_
                                                      : block_start_;
   }
 
-  Value Right() const {
+  T Right() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return IsLtr(direction_) ? inline_end_ : inline_start_;
     return IsFlippedBlocksWritingMode(writing_mode_) ? block_start_
                                                      : block_end_;
   }
 
-  Value Top() const {
+  T Top() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return block_start_;
     return IsLtr(direction_) ? inline_start_ : inline_end_;
   }
 
-  Value Bottom() const {
+  T Bottom() const {
     if (IsHorizontalWritingMode(writing_mode_))
       return block_end_;
     return IsLtr(direction_) ? inline_end_ : inline_start_;
@@ -157,154 +131,10 @@
  private:
   WritingMode writing_mode_;
   TextDirection direction_;
-  Value inline_start_;  // a.k.a. start
-  Value inline_end_;    // a.k.a. end
-  Value block_start_;   // a.k.a. before
-  Value block_end_;     // a.k.a. after
-};
-
-template <typename Value, typename Object>
-class LogicalToPhysicalGetter {
-  STACK_ALLOCATED();
-
- public:
-  using Getter = Value (Object::*)() const;
-  LogicalToPhysicalGetter(WritingMode writing_mode,
-                          TextDirection direction,
-                          const Object& object,
-                          Getter inline_start_getter,
-                          Getter inline_end_getter,
-                          Getter block_start_getter,
-                          Getter block_end_getter)
-      : object_(object),
-        converter_(writing_mode,
-                   direction,
-                   inline_start_getter,
-                   inline_end_getter,
-                   block_start_getter,
-                   block_end_getter) {}
-
-  Value Left() const { return (object_.*converter_.Left())(); }
-  Value Right() const { return (object_.*converter_.Right())(); }
-  Value Top() const { return (object_.*converter_.Top())(); }
-  Value Bottom() const { return (object_.*converter_.Bottom())(); }
-
- private:
-  const Object& object_;
-  LogicalToPhysical<Getter> converter_;
-};
-
-template <typename Value, typename Object>
-class PhysicalToLogicalGetter {
-  STACK_ALLOCATED();
-
- public:
-  using Getter = Value (Object::*)() const;
-  PhysicalToLogicalGetter(WritingMode writing_mode,
-                          TextDirection direction,
-                          const Object& object,
-                          Getter top_getter,
-                          Getter right_getter,
-                          Getter bottom_getter,
-                          Getter left_getter)
-      : object_(object),
-        converter_(writing_mode,
-                   direction,
-                   top_getter,
-                   right_getter,
-                   bottom_getter,
-                   left_getter) {}
-
-  Value InlineStart() const { return (object_.*converter_.InlineStart())(); }
-  Value InlineEnd() const { return (object_.*converter_.InlineEnd())(); }
-  Value BlockStart() const { return (object_.*converter_.BlockStart())(); }
-  Value BlockEnd() const { return (object_.*converter_.BlockEnd())(); }
-  Value Over() const { return (object_.*converter_.Over())(); }
-  Value Under() const { return (object_.*converter_.Under())(); }
-  Value LineLeft() const { return (object_.*converter_.LineLeft())(); }
-  Value LineRight() const { return (object_.*converter_.LineRight())(); }
-  Value Start() const { return (object_.*converter_.Start())(); }
-  Value End() const { return (object_.*converter_.End())(); }
-  Value Before() const { return (object_.*converter_.Before())(); }
-  Value After() const { return (object_.*converter_.After())(); }
-
- private:
-  const Object& object_;
-  PhysicalToLogical<Getter> converter_;
-};
-
-template <typename Value, typename Object>
-class PhysicalToLogicalSetter {
-  STACK_ALLOCATED();
-
- public:
-  using Setter = void (Object::*)(Value);
-  PhysicalToLogicalSetter(WritingMode writing_mode,
-                          TextDirection direction,
-                          Object& object,
-                          Setter inline_start_setter,
-                          Setter inline_end_setter,
-                          Setter block_start_setter,
-                          Setter block_end_setter)
-      : object_(object),
-        converter_(writing_mode,
-                   direction,
-                   inline_start_setter,
-                   inline_end_setter,
-                   block_start_setter,
-                   block_end_setter) {}
-
-  void SetLeft(Value v) { (object_.*converter_.Left())(v); }
-  void SetRight(Value v) { (object_.*converter_.Right())(v); }
-  void SetTop(Value v) { (object_.*converter_.Top())(v); }
-  void SetBottom(Value v) { (object_.*converter_.Bottom())(v); }
-
- private:
-  Object& object_;
-  // This converter converts logical setters to physical setters which accept
-  // physical values and call the logical setters to set logical values.
-  LogicalToPhysical<Setter> converter_;
-};
-
-template <typename Value, typename Object>
-class LogicalToPhysicalSetter {
-  STACK_ALLOCATED();
-
- public:
-  using Setter = void (Object::*)(Value);
-  LogicalToPhysicalSetter(WritingMode writing_mode,
-                          TextDirection direction,
-                          Object& object,
-                          Setter top_setter,
-                          Setter right_setter,
-                          Setter bottom_setter,
-                          Setter left_setter)
-      : object_(object),
-        converter_(writing_mode,
-                   direction,
-                   top_setter,
-                   right_setter,
-                   bottom_setter,
-                   left_setter) {}
-
-  void SetInlineStart(Value v) { (object_.*converter_.InlineStart())(v); }
-  void SetInlineEnd(Value v) { (object_.*converter_.InlineEnd())(v); }
-  void SetBlockStart(Value v) { (object_.*converter_.BlockStart())(v); }
-  void SetBlockEnd(Value v) { (object_.*converter_.BlockEnd())(v); }
-  void SetOver(Value v) { (object_.*converter_.Over())(v); }
-  void SetUnder(Value v) { (object_.*converter_.Under())(v); }
-  void SetLineLeft(Value v) { (object_.*converter_.LineLeft())(v); }
-  void SetLineRight(Value v) { (object_.*converter_.LineRight())(v); }
-  void SetStart(Value v) { (object_.*converter_.Start())(v); }
-  void SetEnd(Value v) { (object_.*converter_.End())(v); }
-  void SetBefore(Value v) { (object_.*converter_.Before())(v); }
-  void SetAfter(Value v) { (object_.*converter_.After())(v); }
-
- private:
-  Object& object_;
-  // This converter converts physical setters to logical setters which accept
-  // logical values and call the physical setters to set physical values.
-  PhysicalToLogical<Setter> converter_;
+  T inline_start_;  // a.k.a. start
+  T inline_end_;    // a.k.a. end
+  T block_start_;   // a.k.a. before
+  T block_end_;     // a.k.a. after
 };
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/text/WritingModeUtilsTest.cpp b/third_party/WebKit/Source/platform/text/WritingModeUtilsTest.cpp
index 917a31c7..6683fefc 100644
--- a/third_party/WebKit/Source/platform/text/WritingModeUtilsTest.cpp
+++ b/third_party/WebKit/Source/platform/text/WritingModeUtilsTest.cpp
@@ -12,8 +12,7 @@
 
 enum { kTop, kRight, kBottom, kLeft };
 
-template <typename PhysicalToLogicalConverter>
-void CheckLegacyLogicalDirections(const PhysicalToLogicalConverter& converter) {
+void CheckLegacyLogicalDirections(PhysicalToLogical<int> converter) {
   EXPECT_EQ(converter.InlineStart(), converter.Start());
   EXPECT_EQ(converter.InlineEnd(), converter.End());
   EXPECT_EQ(converter.BlockStart(), converter.Before());
@@ -110,7 +109,7 @@
   CheckLegacyLogicalDirections(converter);
 }
 
-enum { kInlineStart = 1000, kInlineEnd, kBlockStart, kBlockEnd };
+enum { kInlineStart, kInlineEnd, kBlockStart, kBlockEnd };
 
 TEST(WritingModeUtilsTest, LogicalToPhysicalHorizontalLtr) {
   LogicalToPhysical<int> converter(WritingMode::kHorizontalTb,
@@ -172,127 +171,6 @@
   EXPECT_EQ(kInlineStart, converter.Bottom());
 }
 
-class PhysicalValues {
- public:
-  int Top() const { return top_; }
-  int Right() const { return right_; }
-  int Bottom() const { return bottom_; }
-  int Left() const { return left_; }
-  void SetTop(int top) { top_ = top; }
-  void SetRight(int right) { right_ = right; }
-  void SetBottom(int bottom) { bottom_ = bottom; }
-  void SetLeft(int left) { left_ = left; }
-
- private:
-  int top_ = kTop;
-  int right_ = kRight;
-  int bottom_ = kBottom;
-  int left_ = kLeft;
-};
-
-TEST(WritingModeUtilsTest, PhysicalToLogicalGetter) {
-  PhysicalValues physical_values;
-  PhysicalToLogicalGetter<int, PhysicalValues> getter(
-      WritingMode::kVerticalRl, TextDirection::kRtl, physical_values,
-      &PhysicalValues::Top, &PhysicalValues::Right, &PhysicalValues::Bottom,
-      &PhysicalValues::Left);
-
-  EXPECT_EQ(kBottom, getter.InlineStart());
-  EXPECT_EQ(kTop, getter.InlineEnd());
-  EXPECT_EQ(kRight, getter.BlockStart());
-  EXPECT_EQ(kLeft, getter.BlockEnd());
-  EXPECT_EQ(kTop, getter.LineLeft());
-  EXPECT_EQ(kBottom, getter.LineRight());
-  EXPECT_EQ(kRight, getter.Over());
-  EXPECT_EQ(kLeft, getter.Under());
-  CheckLegacyLogicalDirections(getter);
-}
-
-TEST(WritingModeUtilsTest, LogicalToPhysicalSetter) {
-  PhysicalValues physical_values;
-  LogicalToPhysicalSetter<int, PhysicalValues> setter(
-      WritingMode::kVerticalRl, TextDirection::kRtl, physical_values,
-      &PhysicalValues::SetTop, &PhysicalValues::SetRight,
-      &PhysicalValues::SetBottom, &PhysicalValues::SetLeft);
-  setter.SetInlineStart(kInlineStart);
-  setter.SetInlineEnd(kInlineEnd);
-  setter.SetBlockStart(kBlockStart);
-  setter.SetBlockEnd(kBlockEnd);
-
-  EXPECT_EQ(kBlockEnd, physical_values.Left());
-  EXPECT_EQ(kBlockStart, physical_values.Right());
-  EXPECT_EQ(kInlineEnd, physical_values.Top());
-  EXPECT_EQ(kInlineStart, physical_values.Bottom());
-
-  setter.SetStart(kInlineStart);
-  setter.SetEnd(kInlineEnd);
-  setter.SetBefore(kBlockStart);
-  setter.SetAfter(kBlockEnd);
-
-  EXPECT_EQ(kBlockEnd, physical_values.Left());
-  EXPECT_EQ(kBlockStart, physical_values.Right());
-  EXPECT_EQ(kInlineEnd, physical_values.Top());
-  EXPECT_EQ(kInlineStart, physical_values.Bottom());
-
-  setter.SetLineRight(kInlineStart);
-  setter.SetLineLeft(kInlineEnd);
-  setter.SetOver(kBlockStart);
-  setter.SetUnder(kBlockEnd);
-
-  EXPECT_EQ(kBlockEnd, physical_values.Left());
-  EXPECT_EQ(kBlockStart, physical_values.Right());
-  EXPECT_EQ(kInlineEnd, physical_values.Top());
-  EXPECT_EQ(kInlineStart, physical_values.Bottom());
-}
-
-class LogicalValues {
- public:
-  int InlineStart() const { return inline_start_; }
-  int InlineEnd() const { return inline_end_; }
-  int BlockStart() const { return block_start_; }
-  int BlockEnd() const { return block_end_; }
-  void SetInlineStart(int inline_start) { inline_start_ = inline_start; }
-  void SetInlineEnd(int inline_end) { inline_end_ = inline_end; }
-  void SetBlockStart(int block_start) { block_start_ = block_start; }
-  void SetBlockEnd(int block_end) { block_end_ = block_end; }
-
- private:
-  int inline_start_ = kInlineStart;
-  int inline_end_ = kInlineEnd;
-  int block_start_ = kBlockStart;
-  int block_end_ = kBlockEnd;
-};
-
-TEST(WritingModeUtilsTest, LogicalToPhysicalGetter) {
-  LogicalValues logical_values;
-  LogicalToPhysicalGetter<int, LogicalValues> getter(
-      WritingMode::kVerticalRl, TextDirection::kRtl, logical_values,
-      &LogicalValues::InlineStart, &LogicalValues::InlineEnd,
-      &LogicalValues::BlockStart, &LogicalValues::BlockEnd);
-
-  EXPECT_EQ(kBlockEnd, getter.Left());
-  EXPECT_EQ(kBlockStart, getter.Right());
-  EXPECT_EQ(kInlineEnd, getter.Top());
-  EXPECT_EQ(kInlineStart, getter.Bottom());
-}
-
-TEST(WritingModeUtilsTest, PhysicalToLogicalSetter) {
-  LogicalValues logical_values;
-  PhysicalToLogicalSetter<int, LogicalValues> setter(
-      WritingMode::kVerticalRl, TextDirection::kRtl, logical_values,
-      &LogicalValues::SetInlineStart, &LogicalValues::SetInlineEnd,
-      &LogicalValues::SetBlockStart, &LogicalValues::SetBlockEnd);
-  setter.SetTop(kTop);
-  setter.SetRight(kRight);
-  setter.SetBottom(kBottom);
-  setter.SetLeft(kLeft);
-
-  EXPECT_EQ(kBottom, logical_values.InlineStart());
-  EXPECT_EQ(kTop, logical_values.InlineEnd());
-  EXPECT_EQ(kRight, logical_values.BlockStart());
-  EXPECT_EQ(kLeft, logical_values.BlockEnd());
-}
-
 }  // namespace
 
 }  // namespace blink
diff --git a/third_party/WebKit/Source/platform/wtf/Assertions.cpp b/third_party/WebKit/Source/platform/wtf/Assertions.cpp
index 7585960c5..8b8eb859 100644
--- a/third_party/WebKit/Source/platform/wtf/Assertions.cpp
+++ b/third_party/WebKit/Source/platform/wtf/Assertions.cpp
@@ -44,42 +44,42 @@
 #include "platform/wtf/ThreadSpecific.h"
 #include "platform/wtf/Threading.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include <AvailabilityMacros.h>
 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
 #define WTF_USE_APPLE_SYSTEM_LOG 1
 #include <asl.h>
 #endif
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
 
 #if defined(COMPILER_MSVC)
 #include <crtdbg.h>
 #endif
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
 #endif
 
-#if OS(MACOSX) || (OS(LINUX) && !defined(__UCLIBC__))
+#if defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(__UCLIBC__))
 #include <cxxabi.h>
 #include <dlfcn.h>
 #include <execinfo.h>
 #endif
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #include <android/log.h>
 #endif
 
 PRINTF_FORMAT(1, 0)
 static void vprintf_stderr_common(const char* format, va_list args) {
-#if OS(MACOSX) && USE(APPLE_SYSTEM_LOG)
+#if defined(OS_MACOSX) && USE(APPLE_SYSTEM_LOG)
   va_list copyOfArgs;
   va_copy(copyOfArgs, args);
   asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs);
   va_end(copyOfArgs);
-#elif OS(ANDROID)
+#elif defined(OS_ANDROID)
   __android_log_vprint(ANDROID_LOG_WARN, "WebKit", format, args);
-#elif OS(WIN)
+#elif defined(OS_WIN)
   if (IsDebuggerPresent()) {
     size_t size = 1024;
 
diff --git a/third_party/WebKit/Source/platform/wtf/Assertions.h b/third_party/WebKit/Source/platform/wtf/Assertions.h
index aed8561..a17cdd65 100644
--- a/third_party/WebKit/Source/platform/wtf/Assertions.h
+++ b/third_party/WebKit/Source/platform/wtf/Assertions.h
@@ -31,15 +31,17 @@
 // Objective C++.
 
 #include <stdarg.h>
+
 #include "base/allocator/partition_allocator/oom.h"
 #include "base/gtest_prod_util.h"
 #include "base/logging.h"
+#include "build/build_config.h"
 #include "platform/wtf/Compiler.h"
 #include "platform/wtf/Noncopyable.h"
 #include "platform/wtf/WTFExport.h"
 #include "platform/wtf/build_config.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
 #endif
 
diff --git a/third_party/WebKit/Source/platform/wtf/ByteOrder.h b/third_party/WebKit/Source/platform/wtf/ByteOrder.h
index e2f3b10..b77e441 100644
--- a/third_party/WebKit/Source/platform/wtf/ByteOrder.h
+++ b/third_party/WebKit/Source/platform/wtf/ByteOrder.h
@@ -34,11 +34,11 @@
 #include "build/build_config.h"
 #include "platform/wtf/build_config.h"
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
 #include <arpa/inet.h>
 #endif
 
-#if OS(WIN)
+#if defined(OS_WIN)
 
 #include "platform/wtf/ByteSwap.h"
 
@@ -70,6 +70,6 @@
 }
 #endif
 
-#endif  // OS(WIN)
+#endif  // defined(OS_WIN)
 
 #endif  // WTF_ByteOrder_h
diff --git a/third_party/WebKit/Source/platform/wtf/DataLog.cpp b/third_party/WebKit/Source/platform/wtf/DataLog.cpp
index 41c5c9b1..3914c59 100644
--- a/third_party/WebKit/Source/platform/wtf/DataLog.cpp
+++ b/third_party/WebKit/Source/platform/wtf/DataLog.cpp
@@ -25,7 +25,9 @@
 
 #include "platform/wtf/DataLog.h"
 
-#if OS(POSIX)
+#include "build/build_config.h"
+
+#if defined(OS_POSIX)
 #include <pthread.h>
 #include <unistd.h>
 #endif
@@ -42,7 +44,7 @@
 
 namespace WTF {
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
 static pthread_once_t g_initialize_log_file_once_key = PTHREAD_ONCE_INIT;
 #endif
 
@@ -76,7 +78,7 @@
 }
 
 static void InitializeLogFile() {
-#if OS(POSIX)
+#if defined(OS_POSIX)
   pthread_once(&g_initialize_log_file_once_key, InitializeLogFileOnce);
 #else
   if (!g_file)
diff --git a/third_party/WebKit/Source/platform/wtf/DateMath.cpp b/third_party/WebKit/Source/platform/wtf/DateMath.cpp
index 04ef8914..28dbdc4 100644
--- a/third_party/WebKit/Source/platform/wtf/DateMath.cpp
+++ b/third_party/WebKit/Source/platform/wtf/DateMath.cpp
@@ -86,7 +86,7 @@
 #include "platform/wtf/StringExtras.h"
 #include "platform/wtf/text/StringBuilder.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
 #else
 #include <sys/time.h>
@@ -334,7 +334,7 @@
 }
 
 static double CalculateUTCOffset() {
-#if OS(WIN)
+#if defined(OS_WIN)
   TIME_ZONE_INFORMATION time_zone_information;
   GetTimeZoneInformation(&time_zone_information);
   int32_t bias =
@@ -422,7 +422,7 @@
 // We follow the recommendation of RFC 2822 to consider all
 // obsolete time zones not listed here equivalent to "-0000".
 static const struct KnownZone {
-#if !OS(WIN)
+#if !defined(OS_WIN)
   const
 #endif
       char tz_name[4];
diff --git a/third_party/WebKit/Source/platform/wtf/MathExtras.h b/third_party/WebKit/Source/platform/wtf/MathExtras.h
index d6e117eb..9614d0c 100644
--- a/third_party/WebKit/Source/platform/wtf/MathExtras.h
+++ b/third_party/WebKit/Source/platform/wtf/MathExtras.h
@@ -43,7 +43,7 @@
 #include <stdint.h>
 #endif
 
-#if OS(OPENBSD)
+#if defined(OS_OPENBSD)
 #include <machine/ieee.h>
 #include <sys/types.h>
 #endif
diff --git a/third_party/WebKit/Source/platform/wtf/README.md b/third_party/WebKit/Source/platform/wtf/README.md
index 7c73693..1e15098 100644
--- a/third_party/WebKit/Source/platform/wtf/README.md
+++ b/third_party/WebKit/Source/platform/wtf/README.md
@@ -66,7 +66,7 @@
 
   [Compiler.h] (e.g. `COMPILER(GCC)`),
   [CPU.h] (e.g. `WTF_CPU_ARM_NEON`),
-  [build_config.h] (e.g. `OS(WIN)`)
+  [build_config.h] (e.g. `USE(APPLE_SYSTEM_LOG)`)
 
 * **Miscellaneous**
 
diff --git a/third_party/WebKit/Source/platform/wtf/StackUtil.cpp b/third_party/WebKit/Source/platform/wtf/StackUtil.cpp
index ef7daac..c547b58e 100644
--- a/third_party/WebKit/Source/platform/wtf/StackUtil.cpp
+++ b/third_party/WebKit/Source/platform/wtf/StackUtil.cpp
@@ -8,7 +8,7 @@
 #include "platform/wtf/Threading.h"
 #include "platform/wtf/WTFThreadData.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <stddef.h>
 #include <windows.h>
 #include <winnt.h>
@@ -28,14 +28,14 @@
 // FIXME: On Mac OSX and Linux, this method cannot estimate stack size
 // correctly for the main thread.
 
-#if defined(__GLIBC__) || OS(ANDROID) || OS(FREEBSD)
+#if defined(__GLIBC__) || defined(OS_ANDROID) || defined(OS_FREEBSD)
   // pthread_getattr_np() can fail if the thread is not invoked by
   // pthread_create() (e.g., the main thread of webkit_unit_tests).
   // If so, a conservative size estimate is returned.
 
   pthread_attr_t attr;
   int error;
-#if OS(FREEBSD)
+#if defined(OS_FREEBSD)
   pthread_attr_init(&attr);
   error = pthread_attr_get_np(pthread_self(), &attr);
 #else
@@ -49,7 +49,7 @@
     pthread_attr_destroy(&attr);
     return size;
   }
-#if OS(FREEBSD)
+#if defined(OS_FREEBSD)
   pthread_attr_destroy(&attr);
 #endif
 
@@ -60,7 +60,7 @@
   //    low as 512k.
   //
   return 512 * 1024;
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
   // pthread_get_stacksize_np() returns too low a value for the main thread on
   // OSX 10.9,
   // http://mail.openjdk.java.net/pipermail/hotspot-dev/2013-October/011369.html
@@ -95,10 +95,10 @@
 }
 
 void* GetStackStart() {
-#if defined(__GLIBC__) || OS(ANDROID) || OS(FREEBSD)
+#if defined(__GLIBC__) || defined(OS_ANDROID) || defined(OS_FREEBSD)
   pthread_attr_t attr;
   int error;
-#if OS(FREEBSD)
+#if defined(OS_FREEBSD)
   pthread_attr_init(&attr);
   error = pthread_attr_get_np(pthread_self(), &attr);
 #else
@@ -112,7 +112,7 @@
     pthread_attr_destroy(&attr);
     return reinterpret_cast<uint8_t*>(base) + size;
   }
-#if OS(FREEBSD)
+#if defined(OS_FREEBSD)
   pthread_attr_destroy(&attr);
 #endif
 #if defined(__GLIBC__)
@@ -125,7 +125,7 @@
   NOTREACHED();
   return nullptr;
 #endif
-#elif OS(MACOSX)
+#elif defined(OS_MACOSX)
   return pthread_get_stackaddr_np(pthread_self());
 #elif defined(OS_WIN) && defined(COMPILER_MSVC)
 // On Windows stack limits for the current thread are available in
diff --git a/third_party/WebKit/Source/platform/wtf/StringExtras.h b/third_party/WebKit/Source/platform/wtf/StringExtras.h
index 20af0cd..9e464f5 100644
--- a/third_party/WebKit/Source/platform/wtf/StringExtras.h
+++ b/third_party/WebKit/Source/platform/wtf/StringExtras.h
@@ -32,7 +32,7 @@
 #include "build/build_config.h"
 #include "platform/wtf/build_config.h"
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
 #include <strings.h>
 #endif
 
diff --git a/third_party/WebKit/Source/platform/wtf/StringExtrasTest.cpp b/third_party/WebKit/Source/platform/wtf/StringExtrasTest.cpp
index c7be3df5..d91d2e1 100644
--- a/third_party/WebKit/Source/platform/wtf/StringExtrasTest.cpp
+++ b/third_party/WebKit/Source/platform/wtf/StringExtrasTest.cpp
@@ -25,10 +25,12 @@
 
 #include "platform/wtf/StringExtras.h"
 
+#include <limits>
+
+#include "build/build_config.h"
 #include "platform/wtf/text/CString.h"
 #include "platform/wtf/text/WTFString.h"
 #include "testing/gtest/include/gtest/gtest.h"
-#include <limits>
 
 namespace WTF {
 
@@ -59,11 +61,11 @@
 struct PrintfFormatTrait<long long> {
   static const char kFormat[];
 };
-#if OS(WIN)
+#if defined(OS_WIN)
 const char PrintfFormatTrait<long long>::kFormat[] = "%I64i";
 #else
 const char PrintfFormatTrait<long long>::kFormat[] = "%lli";
-#endif  // OS(WIN)
+#endif  // defined(OS_WIN)
 
 template <>
 struct PrintfFormatTrait<unsigned short> {
@@ -87,11 +89,11 @@
 struct PrintfFormatTrait<unsigned long long> {
   static const char kFormat[];
 };
-#if OS(WIN)
+#if defined(OS_WIN)
 const char PrintfFormatTrait<unsigned long long>::kFormat[] = "%I64u";
 #else
 const char PrintfFormatTrait<unsigned long long>::kFormat[] = "%llu";
-#endif  // OS(WIN)
+#endif  // defined(OS_WIN)
 
 // FIXME: use snprintf from StringExtras.h
 template <typename IntegerType>
diff --git a/third_party/WebKit/Source/platform/wtf/ThreadSpecific.h b/third_party/WebKit/Source/platform/wtf/ThreadSpecific.h
index cad2797..ee4fe8be 100644
--- a/third_party/WebKit/Source/platform/wtf/ThreadSpecific.h
+++ b/third_party/WebKit/Source/platform/wtf/ThreadSpecific.h
@@ -42,6 +42,7 @@
 #ifndef WTF_ThreadSpecific_h
 #define WTF_ThreadSpecific_h
 
+#include "build/build_config.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Noncopyable.h"
 #include "platform/wtf/StackUtil.h"
@@ -51,15 +52,15 @@
 #include "platform/wtf/allocator/PartitionAllocator.h"
 #include "platform/wtf/allocator/Partitions.h"
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
 #include <pthread.h>
-#elif OS(WIN)
+#elif defined(OS_WIN)
 #include <windows.h>
 #endif
 
 namespace WTF {
 
-#if OS(WIN)
+#if defined(OS_WIN)
 // ThreadSpecificThreadExit should be called each time when a thread is
 // detached.
 // This is done automatically for threads created with WTF::createThread.
@@ -80,7 +81,7 @@
   T& operator*();
 
  private:
-#if OS(WIN)
+#if defined(OS_WIN)
   WTF_EXPORT friend void ThreadSpecificThreadExit();
 #endif
 
@@ -104,21 +105,21 @@
 
     T* value;
     ThreadSpecific<T>* owner;
-#if OS(WIN)
+#if defined(OS_WIN)
     void (*destructor)(void*);
 #endif
   };
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
   pthread_key_t key_;
-#elif OS(WIN)
+#elif defined(OS_WIN)
   int index_;
 #endif
   // This member must only be accessed or modified on the main thread.
   T* main_thread_storage_ = nullptr;
 };
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
 
 typedef pthread_key_t ThreadSpecificKey;
 
@@ -159,7 +160,7 @@
   pthread_setspecific(key_, new Data(ptr, this));
 }
 
-#elif OS(WIN)
+#elif defined(OS_WIN)
 
 // TLS_OUT_OF_INDEXES is not defined on WinCE.
 #ifndef TLS_OUT_OF_INDEXES
@@ -224,7 +225,7 @@
 inline void ThreadSpecific<T>::Destroy(void* ptr) {
   Data* data = static_cast<Data*>(ptr);
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
   // We want get() to keep working while data destructor works, because it can
   // be called indirectly by the destructor.  Some pthreads implementations
   // zero out the pointer before calling destroy(), so we temporarily reset it.
@@ -241,9 +242,9 @@
   data->value->~T();
   Partitions::FastFree(data->value);
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
   pthread_setspecific(data->owner->key_, 0);
-#elif OS(WIN)
+#elif defined(OS_WIN)
   TlsSetValue(TlsKeys()[data->owner->index_], 0);
 #else
 #error ThreadSpecific is not implemented for this platform.
@@ -260,7 +261,7 @@
 template <typename T>
 inline ThreadSpecific<T>::operator T*() {
   T* off_thread_ptr;
-#if defined(__GLIBC__) || OS(ANDROID) || OS(FREEBSD)
+#if defined(__GLIBC__) || defined(OS_ANDROID) || defined(OS_FREEBSD)
   // TLS is fast on these platforms.
   // TODO(csharrison): Qualify this statement for Android.
   const bool kMainThreadAlwaysChecksTLS = true;
diff --git a/third_party/WebKit/Source/platform/wtf/ThreadSpecificWin.cpp b/third_party/WebKit/Source/platform/wtf/ThreadSpecificWin.cpp
index 5f12896..9a000d5 100644
--- a/third_party/WebKit/Source/platform/wtf/ThreadSpecificWin.cpp
+++ b/third_party/WebKit/Source/platform/wtf/ThreadSpecificWin.cpp
@@ -21,7 +21,9 @@
 
 #include "platform/wtf/ThreadSpecific.h"
 
-#if OS(WIN)
+#include "build/build_config.h"
+
+#if defined(OS_WIN)
 
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/DoublyLinkedList.h"
@@ -126,4 +128,4 @@
 
 }  // namespace WTF
 
-#endif  // OS(WIN)
+#endif  // defined(OS_WIN)
diff --git a/third_party/WebKit/Source/platform/wtf/Threading.h b/third_party/WebKit/Source/platform/wtf/Threading.h
index 625a207..e85ef3d5 100644
--- a/third_party/WebKit/Source/platform/wtf/Threading.h
+++ b/third_party/WebKit/Source/platform/wtf/Threading.h
@@ -30,14 +30,16 @@
 #ifndef Threading_h
 #define Threading_h
 
+#include <stdint.h>
+
+#include "build/build_config.h"
 #include "platform/wtf/Atomics.h"
 #include "platform/wtf/TypeTraits.h"
 #include "platform/wtf/WTFExport.h"
-#include <stdint.h>
 
 namespace WTF {
 
-#if OS(WIN)
+#if defined(OS_WIN)
 typedef uint32_t ThreadIdentifier;
 #else
 typedef intptr_t ThreadIdentifier;
diff --git a/third_party/WebKit/Source/platform/wtf/ThreadingPrimitives.h b/third_party/WebKit/Source/platform/wtf/ThreadingPrimitives.h
index f578256f..95a0781f8 100644
--- a/third_party/WebKit/Source/platform/wtf/ThreadingPrimitives.h
+++ b/third_party/WebKit/Source/platform/wtf/ThreadingPrimitives.h
@@ -31,23 +31,24 @@
 #ifndef ThreadingPrimitives_h
 #define ThreadingPrimitives_h
 
+#include "build/build_config.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/Assertions.h"
 #include "platform/wtf/Locker.h"
 #include "platform/wtf/Noncopyable.h"
 #include "platform/wtf/WTFExport.h"
 
-#if OS(WIN)
+#if defined(OS_WIN)
 #include <windows.h>
 #endif
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
 #include <pthread.h>
 #endif
 
 namespace WTF {
 
-#if OS(POSIX)
+#if defined(OS_POSIX)
 struct PlatformMutex {
   pthread_mutex_t internal_mutex_;
 #if DCHECK_IS_ON()
@@ -55,7 +56,7 @@
 #endif
 };
 typedef pthread_cond_t PlatformCondition;
-#elif OS(WIN)
+#elif defined(OS_WIN)
 struct PlatformMutex {
   CRITICAL_SECTION internal_mutex_;
   size_t recursion_count_;
@@ -151,7 +152,7 @@
   PlatformCondition condition_;
 };
 
-#if OS(WIN)
+#if defined(OS_WIN)
 // The absoluteTime is in seconds, starting on January 1, 1970. The time is
 // assumed to use the same time zone as WTF::currentTime().
 // Returns an interval in milliseconds suitable for passing to one of the Win32
@@ -168,7 +169,7 @@
 using WTF::MutexTryLocker;
 using WTF::ThreadCondition;
 
-#if OS(WIN)
+#if defined(OS_WIN)
 using WTF::AbsoluteTimeToWaitTimeoutInterval;
 #endif
 
diff --git a/third_party/WebKit/Source/platform/wtf/ThreadingPthreads.cpp b/third_party/WebKit/Source/platform/wtf/ThreadingPthreads.cpp
index 763081e..3df13f56 100644
--- a/third_party/WebKit/Source/platform/wtf/ThreadingPthreads.cpp
+++ b/third_party/WebKit/Source/platform/wtf/ThreadingPthreads.cpp
@@ -30,7 +30,9 @@
 
 #include "platform/wtf/Threading.h"
 
-#if OS(POSIX)
+#include "build/build_config.h"
+
+#if defined(OS_POSIX)
 
 #include "platform/wtf/CurrentTime.h"
 #include "platform/wtf/DateMath.h"
@@ -45,15 +47,15 @@
 #include <sched.h>
 #include <sys/time.h>
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include <objc/objc-auto.h>
 #endif
 
-#if OS(LINUX)
+#if defined(OS_LINUX)
 #include <sys/syscall.h>
 #endif
 
-#if OS(LINUX) || OS(ANDROID)
+#if defined(OS_LINUX) || defined(OS_ANDROID)
 #include <unistd.h>
 #endif
 
@@ -62,11 +64,11 @@
 namespace internal {
 
 ThreadIdentifier CurrentThreadSyscall() {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   return pthread_mach_thread_np(pthread_self());
-#elif OS(LINUX)
+#elif defined(OS_LINUX)
   return syscall(__NR_gettid);
-#elif OS(ANDROID)
+#elif defined(OS_ANDROID)
   return gettid();
 #else
   return reinterpret_cast<uintptr_t>(pthread_self());
@@ -267,4 +269,4 @@
 
 }  // namespace WTF
 
-#endif  // OS(POSIX)
+#endif  // defined(OS_POSIX)
diff --git a/third_party/WebKit/Source/platform/wtf/ThreadingWin.cpp b/third_party/WebKit/Source/platform/wtf/ThreadingWin.cpp
index 2fd8fa3..0013b45 100644
--- a/third_party/WebKit/Source/platform/wtf/ThreadingWin.cpp
+++ b/third_party/WebKit/Source/platform/wtf/ThreadingWin.cpp
@@ -98,7 +98,9 @@
 
 #include "platform/wtf/Threading.h"
 
-#if OS(WIN)
+#include "build/build_config.h"
+
+#if defined(OS_WIN)
 
 #include "platform/wtf/CurrentTime.h"
 #include "platform/wtf/DateMath.h"
@@ -430,4 +432,4 @@
 
 }  // namespace WTF
 
-#endif  // OS(WIN)
+#endif  // defined(OS_WIN)
diff --git a/third_party/WebKit/Source/platform/wtf/build_config.h b/third_party/WebKit/Source/platform/wtf/build_config.h
index d40ab5f7..4703e00 100644
--- a/third_party/WebKit/Source/platform/wtf/build_config.h
+++ b/third_party/WebKit/Source/platform/wtf/build_config.h
@@ -34,11 +34,6 @@
  * present or not */
 #define HAVE(WTF_FEATURE) (defined HAVE_##WTF_FEATURE && HAVE_##WTF_FEATURE)
 
-// OS() - underlying operating system; only to be used for mandated low-level
-// services like virtual memory, not to choose a GUI toolkit
-// This macro is deprecated.  Use defined(OS_FOO).  See crbug.com/737403.
-#define OS(WTF_FEATURE) (defined OS_##WTF_FEATURE && OS_##WTF_FEATURE)
-
 /* ==== Policy decision macros: these define policy choices for a particular
  * port. ==== */
 
@@ -46,7 +41,8 @@
 #define USE(WTF_FEATURE) \
   (defined WTF_USE_##WTF_FEATURE && WTF_USE_##WTF_FEATURE)
 
-// There is an assumption in the project that either OS_WIN or OS_POSIX is set.
+/* There is an assumption in the project that either OS_WIN or OS_POSIX is
+ * set. */
 #if !defined(OS_WIN) && !defined(OS_POSIX)
 #error Either OS_WIN or OS_POSIX needs to be set.
 #endif
diff --git a/third_party/WebKit/Source/platform/wtf/text/AtomicString.h b/third_party/WebKit/Source/platform/wtf/text/AtomicString.h
index 83ea6c6..efcac87 100644
--- a/third_party/WebKit/Source/platform/wtf/text/AtomicString.h
+++ b/third_party/WebKit/Source/platform/wtf/text/AtomicString.h
@@ -21,14 +21,16 @@
 #ifndef AtomicString_h
 #define AtomicString_h
 
+#include <cstring>
+#include <iosfwd>
+
+#include "build/build_config.h"
 #include "platform/wtf/Allocator.h"
 #include "platform/wtf/HashTableDeletedValueType.h"
 #include "platform/wtf/WTFExport.h"
 #include "platform/wtf/text/CString.h"
 #include "platform/wtf/text/StringView.h"
 #include "platform/wtf/text/WTFString.h"
-#include <cstring>
-#include <iosfwd>
 
 namespace WTF {
 
@@ -236,7 +238,7 @@
     return AddSlowCase(r);
   }
   static RefPtr<StringImpl> AddSlowCase(StringImpl*);
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   static RefPtr<StringImpl> Add(CFStringRef);
 #endif
 };
diff --git a/third_party/WebKit/Source/platform/wtf/text/AtomicStringCF.cpp b/third_party/WebKit/Source/platform/wtf/text/AtomicStringCF.cpp
index 3cdd2f17..cea6354 100644
--- a/third_party/WebKit/Source/platform/wtf/text/AtomicStringCF.cpp
+++ b/third_party/WebKit/Source/platform/wtf/text/AtomicStringCF.cpp
@@ -25,9 +25,10 @@
 
 #include "platform/wtf/text/AtomicString.h"
 
+#include "build/build_config.h"
 #include "platform/wtf/text/AtomicStringTable.h"
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 
 #include "platform/wtf/text/CString.h"
 #include <CoreFoundation/CoreFoundation.h>
@@ -56,4 +57,4 @@
 
 }  // namespace WTF
 
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
diff --git a/third_party/WebKit/Source/platform/wtf/text/StringImpl.h b/third_party/WebKit/Source/platform/wtf/text/StringImpl.h
index 0d78c2f5..3d7ec33 100644
--- a/third_party/WebKit/Source/platform/wtf/text/StringImpl.h
+++ b/third_party/WebKit/Source/platform/wtf/text/StringImpl.h
@@ -24,6 +24,9 @@
 #ifndef StringImpl_h
 #define StringImpl_h
 
+#include <limits.h>
+#include <string.h>
+#include "build/build_config.h"
 #include "platform/wtf/ASCIICType.h"
 #include "platform/wtf/Forward.h"
 #include "platform/wtf/HashMap.h"
@@ -32,14 +35,12 @@
 #include "platform/wtf/WTFExport.h"
 #include "platform/wtf/text/ASCIIFastPath.h"
 #include "platform/wtf/text/Unicode.h"
-#include <limits.h>
-#include <string.h>
 
 #if DCHECK_IS_ON()
 #include "platform/wtf/ThreadRestrictionVerifier.h"
 #endif
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 typedef const struct __CFString* CFStringRef;
 #endif
 
@@ -414,7 +415,7 @@
                  unsigned start = 0,
                  unsigned length = UINT_MAX) const;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   RetainPtr<CFStringRef> CreateCFString();
 #endif
 #ifdef __OBJC__
diff --git a/third_party/WebKit/Source/platform/wtf/text/StringImplCF.cpp b/third_party/WebKit/Source/platform/wtf/text/StringImplCF.cpp
index 578d1aa..10bee71b 100644
--- a/third_party/WebKit/Source/platform/wtf/text/StringImplCF.cpp
+++ b/third_party/WebKit/Source/platform/wtf/text/StringImplCF.cpp
@@ -20,7 +20,9 @@
 
 #include "platform/wtf/text/StringImpl.h"
 
-#if OS(MACOSX)
+#include "build/build_config.h"
+
+#if defined(OS_MACOSX)
 
 #include "platform/wtf/RetainPtr.h"
 #include "platform/wtf/Threading.h"
@@ -160,4 +162,4 @@
 
 }  // namespace WTF
 
-#endif  // OS(MACOSX)
+#endif  // defined(OS_MACOSX)
diff --git a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp
index e1aa336..b81ff82a 100644
--- a/third_party/WebKit/Source/web/AssertMatchingEnums.cpp
+++ b/third_party/WebKit/Source/web/AssertMatchingEnums.cpp
@@ -32,9 +32,10 @@
 // matching blink defined enum values.
 
 #include "bindings/core/v8/serialization/SerializedScriptValue.h"
+#include "build/build_config.h"
 #include "core/dom/IconURL.h"
 #include "core/editing/SelectionType.h"
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
 #include "core/events/WheelEvent.h"
 #endif
 #include "core/fileapi/FileError.h"
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.cpp b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
index d2340f0..f093c74 100644
--- a/third_party/WebKit/Source/web/ChromeClientImpl.cpp
+++ b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
@@ -32,7 +32,9 @@
 #include "web/ChromeClientImpl.h"
 
 #include <memory>
+
 #include "bindings/core/v8/ScriptController.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/dom/Fullscreen.h"
@@ -631,7 +633,7 @@
   if (cursor_overridden_)
     return;
 
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
   // On Mac the mousemove event propagates to both the popup and main window.
   // If a popup is open we don't want the main window to change the cursor.
   if (web_view_->HasOpenedPopup())
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp b/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp
index b534d49..0b58977 100644
--- a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp
+++ b/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp
@@ -32,6 +32,7 @@
 
 #include <memory>
 
+#include "build/build_config.h"
 #include "core/animation/CompositorMutatorImpl.h"
 #include "core/dom/UserGestureIndicator.h"
 #include "core/editing/CompositionUnderlineVectorBuilder.h"
@@ -837,7 +838,7 @@
 
   // Dispatch the contextmenu event regardless of if the click was swallowed.
   if (!GetPage()->GetSettings().GetShowContextMenuOnMouseUp()) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     if (event.button == WebMouseEvent::Button::kRight ||
         (event.button == WebMouseEvent::Button::kLeft &&
          event.GetModifiers() & WebMouseEvent::kControlKey))
@@ -981,9 +982,9 @@
     return result;
   }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   const WebInputEvent::Type kContextMenuKeyTriggeringEventType =
-#if OS(WIN)
+#if defined(OS_WIN)
       WebInputEvent::kKeyUp;
 #else
       WebInputEvent::kRawKeyDown;
@@ -1003,7 +1004,7 @@
     View()->SendContextMenuEvent(event);
     return WebInputEventResult::kHandledSystem;
   }
-#endif  // !OS(MACOSX)
+#endif  // !defined(OS_MACOSX)
 
   return WebInputEventResult::kNotHandled;
 }
diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp
index 14c2d52..f6317cf7 100644
--- a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp
+++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp
@@ -100,6 +100,7 @@
 #include "bindings/core/v8/SourceLocation.h"
 #include "bindings/core/v8/V8BindingForCore.h"
 #include "bindings/core/v8/V8GCController.h"
+#include "build/build_config.h"
 #include "core/HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/dom/IconURL.h"
@@ -333,7 +334,7 @@
 
       AffineTransform transform;
       transform.Translate(0, current_height);
-#if OS(WIN) || OS(MACOSX)
+#if defined(OS_WIN) || defined(OS_MACOSX)
       // Account for the disabling of scaling in spoolPage. In the context of
       // SpoolAllPagesWithBoundariesForTesting the scale HAS NOT been
       // pre-applied.
@@ -365,7 +366,7 @@
     float scale = printed_page_width_ / page_rect.Width();
 
     AffineTransform transform;
-#if OS(POSIX) && !OS(MACOSX)
+#if defined(OS_POSIX) && !defined(OS_MACOSX)
     transform.Scale(scale);
 #endif
     transform.Translate(static_cast<float>(-page_rect.X()),
@@ -1132,7 +1133,7 @@
 
   String text = GetFrame()->Selection().SelectedText(
       TextIteratorBehavior::EmitsObjectReplacementCharacterBehavior());
-#if OS(WIN)
+#if defined(OS_WIN)
   ReplaceNewlinesWithWindowsStyleNewlines(text);
 #endif
   ReplaceNBSPWithSpace(text);
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp
index ec1f1ed..be61617 100644
--- a/third_party/WebKit/Source/web/WebViewImpl.cpp
+++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -31,6 +31,8 @@
 #include "web/WebViewImpl.h"
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "core/CSSValueKeywords.h"
 #include "core/HTMLNames.h"
 #include "core/animation/CompositorMutatorImpl.h"
@@ -492,7 +494,7 @@
 
   // Dispatch the contextmenu event regardless of if the click was swallowed.
   if (!GetPage()->GetSettings().GetShowContextMenuOnMouseUp()) {
-#if OS(MACOSX)
+#if defined(OS_MACOSX)
     if (event.button == WebMouseEvent::Button::kRight ||
         (event.button == WebMouseEvent::Button::kLeft &&
          event.GetModifiers() & WebMouseEvent::kControlKey))
@@ -1175,9 +1177,9 @@
     return result;
   }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
   const WebInputEvent::Type kContextMenuKeyTriggeringEventType =
-#if OS(WIN)
+#if defined(OS_WIN)
       WebInputEvent::kKeyUp;
 #else
       WebInputEvent::kRawKeyDown;
@@ -1197,7 +1199,7 @@
     SendContextMenuEvent(event);
     return WebInputEventResult::kHandledSystem;
   }
-#endif  // !OS(MACOSX)
+#endif  // !defined(OS_MACOSX)
 
   return WebInputEventResult::kNotHandled;
 }
@@ -1619,7 +1621,7 @@
   return true;
 }
 
-#if !OS(MACOSX)
+#if !defined(OS_MACOSX)
 // Mac has no way to open a context menu based on a keyboard event.
 WebInputEventResult WebViewImpl::SendContextMenuEvent(
     const WebKeyboardEvent& event) {
@@ -2081,7 +2083,7 @@
   software_paint_rate_histogram.Count(pixels_per_sec / 1000000);
 }
 
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 void WebViewImpl::PaintIgnoringCompositing(WebCanvas* canvas,
                                            const WebRect& rect) {
   // This is called on a composited WebViewImpl, but we will ignore it,
@@ -3826,13 +3828,20 @@
   // the mehtod.
   visual_viewport.SetScrollLayerOnScrollbars(layout_viewport_scroll_web_layer);
 
-  layer_tree_view_->RegisterViewportLayers(
-      visual_viewport.OverscrollElasticityLayer()->PlatformLayer(),
-      visual_viewport.PageScaleLayer()->PlatformLayer(),
-      visual_viewport.ContainerLayer()->PlatformLayer(),
-      layout_viewport_container_web_layer,
-      visual_viewport.ScrollLayer()->PlatformLayer(),
-      layout_viewport_scroll_web_layer);
+  WebLayerTreeView::ViewportLayers viewport_layers;
+  viewport_layers.overscroll_elasticity =
+      visual_viewport.OverscrollElasticityLayer()->PlatformLayer();
+  viewport_layers.page_scale =
+      visual_viewport.PageScaleLayer()->PlatformLayer();
+  viewport_layers.inner_viewport_container =
+      visual_viewport.ContainerLayer()->PlatformLayer();
+  viewport_layers.outer_viewport_container =
+      layout_viewport_container_web_layer;
+  viewport_layers.inner_viewport_scroll =
+      visual_viewport.ScrollLayer()->PlatformLayer();
+  viewport_layers.outer_viewport_scroll = layout_viewport_scroll_web_layer;
+
+  layer_tree_view_->RegisterViewportLayers(viewport_layers);
 }
 
 void WebViewImpl::SetRootGraphicsLayer(GraphicsLayer* graphics_layer) {
diff --git a/third_party/WebKit/Source/web/WebViewImpl.h b/third_party/WebKit/Source/web/WebViewImpl.h
index 68fc818..51cd9f0 100644
--- a/third_party/WebKit/Source/web/WebViewImpl.h
+++ b/third_party/WebKit/Source/web/WebViewImpl.h
@@ -32,6 +32,8 @@
 #define WebViewImpl_h
 
 #include <memory>
+
+#include "build/build_config.h"
 #include "core/editing/spellcheck/SpellCheckerClientImpl.h"
 #include "core/exported/WebPagePopupImpl.h"
 #include "core/exported/WebViewBase.h"
@@ -117,7 +119,7 @@
 
   void UpdateAllLifecyclePhases() override;
   void Paint(WebCanvas*, const WebRect&) override;
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
   void PaintIgnoringCompositing(WebCanvas*, const WebRect&) override;
 #endif
   void LayoutAndPaintAsync(WebLayoutAndPaintAsyncCallback*) override;
diff --git a/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp b/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp
index e48c3d5d..d925cd6 100644
--- a/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp
+++ b/third_party/WebKit/Source/web/tests/LayoutGeometryMapTest.cpp
@@ -30,6 +30,7 @@
 
 #include "core/layout/LayoutGeometryMap.h"
 
+#include "build/build_config.h"
 #include "core/dom/Document.h"
 #include "core/frame/FrameTestHelpers.h"
 #include "core/frame/WebLocalFrameBase.h"
@@ -212,7 +213,7 @@
 
 // Fails on Windows due to crbug.com/391457. When run through the transform the
 // position on windows differs by a pixel
-#if OS(WIN)
+#if defined(OS_WIN)
 TEST_P(LayoutGeometryMapTest, DISABLED_TransformedGeometryTest)
 #else
 TEST_P(LayoutGeometryMapTest, TransformedGeometryTest)
diff --git a/third_party/WebKit/Source/web/tests/VirtualTimeTest.cpp b/third_party/WebKit/Source/web/tests/VirtualTimeTest.cpp
index 4e4a9e1..f2a9f060 100644
--- a/third_party/WebKit/Source/web/tests/VirtualTimeTest.cpp
+++ b/third_party/WebKit/Source/web/tests/VirtualTimeTest.cpp
@@ -3,6 +3,7 @@
 // found in the LICENSE file.
 
 #include "base/message_loop/message_loop.h"
+#include "build/build_config.h"
 #include "core/dom/TaskRunnerHelper.h"
 #include "core/testing/sim/SimRequest.h"
 #include "core/testing/sim/SimTest.h"
@@ -68,7 +69,7 @@
 }
 
 // http://crbug.com/633321
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_DOMTimersFireInExpectedOrder DISABLED_DOMTimersFireInExpectedOrder
 #else
 #define MAYBE_DOMTimersFireInExpectedOrder DOMTimersFireInExpectedOrder
@@ -95,7 +96,7 @@
 }
 
 // http://crbug.com/633321
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_SetInterval DISABLED_SetInterval
 #else
 #define MAYBE_SetInterval SetInterval
@@ -121,7 +122,7 @@
 }
 
 // http://crbug.com/633321
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_AllowVirtualTimeToAdvance DISABLED_AllowVirtualTimeToAdvance
 #else
 #define MAYBE_AllowVirtualTimeToAdvance AllowVirtualTimeToAdvance
@@ -151,7 +152,7 @@
 }
 
 // http://crbug.com/633321
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_VirtualTimeNotAllowedToAdvanceWhileResourcesLoading \
   DISABLED_VirtualTimeNotAllowedToAdvanceWhileResourcesLoading
 #else
@@ -200,7 +201,7 @@
 }
 
 // http://crbug.com/633321
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 #define MAYBE_DOMTimersSuspended DISABLED_DOMTimersSuspended
 #else
 #define MAYBE_DOMTimersSuspended DOMTimersSuspended
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
index 55d80016..7e779df 100644
--- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
+++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -43,6 +43,7 @@
 #include "bindings/core/v8/V8Node.h"
 #include "bindings/core/v8/serialization/SerializedScriptValueFactory.h"
 #include "bindings/core/v8/serialization/V8ScriptValueSerializer.h"
+#include "build/build_config.h"
 #include "core/clipboard/DataTransfer.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
@@ -3184,7 +3185,7 @@
 }
 
 // Android doesn't have scrollbars on the main LocalFrameView
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 TEST_F(WebFrameTest, DISABLED_updateOverlayScrollbarLayers)
 #else
 TEST_F(WebFrameTest, updateOverlayScrollbarLayers)
@@ -5761,7 +5762,7 @@
   EXPECT_EQ(64, ComputeOffset(layout_object, 1000, 1000));
 }
 
-#if !OS(MACOSX) && !OS(LINUX)
+#if !defined(OS_MACOSX) && !defined(OS_LINUX)
 TEST_P(ParameterizedWebFrameTest,
        SelectRangeStaysHorizontallyAlignedWhenMoved) {
   RegisterMockedHttpURLLoad("move_caret.html");
@@ -8692,7 +8693,7 @@
 }
 
 // Crashes on Android: http://crbug.com/403804
-#if OS(ANDROID)
+#if defined(OS_ANDROID)
 TEST_P(ParameterizedWebFrameTest, DISABLED_PrintingBasic)
 #else
 TEST_P(ParameterizedWebFrameTest, PrintingBasic)
diff --git a/third_party/WebKit/public/platform/WebContentDecryptionModule.h b/third_party/WebKit/public/platform/WebContentDecryptionModule.h
index 65d7b076d..11f96c7 100644
--- a/third_party/WebKit/public/platform/WebContentDecryptionModule.h
+++ b/third_party/WebKit/public/platform/WebContentDecryptionModule.h
@@ -46,6 +46,9 @@
   virtual void SetServerCertificate(const unsigned char* certificate,
                                     size_t certificate_length,
                                     WebContentDecryptionModuleResult) = 0;
+
+  virtual void GetStatusForPolicy(const WebString& min_hdcp_version,
+                                  WebContentDecryptionModuleResult) = 0;
 };
 
 }  // namespace blink
diff --git a/third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h b/third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h
index 1eaf954..eaeba5cf 100644
--- a/third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h
+++ b/third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h
@@ -7,6 +7,7 @@
 
 #include "WebCommon.h"
 #include "WebContentDecryptionModuleException.h"
+#include "WebEncryptedMediaKeyInformation.h"
 #include "WebPrivatePtr.h"
 
 namespace blink {
@@ -52,6 +53,10 @@
   // Called when the CDM completes a session operation.
   BLINK_PLATFORM_EXPORT void CompleteWithSession(SessionStatus);
 
+  // Called when the CDM completes getting key status for policy.
+  BLINK_PLATFORM_EXPORT void CompleteWithKeyStatus(
+      WebEncryptedMediaKeyInformation::KeyStatus);
+
   // Called when the operation fails.
   BLINK_PLATFORM_EXPORT void CompleteWithError(
       WebContentDecryptionModuleException,
diff --git a/third_party/WebKit/public/platform/WebLayerTreeView.h b/third_party/WebKit/public/platform/WebLayerTreeView.h
index eac29e0..dd162199 100644
--- a/third_party/WebKit/public/platform/WebLayerTreeView.h
+++ b/third_party/WebKit/public/platform/WebLayerTreeView.h
@@ -139,14 +139,17 @@
   // Prevents updates to layer tree from becoming visible.
   virtual void SetDeferCommits(bool defer_commits) {}
 
+  struct ViewportLayers {
+    const WebLayer* overscroll_elasticity = nullptr;
+    const WebLayer* page_scale = nullptr;
+    const WebLayer* inner_viewport_container = nullptr;
+    const WebLayer* outer_viewport_container = nullptr;
+    const WebLayer* inner_viewport_scroll = nullptr;
+    const WebLayer* outer_viewport_scroll = nullptr;
+  };
+
   // Identify key viewport layers to the compositor.
-  virtual void RegisterViewportLayers(
-      const WebLayer* overscroll_elasticity_layer,
-      const WebLayer* page_scale_layer,
-      const WebLayer* inner_viewport_container_layer,
-      const WebLayer* outer_viewport_container_layer,
-      const WebLayer* inner_viewport_scroll_layer,
-      const WebLayer* outer_viewport_scroll_layer) {}
+  virtual void RegisterViewportLayers(const ViewportLayers& viewport_layers) {}
   virtual void ClearViewportLayers() {}
 
   // Used to update the active selection bounds.
diff --git a/tools/clang/scripts/run_tool.py b/tools/clang/scripts/run_tool.py
index d55275a0..98f1cac5 100755
--- a/tools/clang/scripts/run_tool.py
+++ b/tools/clang/scripts/run_tool.py
@@ -56,7 +56,6 @@
 import subprocess
 import sys
 
-
 script_dir = os.path.dirname(os.path.realpath(__file__))
 tool_dir = os.path.abspath(os.path.join(script_dir, '../pylib'))
 sys.path.insert(0, tool_dir)
@@ -70,15 +69,15 @@
 
   Args:
     git_files: List of all repository files.
-    paths: Prefix filter for the returned paths. May contain multiple entries.
+    paths: Prefix filter for the returned paths. May contain multiple entries,
+        and the contents should be absolute paths.
 
   Returns:
     Pruned list of files.
   """
   pruned_list = []
-  paths = [os.path.realpath(p) for p in sorted(paths)]
   git_index = 0
-  for path in paths:
+  for path in sorted(paths):
     least = git_index
     most = len(git_files) - 1
     while least <= most:
@@ -99,23 +98,35 @@
 
 
 def _GetFilesFromGit(paths=None):
-  """Gets the list of files in the git repository.
+  """Gets the list of files in the git repository if |paths| includes prefix
+  path filters or is empty. All complete filenames in |paths| are also included
+  in the output.
 
   Args:
     paths: Prefix filter for the returned paths. May contain multiple entries.
   """
-  args = []
-  if sys.platform == 'win32':
-    args.append('git.bat')
-  else:
-    args.append('git')
-  args.append('ls-files')
-  command = subprocess.Popen(args, stdout=subprocess.PIPE)
-  output, _ = command.communicate()
-  git_files = [os.path.realpath(p) for p in output.splitlines()]
-  if paths:
-    git_files = _PruneGitFiles(git_files, paths)
-  return git_files
+  partial_paths = []
+  files = []
+  for p in paths:
+    real_path = os.path.realpath(p)
+    if os.path.isfile(real_path):
+      files.append(real_path)
+    else:
+      partial_paths.append(real_path)
+  if partial_paths or not files:
+    args = []
+    if sys.platform == 'win32':
+      args.append('git.bat')
+    else:
+      args.append('git')
+    args.append('ls-files')
+    command = subprocess.Popen(args, stdout=subprocess.PIPE)
+    output, _ = command.communicate()
+    git_files = [os.path.realpath(p) for p in output.splitlines()]
+    if partial_paths:
+      git_files = _PruneGitFiles(git_files, partial_paths)
+    files.extend(git_files)
+  return files
 
 
 def _GetFilesFromCompileDB(build_directory):
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml
index 3c2dd247..f2805470 100644
--- a/tools/metrics/histograms/histograms.xml
+++ b/tools/metrics/histograms/histograms.xml
@@ -44912,6 +44912,14 @@
 </histogram>
 
 <histogram name="NewTabPage.ContentSuggestions.CountOnNtpOpened">
+  <obsolete>
+    Deprecated in July 2017. This metric was replaced by
+    CountOnNtpOpenedIfVisible. Initially the metric was not recorded properly if
+    any category was not visible. This was fixed in
+    https://codereview.chromium.org/2874213002/, however, not visible categories
+    still were polluting the metric (they were recorded as showing 0
+    suggestions).
+  </obsolete>
   <owner>treib@chromium.org</owner>
   <summary>
     Android: The number of suggestion cards that were available at the time an
@@ -44919,6 +44927,15 @@
   </summary>
 </histogram>
 
+<histogram name="NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible">
+  <owner>vitaliii@chromium.org</owner>
+  <summary>
+    Android: The number of suggestion cards that were available at the time an
+    NTP was opened. Only visible categories (i.e. which can be seen by the user
+    on this NTP) are recorded, including empty ones.
+  </summary>
+</histogram>
+
 <histogram name="NewTabPage.ContentSuggestions.DismissedUnvisited"
     units="index">
   <owner>treib@chromium.org</owner>
@@ -89120,7 +89137,8 @@
   <suffix name="Experimental" label="Experimental"/>
   <suffix name="ReadingList" label="Reading List entries"/>
   <suffix name="BreakingNews" label="Breaking News entries"/>
-  <affected-histogram name="NewTabPage.ContentSuggestions.CountOnNtpOpened"/>
+  <affected-histogram
+      name="NewTabPage.ContentSuggestions.CountOnNtpOpenedIfVisible"/>
   <affected-histogram name="NewTabPage.ContentSuggestions.DismissedUnvisited"/>
   <affected-histogram name="NewTabPage.ContentSuggestions.DismissedVisited"/>
   <affected-histogram name="NewTabPage.ContentSuggestions.MenuOpened"/>
diff --git a/tools/perf/page_sets/system_health/expectations.py b/tools/perf/page_sets/system_health/expectations.py
index 715db4f..45e87cd6 100644
--- a/tools/perf/page_sets/system_health/expectations.py
+++ b/tools/perf/page_sets/system_health/expectations.py
@@ -28,6 +28,8 @@
                       [expectations.ALL_WIN], 'crbug.com/728152')
     self.DisableStory('browse:news:cnn',
                       [expectations.ALL_MAC], 'crbug.com/728576')
+    self.DisableStory('browse:social:twitter_infinite_scroll',
+                      [expectations.ALL], 'crbug.com/728464')
     self.DisableStory('browse:media:flickr_infinite_scroll',
                       [expectations.ALL],
                       'crbug.com/728785')
@@ -161,6 +163,8 @@
                       'crbug.com/728152')
     self.DisableStory('browse:news:cnn',
                       [expectations.ALL_MAC], 'crbug.com/728576')
+    self.DisableStory('browse:social:twitter_infinite_scroll',
+                      [expectations.ALL], 'crbug.com/728464')
     self.DisableStory('browse:media:flickr_infinite_scroll',
                       [expectations.ALL, expectations.ALL_WIN],
                       'crbug.com/728785')
diff --git a/ui/file_manager/integration_tests/file_manager/quick_view.js b/ui/file_manager/integration_tests/file_manager/quick_view.js
index 033d52d..7a602e92d 100644
--- a/ui/file_manager/integration_tests/file_manager/quick_view.js
+++ b/ui/file_manager/integration_tests/file_manager/quick_view.js
@@ -37,8 +37,8 @@
                 'deepQueryAllElements', appId,
                 [['#quick-view', '#dialog'], null, ['display']])
             .then(function(results) {
-              chrome.test.assertEq(1, results.length);
-              if (results[0].styles.display === 'none') {
+              if (results.length === 0 ||
+                  results[0].styles.display === 'none') {
                 return pending('Quick View is not opened yet.');
               };
               return results;
diff --git a/ui/keyboard/keyboard_controller.cc b/ui/keyboard/keyboard_controller.cc
index 8c98f17..8bd0a54 100644
--- a/ui/keyboard/keyboard_controller.cc
+++ b/ui/keyboard/keyboard_controller.cc
@@ -278,7 +278,6 @@
                                        KeyboardLayoutDelegate* delegate)
     : ui_(ui),
       layout_delegate_(delegate),
-      input_method_(NULL),
       keyboard_visible_(false),
       show_on_resize_(false),
       keyboard_locked_(false),
@@ -286,8 +285,7 @@
       state_(KeyboardControllerState::UNKNOWN),
       weak_factory_(this) {
   CHECK(ui);
-  input_method_ = ui_->GetInputMethod();
-  input_method_->AddObserver(this);
+  ui_->GetInputMethod()->AddObserver(this);
   ui_->SetController(this);
   ChangeState(KeyboardControllerState::INITIAL);
 }
@@ -299,8 +297,7 @@
     container_->RemoveObserver(this);
     container_->RemovePreTargetHandler(&event_filter_);
   }
-  if (input_method_)
-    input_method_->RemoveObserver(this);
+  ui_->GetInputMethod()->RemoveObserver(this);
   for (KeyboardControllerObserver& observer : observer_list_)
     observer.OnKeyboardClosed();
   ui_->SetController(nullptr);
@@ -547,12 +544,6 @@
   }
 }
 
-void KeyboardController::OnInputMethodDestroyed(
-    const ui::InputMethod* input_method) {
-  DCHECK_EQ(input_method_, input_method);
-  input_method_ = NULL;
-}
-
 void KeyboardController::OnShowImeIfNeeded() {
   // Calling |ShowKeyboardInternal| may move the keyboard to another display.
   if (IsKeyboardEnabled() && !keyboard_locked())
diff --git a/ui/keyboard/keyboard_controller.h b/ui/keyboard/keyboard_controller.h
index c742fcd..a62890e3 100644
--- a/ui/keyboard/keyboard_controller.h
+++ b/ui/keyboard/keyboard_controller.h
@@ -170,12 +170,12 @@
                              const gfx::Rect& new_bounds) override;
 
   // InputMethodObserver overrides
-  void OnTextInputTypeChanged(const ui::TextInputClient* client) override {}
-  void OnFocus() override {}
   void OnBlur() override {}
   void OnCaretBoundsChanged(const ui::TextInputClient* client) override {}
+  void OnFocus() override {}
+  void OnInputMethodDestroyed(const ui::InputMethod* input_method) override {}
+  void OnTextInputTypeChanged(const ui::TextInputClient* client) override {}
   void OnTextInputStateChanged(const ui::TextInputClient* client) override;
-  void OnInputMethodDestroyed(const ui::InputMethod* input_method) override;
   void OnShowImeIfNeeded() override;
 
   // Show virtual keyboard immediately with animation.
@@ -206,7 +206,6 @@
   // uses container_'s animator.
   std::unique_ptr<CallbackAnimationObserver> animation_observer_;
 
-  ui::InputMethod* input_method_;
   bool keyboard_visible_;
   bool show_on_resize_;
   // If true, the keyboard is always visible even if no window has input focus.
diff --git a/ui/message_center/BUILD.gn b/ui/message_center/BUILD.gn
index 377026c..99940ddeb 100644
--- a/ui/message_center/BUILD.gn
+++ b/ui/message_center/BUILD.gn
@@ -268,6 +268,7 @@
         "views/message_center_view_unittest.cc",
         "views/message_list_view_unittest.cc",
         "views/message_popup_collection_unittest.cc",
+        "views/notification_view_md_unittest.cc",
         "views/notification_view_unittest.cc",
         "views/notifier_settings_view_unittest.cc",
       ]
diff --git a/ui/message_center/views/notification_view_md.cc b/ui/message_center/views/notification_view_md.cc
index 5426c6f..93c99752c 100644
--- a/ui/message_center/views/notification_view_md.cc
+++ b/ui/message_center/views/notification_view_md.cc
@@ -117,6 +117,8 @@
   explicit ItemView(const message_center::NotificationItem& item);
   ~ItemView() override;
 
+  const char* GetClassName() const override;
+
  private:
   DISALLOW_COPY_AND_ASSIGN(ItemView);
 };
@@ -143,6 +145,10 @@
 
 ItemView::~ItemView() = default;
 
+const char* ItemView::GetClassName() const {
+  return "ItemView";
+}
+
 // CompactTitleMessageView /////////////////////////////////////////////////////
 
 // CompactTitleMessageView shows notification title and message in a single
@@ -152,6 +158,8 @@
   explicit CompactTitleMessageView();
   ~CompactTitleMessageView() override;
 
+  const char* GetClassName() const override;
+
   void OnPaint(gfx::Canvas* canvas) override;
 
   void set_title(const base::string16& title) { title_ = title; }
@@ -167,7 +175,11 @@
   views::Label* message_view_ = nullptr;
 };
 
-CompactTitleMessageView::~CompactTitleMessageView() {}
+CompactTitleMessageView::~CompactTitleMessageView() = default;
+
+const char* CompactTitleMessageView::GetClassName() const {
+  return "CompactTitleMessageView";
+}
 
 CompactTitleMessageView::CompactTitleMessageView() {
   SetLayoutManager(new views::FillLayout());
@@ -230,6 +242,7 @@
   ~NotificationButtonMD() override;
 
   void SetText(const base::string16& text) override;
+  const char* GetClassName() const override;
 
   std::unique_ptr<views::InkDropHighlight> CreateInkDropHighlight()
       const override;
@@ -260,6 +273,10 @@
   views::LabelButton::SetText(base::i18n::ToUpper(text));
 }
 
+const char* NotificationButtonMD::GetClassName() const {
+  return "NotificationButtonMD";
+}
+
 std::unique_ptr<views::InkDropHighlight>
 NotificationButtonMD::CreateInkDropHighlight() const {
   std::unique_ptr<views::InkDropHighlight> highlight =
@@ -315,10 +332,12 @@
   CreateOrUpdateIconView(notification);
   CreateOrUpdateSmallIconView(notification);
   CreateOrUpdateImageView(notification);
-  CreateOrUpdateActionButtonViews(notification);
   CreateOrUpdateCloseButtonView(notification);
   CreateOrUpdateSettingsButtonView(notification);
   UpdateViewForExpandedState(expanded_);
+  // Should be called at the last because SynthesizeMouseMoveEvent() requires
+  // everything is in the right location when called.
+  CreateOrUpdateActionButtonViews(notification);
 }
 
 NotificationViewMD::NotificationViewMD(MessageCenterController* controller,
@@ -483,8 +502,10 @@
 
 void NotificationViewMD::CreateOrUpdateTitleView(
     const Notification& notification) {
-  if (notification.type() == NOTIFICATION_TYPE_PROGRESS) {
-    left_content_->RemoveChildView(title_view_);
+  if (notification.title().empty() ||
+      notification.type() == NOTIFICATION_TYPE_PROGRESS) {
+    if (title_view_)
+      left_content_->RemoveChildView(title_view_);
     title_view_ = nullptr;
     return;
   }
@@ -539,7 +560,8 @@
 void NotificationViewMD::CreateOrUpdateCompactTitleMessageView(
     const Notification& notification) {
   if (notification.type() != NOTIFICATION_TYPE_PROGRESS) {
-    left_content_->RemoveChildView(compact_title_message_view_);
+    if (compact_title_message_view_)
+      left_content_->RemoveChildView(compact_title_message_view_);
     compact_title_message_view_ = nullptr;
     return;
   }
@@ -556,7 +578,8 @@
 void NotificationViewMD::CreateOrUpdateProgressBarView(
     const Notification& notification) {
   if (notification.type() != NOTIFICATION_TYPE_PROGRESS) {
-    left_content_->RemoveChildView(progress_bar_view_);
+    if (progress_bar_view_)
+      left_content_->RemoveChildView(progress_bar_view_);
     progress_bar_view_ = nullptr;
     header_row_->ClearProgress();
     return;
@@ -604,7 +627,8 @@
     const Notification& notification) {
   if (notification.type() == NOTIFICATION_TYPE_PROGRESS ||
       notification.type() == NOTIFICATION_TYPE_MULTIPLE) {
-    right_content_->RemoveChildView(icon_view_);
+    if (icon_view_)
+      right_content_->RemoveChildView(icon_view_);
     icon_view_ = nullptr;
     return;
   }
@@ -696,11 +720,14 @@
     }
   }
 
-  if (new_buttons) {
-    // TODO(fukino): Investigate if this Layout() is necessary.
-    Layout();
+  // Inherit mouse hover state when action button views reset.
+  // If the view is not expanded, there should be no hover state.
+  if (new_buttons && expanded_) {
     views::Widget* widget = GetWidget();
-    if (widget != NULL) {
+    if (widget) {
+      // This Layout() is needed because button should be in the right location
+      // in the view hierarchy when SynthesizeMouseMoveEvent() is called.
+      Layout();
       widget->SetSize(widget->GetContentsView()->GetPreferredSize());
       GetWidget()->SynthesizeMouseMoveEvent();
     }
diff --git a/ui/message_center/views/notification_view_md.h b/ui/message_center/views/notification_view_md.h
index 890165a..547d112d 100644
--- a/ui/message_center/views/notification_view_md.h
+++ b/ui/message_center/views/notification_view_md.h
@@ -64,6 +64,13 @@
   views::View* TargetForRect(views::View* root, const gfx::Rect& rect) override;
 
  private:
+  FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, CreateOrUpdateTest);
+  FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, TestIconSizing);
+  FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, UpdateButtonsStateTest);
+  FRIEND_TEST_ALL_PREFIXES(NotificationViewMDTest, UpdateButtonCountTest);
+
+  friend class NotificationViewMDTest;
+
   void CreateOrUpdateViews(const Notification& notification);
 
   void CreateOrUpdateContextTitleView(const Notification& notification);
diff --git a/ui/message_center/views/notification_view_md_unittest.cc b/ui/message_center/views/notification_view_md_unittest.cc
new file mode 100644
index 0000000..9baa68c
--- /dev/null
+++ b/ui/message_center/views/notification_view_md_unittest.cc
@@ -0,0 +1,501 @@
+// Copyright 2017 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 "ui/message_center/views/notification_view_md.h"
+
+#include "base/strings/string_util.h"
+#include "base/strings/utf_string_conversions.h"
+#include "build/build_config.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "ui/compositor/scoped_animation_duration_scale_mode.h"
+#include "ui/events/event_processor.h"
+#include "ui/events/event_utils.h"
+#include "ui/events/test/event_generator.h"
+#include "ui/gfx/canvas.h"
+#include "ui/message_center/message_center_style.h"
+#include "ui/message_center/views/message_center_controller.h"
+#include "ui/message_center/views/notification_header_view.h"
+#include "ui/message_center/views/proportional_image_view.h"
+#include "ui/views/controls/button/image_button.h"
+#include "ui/views/controls/button/label_button.h"
+#include "ui/views/test/views_test_base.h"
+#include "ui/views/test/widget_test.h"
+
+namespace message_center {
+
+/* Test fixture ***************************************************************/
+
+// Used to fill bitmaps returned by CreateBitmap().
+static const SkColor kBitmapColor = SK_ColorGREEN;
+
+class NotificationViewMDTest : public views::ViewsTestBase,
+                               public MessageCenterController {
+ public:
+  NotificationViewMDTest();
+  ~NotificationViewMDTest() override;
+
+  // Overridden from ViewsTestBase:
+  void SetUp() override;
+  void TearDown() override;
+
+  // Overridden from MessageCenterController:
+  void ClickOnNotification(const std::string& notification_id) override;
+  void RemoveNotification(const std::string& notification_id,
+                          bool by_user) override;
+  std::unique_ptr<ui::MenuModel> CreateMenuModel(
+      const NotifierId& notifier_id,
+      const base::string16& display_source) override;
+  bool HasClickedListener(const std::string& notification_id) override;
+  void ClickOnNotificationButton(const std::string& notification_id,
+                                 int button_index) override;
+  void ClickOnSettingsButton(const std::string& notification_id) override;
+  void UpdateNotificationSize(const std::string& notification_id) override;
+
+  NotificationViewMD* notification_view() const {
+    return notification_view_.get();
+  }
+  Notification* notification() const { return notification_.get(); }
+  views::Widget* widget() const {
+    DCHECK_EQ(widget_, notification_view()->GetWidget());
+    return widget_;
+  }
+
+ protected:
+  const gfx::Image CreateTestImage(int width, int height);
+  const SkBitmap CreateBitmap(int width, int height);
+  std::vector<ButtonInfo> CreateButtons(int number);
+
+  // Paints |view| and returns the size that the original image (which must have
+  // been created by CreateBitmap()) was scaled to.
+  gfx::Size GetImagePaintSize(ProportionalImageView* view);
+
+  void UpdateNotificationViews();
+  float GetNotificationSlideAmount() const;
+  bool IsRemoved(const std::string& notification_id) const;
+  void DispatchGesture(const ui::GestureEventDetails& details);
+  void BeginScroll();
+  void EndScroll();
+  void ScrollBy(int dx);
+  views::ImageButton* GetCloseButton();
+
+ private:
+  std::set<std::string> removed_ids_;
+
+  std::unique_ptr<RichNotificationData> data_;
+  std::unique_ptr<Notification> notification_;
+  std::unique_ptr<NotificationViewMD> notification_view_;
+  views::Widget* widget_;
+
+  DISALLOW_COPY_AND_ASSIGN(NotificationViewMDTest);
+};
+
+NotificationViewMDTest::NotificationViewMDTest() = default;
+NotificationViewMDTest::~NotificationViewMDTest() = default;
+
+void NotificationViewMDTest::SetUp() {
+  views::ViewsTestBase::SetUp();
+  // Create a dummy notification.
+  data_.reset(new RichNotificationData());
+  notification_.reset(new Notification(
+      NOTIFICATION_TYPE_BASE_FORMAT, std::string("notification id"),
+      base::UTF8ToUTF16("title"), base::UTF8ToUTF16("message"),
+      CreateTestImage(80, 80), base::UTF8ToUTF16("display source"), GURL(),
+      NotifierId(NotifierId::APPLICATION, "extension_id"), *data_, nullptr));
+  notification_->set_small_image(CreateTestImage(16, 16));
+  notification_->set_image(CreateTestImage(320, 240));
+
+  // Then create a new NotificationView with that single notification.
+  // In the actual code path, this is instantiated by
+  // MessageViewFactory::Create.
+  // TODO(tetsui): Confirm that NotificationViewMD options are same as one
+  // created by the method.
+  notification_view_.reset(new NotificationViewMD(this, *notification_));
+  notification_view_->SetIsNested();
+  notification_view_->set_owned_by_client();
+
+  views::Widget::InitParams init_params(
+      CreateParams(views::Widget::InitParams::TYPE_POPUP));
+  widget_ = new views::Widget();
+  widget_->Init(init_params);
+  widget_->SetContentsView(notification_view_.get());
+  widget_->SetSize(notification_view_->GetPreferredSize());
+  widget_->Show();
+}
+
+void NotificationViewMDTest::TearDown() {
+  widget()->Close();
+  notification_view_.reset();
+  views::ViewsTestBase::TearDown();
+}
+
+void NotificationViewMDTest::ClickOnNotification(
+    const std::string& notification_id) {
+  // For this test, this method should not be invoked.
+  NOTREACHED();
+}
+
+void NotificationViewMDTest::RemoveNotification(
+    const std::string& notification_id,
+    bool by_user) {
+  removed_ids_.insert(notification_id);
+}
+
+std::unique_ptr<ui::MenuModel> NotificationViewMDTest::CreateMenuModel(
+    const NotifierId& notifier_id,
+    const base::string16& display_source) {
+  // For this test, this method should not be invoked.
+  NOTREACHED();
+  return nullptr;
+}
+
+bool NotificationViewMDTest::HasClickedListener(
+    const std::string& notification_id) {
+  return true;
+}
+
+void NotificationViewMDTest::ClickOnNotificationButton(
+    const std::string& notification_id,
+    int button_index) {
+  // For this test, this method should not be invoked.
+  NOTREACHED();
+}
+
+void NotificationViewMDTest::ClickOnSettingsButton(
+    const std::string& notification_id) {
+  // For this test, this method should not be invoked.
+  NOTREACHED();
+}
+
+void NotificationViewMDTest::UpdateNotificationSize(
+    const std::string& notification_id) {
+  widget()->SetSize(notification_view()->GetPreferredSize());
+}
+
+const gfx::Image NotificationViewMDTest::CreateTestImage(int width,
+                                                         int height) {
+  return gfx::Image::CreateFrom1xBitmap(CreateBitmap(width, height));
+}
+
+const SkBitmap NotificationViewMDTest::CreateBitmap(int width, int height) {
+  SkBitmap bitmap;
+  bitmap.allocN32Pixels(width, height);
+  bitmap.eraseColor(kBitmapColor);
+  return bitmap;
+}
+
+std::vector<ButtonInfo> NotificationViewMDTest::CreateButtons(int number) {
+  ButtonInfo info(base::ASCIIToUTF16("Test button."));
+  info.icon = CreateTestImage(4, 4);
+  return std::vector<ButtonInfo>(number, info);
+}
+
+gfx::Size NotificationViewMDTest::GetImagePaintSize(
+    ProportionalImageView* view) {
+  CHECK(view);
+  if (view->bounds().IsEmpty())
+    return gfx::Size();
+
+  gfx::Size canvas_size = view->bounds().size();
+  gfx::Canvas canvas(canvas_size, 1.0 /* image_scale */, true /* is_opaque */);
+  static_assert(kBitmapColor != SK_ColorBLACK,
+                "The bitmap color must match the background color");
+  canvas.DrawColor(SK_ColorBLACK);
+  view->OnPaint(&canvas);
+
+  SkBitmap bitmap = canvas.GetBitmap();
+  // Incrementally inset each edge at its midpoint to find the bounds of the
+  // rect containing the image's color. This assumes that the image is
+  // centered in the canvas.
+  const int kHalfWidth = canvas_size.width() / 2;
+  const int kHalfHeight = canvas_size.height() / 2;
+  gfx::Rect rect(canvas_size);
+  while (rect.width() > 0 &&
+         bitmap.getColor(rect.x(), kHalfHeight) != kBitmapColor)
+    rect.Inset(1, 0, 0, 0);
+  while (rect.height() > 0 &&
+         bitmap.getColor(kHalfWidth, rect.y()) != kBitmapColor)
+    rect.Inset(0, 1, 0, 0);
+  while (rect.width() > 0 &&
+         bitmap.getColor(rect.right() - 1, kHalfHeight) != kBitmapColor)
+    rect.Inset(0, 0, 1, 0);
+  while (rect.height() > 0 &&
+         bitmap.getColor(kHalfWidth, rect.bottom() - 1) != kBitmapColor)
+    rect.Inset(0, 0, 0, 1);
+
+  return rect.size();
+}
+
+void NotificationViewMDTest::UpdateNotificationViews() {
+  notification_view()->UpdateWithNotification(*notification());
+}
+
+float NotificationViewMDTest::GetNotificationSlideAmount() const {
+  return notification_view_->GetSlideOutLayer()
+      ->transform()
+      .To2dTranslation()
+      .x();
+}
+
+bool NotificationViewMDTest::IsRemoved(
+    const std::string& notification_id) const {
+  return (removed_ids_.find(notification_id) != removed_ids_.end());
+}
+
+void NotificationViewMDTest::DispatchGesture(
+    const ui::GestureEventDetails& details) {
+  ui::test::EventGenerator generator(
+      notification_view()->GetWidget()->GetNativeWindow());
+  ui::GestureEvent event(0, 0, 0, ui::EventTimeForNow(), details);
+  generator.Dispatch(&event);
+}
+
+void NotificationViewMDTest::BeginScroll() {
+  DispatchGesture(ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
+}
+
+void NotificationViewMDTest::EndScroll() {
+  DispatchGesture(ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END));
+}
+
+void NotificationViewMDTest::ScrollBy(int dx) {
+  DispatchGesture(ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, dx, 0));
+}
+
+views::ImageButton* NotificationViewMDTest::GetCloseButton() {
+  return notification_view()->header_row_->close_button();
+}
+
+/* Unit tests *****************************************************************/
+
+// TODO(tetsui): Following tests are not yet ported from NotificationViewTest.
+// * CreateOrUpdateTestSettingsButton
+// * TestLineLimits
+// * TestImageSizing
+// * SettingsButtonTest
+// * ViewOrderingTest
+// * FormatContextMessageTest
+
+TEST_F(NotificationViewMDTest, CreateOrUpdateTest) {
+  EXPECT_NE(nullptr, notification_view()->title_view_);
+  EXPECT_NE(nullptr, notification_view()->message_view_);
+  EXPECT_NE(nullptr, notification_view()->icon_view_);
+  EXPECT_NE(nullptr, notification_view()->image_view_);
+
+  notification()->set_image(gfx::Image());
+  notification()->set_title(base::string16());
+  notification()->set_message(base::string16());
+  notification()->set_icon(gfx::Image());
+
+  notification_view()->CreateOrUpdateViews(*notification());
+
+  EXPECT_EQ(nullptr, notification_view()->title_view_);
+  EXPECT_EQ(nullptr, notification_view()->message_view_);
+  EXPECT_EQ(nullptr, notification_view()->image_view_);
+  // We still expect an icon view for all layouts.
+  EXPECT_NE(nullptr, notification_view()->icon_view_);
+}
+
+TEST_F(NotificationViewMDTest, TestIconSizing) {
+  // TODO(tetsui): Remove duplicated integer literal in CreateOrUpdateIconView.
+  const int kNotificationIconSize = 30;
+
+  notification()->set_type(NOTIFICATION_TYPE_SIMPLE);
+  ProportionalImageView* view = notification_view()->icon_view_;
+
+  // Icons smaller than the maximum size should remain unscaled.
+  notification()->set_icon(
+      CreateTestImage(kNotificationIconSize / 2, kNotificationIconSize / 4));
+  UpdateNotificationViews();
+  EXPECT_EQ(gfx::Size(kNotificationIconSize / 2, kNotificationIconSize / 4)
+                .ToString(),
+            GetImagePaintSize(view).ToString());
+
+  // Icons of exactly the intended icon size should remain unscaled.
+  notification()->set_icon(
+      CreateTestImage(kNotificationIconSize, kNotificationIconSize));
+  UpdateNotificationViews();
+  EXPECT_EQ(gfx::Size(kNotificationIconSize, kNotificationIconSize).ToString(),
+            GetImagePaintSize(view).ToString());
+
+  // Icons over the maximum size should be scaled down, maintaining proportions.
+  notification()->set_icon(
+      CreateTestImage(2 * kNotificationIconSize, 2 * kNotificationIconSize));
+  UpdateNotificationViews();
+  EXPECT_EQ(gfx::Size(kNotificationIconSize, kNotificationIconSize).ToString(),
+            GetImagePaintSize(view).ToString());
+
+  notification()->set_icon(
+      CreateTestImage(4 * kNotificationIconSize, 2 * kNotificationIconSize));
+  UpdateNotificationViews();
+  EXPECT_EQ(
+      gfx::Size(kNotificationIconSize, kNotificationIconSize / 2).ToString(),
+      GetImagePaintSize(view).ToString());
+}
+
+TEST_F(NotificationViewMDTest, UpdateButtonsStateTest) {
+  notification()->set_buttons(CreateButtons(2));
+  notification_view()->CreateOrUpdateViews(*notification());
+  widget()->Show();
+
+  // Action buttons are hidden by collapsed state.
+  if (!notification_view()->expanded_)
+    notification_view()->ToggleExpanded();
+  EXPECT_TRUE(notification_view()->actions_row_->visible());
+
+  EXPECT_EQ(views::CustomButton::STATE_NORMAL,
+            notification_view()->action_buttons_[0]->state());
+
+  // Now construct a mouse move event 1 pixel inside the boundary of the action
+  // button.
+  gfx::Point cursor_location(1, 1);
+  views::View::ConvertPointToWidget(notification_view()->action_buttons_[0],
+                                    &cursor_location);
+  ui::MouseEvent move(ui::ET_MOUSE_MOVED, cursor_location, cursor_location,
+                      ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
+  widget()->OnMouseEvent(&move);
+
+  EXPECT_EQ(views::CustomButton::STATE_HOVERED,
+            notification_view()->action_buttons_[0]->state());
+
+  notification_view()->CreateOrUpdateViews(*notification());
+
+  EXPECT_EQ(views::CustomButton::STATE_HOVERED,
+            notification_view()->action_buttons_[0]->state());
+
+  // Now construct a mouse move event 1 pixel outside the boundary of the
+  // widget.
+  cursor_location = gfx::Point(-1, -1);
+  move = ui::MouseEvent(ui::ET_MOUSE_MOVED, cursor_location, cursor_location,
+                        ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
+  widget()->OnMouseEvent(&move);
+
+  EXPECT_EQ(views::CustomButton::STATE_NORMAL,
+            notification_view()->action_buttons_[0]->state());
+}
+
+TEST_F(NotificationViewMDTest, UpdateButtonCountTest) {
+  notification()->set_buttons(CreateButtons(2));
+  notification_view()->UpdateWithNotification(*notification());
+  widget()->Show();
+
+  // Action buttons are hidden by collapsed state.
+  if (!notification_view()->expanded_)
+    notification_view()->ToggleExpanded();
+  EXPECT_TRUE(notification_view()->actions_row_->visible());
+
+  EXPECT_EQ(views::CustomButton::STATE_NORMAL,
+            notification_view()->action_buttons_[0]->state());
+  EXPECT_EQ(views::CustomButton::STATE_NORMAL,
+            notification_view()->action_buttons_[1]->state());
+
+  // Now construct a mouse move event 1 pixel inside the boundary of the action
+  // button.
+  gfx::Point cursor_location(1, 1);
+  views::View::ConvertPointToScreen(notification_view()->action_buttons_[0],
+                                    &cursor_location);
+  ui::MouseEvent move(ui::ET_MOUSE_MOVED, cursor_location, cursor_location,
+                      ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
+  ui::EventDispatchDetails details =
+      views::test::WidgetTest::GetEventSink(widget())->OnEventFromSource(&move);
+  EXPECT_FALSE(details.dispatcher_destroyed);
+
+  EXPECT_EQ(views::CustomButton::STATE_HOVERED,
+            notification_view()->action_buttons_[0]->state());
+  EXPECT_EQ(views::CustomButton::STATE_NORMAL,
+            notification_view()->action_buttons_[1]->state());
+
+  notification()->set_buttons(CreateButtons(1));
+  notification_view()->UpdateWithNotification(*notification());
+
+  EXPECT_EQ(views::CustomButton::STATE_HOVERED,
+            notification_view()->action_buttons_[0]->state());
+  EXPECT_EQ(1u, notification_view()->action_buttons_.size());
+
+  // Now construct a mouse move event 1 pixel outside the boundary of the
+  // widget.
+  cursor_location = gfx::Point(-1, -1);
+  move = ui::MouseEvent(ui::ET_MOUSE_MOVED, cursor_location, cursor_location,
+                        ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
+  widget()->OnMouseEvent(&move);
+
+  EXPECT_EQ(views::CustomButton::STATE_NORMAL,
+            notification_view()->action_buttons_[0]->state());
+}
+
+TEST_F(NotificationViewMDTest, SlideOut) {
+  ui::ScopedAnimationDurationScaleMode zero_duration_scope(
+      ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
+
+  UpdateNotificationViews();
+  std::string notification_id = notification()->id();
+
+  BeginScroll();
+  ScrollBy(-10);
+  EXPECT_FALSE(IsRemoved(notification_id));
+  EXPECT_EQ(-10.f, GetNotificationSlideAmount());
+  EndScroll();
+  EXPECT_FALSE(IsRemoved(notification_id));
+  EXPECT_EQ(0.f, GetNotificationSlideAmount());
+
+  BeginScroll();
+  ScrollBy(-200);
+  EXPECT_FALSE(IsRemoved(notification_id));
+  EXPECT_EQ(-200.f, GetNotificationSlideAmount());
+  EndScroll();
+  EXPECT_TRUE(IsRemoved(notification_id));
+}
+
+TEST_F(NotificationViewMDTest, SlideOutNested) {
+  ui::ScopedAnimationDurationScaleMode zero_duration_scope(
+      ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
+
+  UpdateNotificationViews();
+  notification_view()->SetIsNested();
+  std::string notification_id = notification()->id();
+
+  BeginScroll();
+  ScrollBy(-10);
+  EXPECT_FALSE(IsRemoved(notification_id));
+  EXPECT_EQ(-10.f, GetNotificationSlideAmount());
+  EndScroll();
+  EXPECT_FALSE(IsRemoved(notification_id));
+  EXPECT_EQ(0.f, GetNotificationSlideAmount());
+
+  BeginScroll();
+  ScrollBy(-200);
+  EXPECT_FALSE(IsRemoved(notification_id));
+  EXPECT_EQ(-200.f, GetNotificationSlideAmount());
+  EndScroll();
+  EXPECT_TRUE(IsRemoved(notification_id));
+}
+
+// Pinning notification is ChromeOS only feature.
+#if defined(OS_CHROMEOS)
+
+TEST_F(NotificationViewMDTest, SlideOutPinned) {
+  ui::ScopedAnimationDurationScaleMode zero_duration_scope(
+      ui::ScopedAnimationDurationScaleMode::ZERO_DURATION);
+
+  notification()->set_pinned(true);
+  UpdateNotificationViews();
+  std::string notification_id = notification()->id();
+
+  BeginScroll();
+  ScrollBy(-200);
+  EXPECT_FALSE(IsRemoved(notification_id));
+  EXPECT_LT(-200.f, GetNotificationSlideAmount());
+  EndScroll();
+  EXPECT_FALSE(IsRemoved(notification_id));
+}
+
+TEST_F(NotificationViewMDTest, Pinned) {
+  notification()->set_pinned(true);
+
+  UpdateNotificationViews();
+  EXPECT_FALSE(GetCloseButton()->visible());
+}
+
+#endif  // defined(OS_CHROMEOS)
+
+}  // namespace message_center
diff --git a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js
index e043933c..85dca03e 100644
--- a/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js
+++ b/ui/webui/resources/cr_elements/cr_dialog/cr_dialog.js
@@ -110,7 +110,8 @@
     var topMarker = this.$.bodyTopMarker;
 
     var callback = function(entries) {
-      assert(entries.length <= 2);
+      // In some rare cases, there could be more than one entry per observed
+      // element, in which case the last entry's result stands.
       for (var i = 0; i < entries.length; i++) {
         var target = entries[i].target;
         assert(target == bottomMarker || target == topMarker);